1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
 598   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 599   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 600   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 601 
 602   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 603 
 604   case vmIntrinsics::_aescrypt_encryptBlock:
 605   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 606 
 607   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 608   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 609     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 612   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 613     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 614 
 615   case vmIntrinsics::_counterMode_AESCrypt:
 616     return inline_counterMode_AESCrypt(intrinsic_id());
 617 
 618   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 619     return inline_galoisCounterMode_AESCrypt();
 620 
 621   case vmIntrinsics::_md5_implCompress:
 622   case vmIntrinsics::_sha_implCompress:
 623   case vmIntrinsics::_sha2_implCompress:
 624   case vmIntrinsics::_sha5_implCompress:
 625   case vmIntrinsics::_sha3_implCompress:
 626     return inline_digestBase_implCompress(intrinsic_id());
 627   case vmIntrinsics::_double_keccak:
 628     return inline_double_keccak();
 629 
 630   case vmIntrinsics::_digestBase_implCompressMB:
 631     return inline_digestBase_implCompressMB(predicate);
 632 
 633   case vmIntrinsics::_multiplyToLen:
 634     return inline_multiplyToLen();
 635 
 636   case vmIntrinsics::_squareToLen:
 637     return inline_squareToLen();
 638 
 639   case vmIntrinsics::_mulAdd:
 640     return inline_mulAdd();
 641 
 642   case vmIntrinsics::_montgomeryMultiply:
 643     return inline_montgomeryMultiply();
 644   case vmIntrinsics::_montgomerySquare:
 645     return inline_montgomerySquare();
 646 
 647   case vmIntrinsics::_bigIntegerRightShiftWorker:
 648     return inline_bigIntegerShift(true);
 649   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 650     return inline_bigIntegerShift(false);
 651 
 652   case vmIntrinsics::_vectorizedMismatch:
 653     return inline_vectorizedMismatch();
 654 
 655   case vmIntrinsics::_ghash_processBlocks:
 656     return inline_ghash_processBlocks();
 657   case vmIntrinsics::_chacha20Block:
 658     return inline_chacha20Block();
 659   case vmIntrinsics::_kyberNtt:
 660     return inline_kyberNtt();
 661   case vmIntrinsics::_kyberInverseNtt:
 662     return inline_kyberInverseNtt();
 663   case vmIntrinsics::_kyberNttMult:
 664     return inline_kyberNttMult();
 665   case vmIntrinsics::_kyberAddPoly_2:
 666     return inline_kyberAddPoly_2();
 667   case vmIntrinsics::_kyberAddPoly_3:
 668     return inline_kyberAddPoly_3();
 669   case vmIntrinsics::_kyber12To16:
 670     return inline_kyber12To16();
 671   case vmIntrinsics::_kyberBarrettReduce:
 672     return inline_kyberBarrettReduce();
 673   case vmIntrinsics::_dilithiumAlmostNtt:
 674     return inline_dilithiumAlmostNtt();
 675   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 676     return inline_dilithiumAlmostInverseNtt();
 677   case vmIntrinsics::_dilithiumNttMult:
 678     return inline_dilithiumNttMult();
 679   case vmIntrinsics::_dilithiumMontMulByConstant:
 680     return inline_dilithiumMontMulByConstant();
 681   case vmIntrinsics::_dilithiumDecomposePoly:
 682     return inline_dilithiumDecomposePoly();
 683   case vmIntrinsics::_base64_encodeBlock:
 684     return inline_base64_encodeBlock();
 685   case vmIntrinsics::_base64_decodeBlock:
 686     return inline_base64_decodeBlock();
 687   case vmIntrinsics::_poly1305_processBlocks:
 688     return inline_poly1305_processBlocks();
 689   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 690     return inline_intpoly_montgomeryMult_P256();
 691   case vmIntrinsics::_intpoly_assign:
 692     return inline_intpoly_assign();
 693   case vmIntrinsics::_encodeISOArray:
 694   case vmIntrinsics::_encodeByteISOArray:
 695     return inline_encodeISOArray(false);
 696   case vmIntrinsics::_encodeAsciiArray:
 697     return inline_encodeISOArray(true);
 698 
 699   case vmIntrinsics::_updateCRC32:
 700     return inline_updateCRC32();
 701   case vmIntrinsics::_updateBytesCRC32:
 702     return inline_updateBytesCRC32();
 703   case vmIntrinsics::_updateByteBufferCRC32:
 704     return inline_updateByteBufferCRC32();
 705 
 706   case vmIntrinsics::_updateBytesCRC32C:
 707     return inline_updateBytesCRC32C();
 708   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 709     return inline_updateDirectByteBufferCRC32C();
 710 
 711   case vmIntrinsics::_updateBytesAdler32:
 712     return inline_updateBytesAdler32();
 713   case vmIntrinsics::_updateByteBufferAdler32:
 714     return inline_updateByteBufferAdler32();
 715 
 716   case vmIntrinsics::_profileBoolean:
 717     return inline_profileBoolean();
 718   case vmIntrinsics::_isCompileConstant:
 719     return inline_isCompileConstant();
 720 
 721   case vmIntrinsics::_countPositives:
 722     return inline_countPositives();
 723 
 724   case vmIntrinsics::_fmaD:
 725   case vmIntrinsics::_fmaF:
 726     return inline_fma(intrinsic_id());
 727 
 728   case vmIntrinsics::_isDigit:
 729   case vmIntrinsics::_isLowerCase:
 730   case vmIntrinsics::_isUpperCase:
 731   case vmIntrinsics::_isWhitespace:
 732     return inline_character_compare(intrinsic_id());
 733 
 734   case vmIntrinsics::_min:
 735   case vmIntrinsics::_max:
 736   case vmIntrinsics::_min_strict:
 737   case vmIntrinsics::_max_strict:
 738   case vmIntrinsics::_minL:
 739   case vmIntrinsics::_maxL:
 740   case vmIntrinsics::_minF:
 741   case vmIntrinsics::_maxF:
 742   case vmIntrinsics::_minD:
 743   case vmIntrinsics::_maxD:
 744   case vmIntrinsics::_minF_strict:
 745   case vmIntrinsics::_maxF_strict:
 746   case vmIntrinsics::_minD_strict:
 747   case vmIntrinsics::_maxD_strict:
 748     return inline_min_max(intrinsic_id());
 749 
 750   case vmIntrinsics::_VectorUnaryOp:
 751     return inline_vector_nary_operation(1);
 752   case vmIntrinsics::_VectorBinaryOp:
 753     return inline_vector_nary_operation(2);
 754   case vmIntrinsics::_VectorUnaryLibOp:
 755     return inline_vector_call(1);
 756   case vmIntrinsics::_VectorBinaryLibOp:
 757     return inline_vector_call(2);
 758   case vmIntrinsics::_VectorTernaryOp:
 759     return inline_vector_nary_operation(3);
 760   case vmIntrinsics::_VectorFromBitsCoerced:
 761     return inline_vector_frombits_coerced();
 762   case vmIntrinsics::_VectorMaskOp:
 763     return inline_vector_mask_operation();
 764   case vmIntrinsics::_VectorLoadOp:
 765     return inline_vector_mem_operation(/*is_store=*/false);
 766   case vmIntrinsics::_VectorLoadMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store*/false);
 768   case vmIntrinsics::_VectorStoreOp:
 769     return inline_vector_mem_operation(/*is_store=*/true);
 770   case vmIntrinsics::_VectorStoreMaskedOp:
 771     return inline_vector_mem_masked_operation(/*is_store=*/true);
 772   case vmIntrinsics::_VectorGatherOp:
 773     return inline_vector_gather_scatter(/*is_scatter*/ false);
 774   case vmIntrinsics::_VectorScatterOp:
 775     return inline_vector_gather_scatter(/*is_scatter*/ true);
 776   case vmIntrinsics::_VectorReductionCoerced:
 777     return inline_vector_reduction();
 778   case vmIntrinsics::_VectorTest:
 779     return inline_vector_test();
 780   case vmIntrinsics::_VectorBlend:
 781     return inline_vector_blend();
 782   case vmIntrinsics::_VectorRearrange:
 783     return inline_vector_rearrange();
 784   case vmIntrinsics::_VectorSelectFrom:
 785     return inline_vector_select_from();
 786   case vmIntrinsics::_VectorCompare:
 787     return inline_vector_compare();
 788   case vmIntrinsics::_VectorBroadcastInt:
 789     return inline_vector_broadcast_int();
 790   case vmIntrinsics::_VectorConvert:
 791     return inline_vector_convert();
 792   case vmIntrinsics::_VectorInsert:
 793     return inline_vector_insert();
 794   case vmIntrinsics::_VectorExtract:
 795     return inline_vector_extract();
 796   case vmIntrinsics::_VectorCompressExpand:
 797     return inline_vector_compress_expand();
 798   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 799     return inline_vector_select_from_two_vectors();
 800   case vmIntrinsics::_IndexVector:
 801     return inline_index_vector();
 802   case vmIntrinsics::_IndexPartiallyInUpperRange:
 803     return inline_index_partially_in_upper_range();
 804 
 805   case vmIntrinsics::_getObjectSize:
 806     return inline_getObjectSize();
 807 
 808   case vmIntrinsics::_blackhole:
 809     return inline_blackhole();
 810 
 811   default:
 812     // If you get here, it may be that someone has added a new intrinsic
 813     // to the list in vmIntrinsics.hpp without implementing it here.
 814 #ifndef PRODUCT
 815     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 816       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 817                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 818     }
 819 #endif
 820     return false;
 821   }
 822 }
 823 
 824 Node* LibraryCallKit::try_to_predicate(int predicate) {
 825   if (!jvms()->has_method()) {
 826     // Root JVMState has a null method.
 827     assert(map()->memory()->Opcode() == Op_Parm, "");
 828     // Insert the memory aliasing node
 829     set_all_memory(reset_memory());
 830   }
 831   assert(merged_memory(), "");
 832 
 833   switch (intrinsic_id()) {
 834   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 835     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 836   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 837     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 839     return inline_electronicCodeBook_AESCrypt_predicate(false);
 840   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 841     return inline_electronicCodeBook_AESCrypt_predicate(true);
 842   case vmIntrinsics::_counterMode_AESCrypt:
 843     return inline_counterMode_AESCrypt_predicate();
 844   case vmIntrinsics::_digestBase_implCompressMB:
 845     return inline_digestBase_implCompressMB_predicate(predicate);
 846   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 847     return inline_galoisCounterMode_AESCrypt_predicate();
 848 
 849   default:
 850     // If you get here, it may be that someone has added a new intrinsic
 851     // to the list in vmIntrinsics.hpp without implementing it here.
 852 #ifndef PRODUCT
 853     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 854       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 855                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 856     }
 857 #endif
 858     Node* slow_ctl = control();
 859     set_control(top()); // No fast path intrinsic
 860     return slow_ctl;
 861   }
 862 }
 863 
 864 //------------------------------set_result-------------------------------
 865 // Helper function for finishing intrinsics.
 866 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 867   record_for_igvn(region);
 868   set_control(_gvn.transform(region));
 869   set_result( _gvn.transform(value));
 870   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 871 }
 872 
 873 RegionNode* LibraryCallKit::create_bailout() {
 874   RegionNode* bailout = new RegionNode(1);
 875   record_for_igvn(bailout);
 876   return bailout;
 877 }
 878 
 879 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
 880   if (bailout->req() > 1) {
 881     bailout = _gvn.transform(bailout)->as_Region();
 882     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 883     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 884     C->root()->add_req(halt);
 885   }
 886   return stopped();
 887 }
 888 
 889 //------------------------------generate_guard---------------------------
 890 // Helper function for generating guarded fast-slow graph structures.
 891 // The given 'test', if true, guards a slow path.  If the test fails
 892 // then a fast path can be taken.  (We generally hope it fails.)
 893 // In all cases, GraphKit::control() is updated to the fast path.
 894 // The returned value represents the control for the slow path.
 895 // The return value is never 'top'; it is either a valid control
 896 // or null if it is obvious that the slow path can never be taken.
 897 // Also, if region and the slow control are not null, the slow edge
 898 // is appended to the region.
 899 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 900   if (stopped()) {
 901     // Already short circuited.
 902     return nullptr;
 903   }
 904 
 905   // Build an if node and its projections.
 906   // If test is true we take the slow path, which we assume is uncommon.
 907   if (_gvn.type(test) == TypeInt::ZERO) {
 908     // The slow branch is never taken.  No need to build this guard.
 909     return nullptr;
 910   }
 911 
 912   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 913 
 914   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 915   if (if_slow == top()) {
 916     // The slow branch is never taken.  No need to build this guard.
 917     return nullptr;
 918   }
 919 
 920   if (region != nullptr)
 921     region->add_req(if_slow);
 922 
 923   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 924   set_control(if_fast);
 925 
 926   return if_slow;
 927 }
 928 
 929 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 930   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 931 }
 932 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 933   return generate_guard(test, region, PROB_FAIR);
 934 }
 935 
 936 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 937                                                      Node** pos_index, bool with_opaque) {
 938   if (stopped())
 939     return nullptr;                // already stopped
 940   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 941     return nullptr;                // index is already adequately typed
 942   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 943   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 944   if (with_opaque) {
 945     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 946   }
 947   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 948   if (is_neg != nullptr && pos_index != nullptr) {
 949     // Emulate effect of Parse::adjust_map_after_if.
 950     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 951     (*pos_index) = _gvn.transform(ccast);
 952   }
 953   return is_neg;
 954 }
 955 
 956 // Make sure that 'position' is a valid limit index, in [0..length].
 957 // There are two equivalent plans for checking this:
 958 //   A. (offset + copyLength)  unsigned<=  arrayLength
 959 //   B. offset  <=  (arrayLength - copyLength)
 960 // We require that all of the values above, except for the sum and
 961 // difference, are already known to be non-negative.
 962 // Plan A is robust in the face of overflow, if offset and copyLength
 963 // are both hugely positive.
 964 //
 965 // Plan B is less direct and intuitive, but it does not overflow at
 966 // all, since the difference of two non-negatives is always
 967 // representable.  Whenever Java methods must perform the equivalent
 968 // check they generally use Plan B instead of Plan A.
 969 // For the moment we use Plan A.
 970 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 971                                                   Node* subseq_length,
 972                                                   Node* array_length,
 973                                                   RegionNode* region,
 974                                                   bool with_opaque) {
 975   if (stopped())
 976     return nullptr;                // already stopped
 977   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 978   if (zero_offset && subseq_length->eqv_uncast(array_length))
 979     return nullptr;                // common case of whole-array copy
 980   Node* last = subseq_length;
 981   if (!zero_offset)             // last += offset
 982     last = _gvn.transform(new AddINode(last, offset));
 983   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 984   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 985   if (with_opaque) {
 986     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 987   }
 988   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 989   return is_over;
 990 }
 991 
 992 // Emit range checks for the given String.value byte array
 993 void LibraryCallKit::generate_string_range_check(Node* array,
 994                                                  Node* offset,
 995                                                  Node* count,
 996                                                  bool char_count,
 997                                                  RegionNode* region) {
 998   if (stopped()) {
 999     return; // already stopped
1000   }
1001   if (char_count) {
1002     // Convert char count to byte count
1003     count = _gvn.transform(new LShiftINode(count, intcon(1)));
1004   }
1005   // Offset and count must not be negative
1006   generate_negative_guard(offset, region, nullptr, true);
1007   generate_negative_guard(count, region, nullptr, true);
1008   // Offset + count must not exceed length of array
1009   generate_limit_guard(offset, count, load_array_length(array), region, true);
1010 }
1011 
1012 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1013                                             bool is_immutable) {
1014   ciKlass* thread_klass = env()->Thread_klass();
1015   const Type* thread_type
1016     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1017 
1018   Node* thread = _gvn.transform(new ThreadLocalNode());
1019   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1020   tls_output = thread;
1021 
1022   Node* thread_obj_handle
1023     = (is_immutable
1024       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1025         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1026       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1027   thread_obj_handle = _gvn.transform(thread_obj_handle);
1028 
1029   DecoratorSet decorators = IN_NATIVE;
1030   if (is_immutable) {
1031     decorators |= C2_IMMUTABLE_MEMORY;
1032   }
1033   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1034 }
1035 
1036 //--------------------------generate_current_thread--------------------
1037 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1039                                /*is_immutable*/false);
1040 }
1041 
1042 //--------------------------generate_virtual_thread--------------------
1043 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1044   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1045                                !C->method()->changes_current_thread());
1046 }
1047 
1048 //------------------------------make_string_method_node------------------------
1049 // Helper method for String intrinsic functions. This version is called with
1050 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1051 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1052 // containing the lengths of str1 and str2.
1053 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1054   Node* result = nullptr;
1055   switch (opcode) {
1056   case Op_StrIndexOf:
1057     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1058                                 str1_start, cnt1, str2_start, cnt2, ae);
1059     break;
1060   case Op_StrComp:
1061     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1062                              str1_start, cnt1, str2_start, cnt2, ae);
1063     break;
1064   case Op_StrEquals:
1065     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1066     // Use the constant length if there is one because optimized match rule may exist.
1067     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1068                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1069     break;
1070   default:
1071     ShouldNotReachHere();
1072     return nullptr;
1073   }
1074 
1075   // All these intrinsics have checks.
1076   C->set_has_split_ifs(true); // Has chance for split-if optimization
1077   clear_upper_avx();
1078 
1079   return _gvn.transform(result);
1080 }
1081 
1082 //------------------------------inline_string_compareTo------------------------
1083 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1084   Node* arg1 = argument(0);
1085   Node* arg2 = argument(1);
1086 
1087   arg1 = must_be_not_null(arg1, true);
1088   arg2 = must_be_not_null(arg2, true);
1089 
1090   // Get start addr and length of first argument
1091   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1092   Node* arg1_cnt    = load_array_length(arg1);
1093 
1094   // Get start addr and length of second argument
1095   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1096   Node* arg2_cnt    = load_array_length(arg2);
1097 
1098   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1099   set_result(result);
1100   return true;
1101 }
1102 
1103 //------------------------------inline_string_equals------------------------
1104 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1105   Node* arg1 = argument(0);
1106   Node* arg2 = argument(1);
1107 
1108   // paths (plus control) merge
1109   RegionNode* region = new RegionNode(3);
1110   Node* phi = new PhiNode(region, TypeInt::BOOL);
1111 
1112   if (!stopped()) {
1113 
1114     arg1 = must_be_not_null(arg1, true);
1115     arg2 = must_be_not_null(arg2, true);
1116 
1117     // Get start addr and length of first argument
1118     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1119     Node* arg1_cnt    = load_array_length(arg1);
1120 
1121     // Get start addr and length of second argument
1122     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1123     Node* arg2_cnt    = load_array_length(arg2);
1124 
1125     // Check for arg1_cnt != arg2_cnt
1126     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1127     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1128     Node* if_ne = generate_slow_guard(bol, nullptr);
1129     if (if_ne != nullptr) {
1130       phi->init_req(2, intcon(0));
1131       region->init_req(2, if_ne);
1132     }
1133 
1134     // Check for count == 0 is done by assembler code for StrEquals.
1135 
1136     if (!stopped()) {
1137       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1138       phi->init_req(1, equals);
1139       region->init_req(1, control());
1140     }
1141   }
1142 
1143   // post merge
1144   set_control(_gvn.transform(region));
1145   record_for_igvn(region);
1146 
1147   set_result(_gvn.transform(phi));
1148   return true;
1149 }
1150 
1151 //------------------------------inline_array_equals----------------------------
1152 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1153   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1154   Node* arg1 = argument(0);
1155   Node* arg2 = argument(1);
1156 
1157   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1158   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1159   clear_upper_avx();
1160 
1161   return true;
1162 }
1163 
1164 
1165 //------------------------------inline_countPositives------------------------------
1166 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1167 bool LibraryCallKit::inline_countPositives() {
1168   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1169   // no receiver since it is static method
1170   Node* ba         = argument(0);
1171   Node* offset     = argument(1);
1172   Node* len        = argument(2);
1173 
1174   ba = must_be_not_null(ba, true);
1175   RegionNode* bailout = create_bailout();
1176   generate_string_range_check(ba, offset, len, false, bailout);
1177   if (check_bailout(bailout)) {
1178     return true;
1179   }
1180 
1181   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1182   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1183   set_result(_gvn.transform(result));
1184   clear_upper_avx();
1185   return true;
1186 }
1187 
1188 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1189   Node* index = argument(0);
1190   Node* length = bt == T_INT ? argument(1) : argument(2);
1191   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1192     return false;
1193   }
1194 
1195   // check that length is positive
1196   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1197   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1198 
1199   {
1200     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1201     uncommon_trap(Deoptimization::Reason_intrinsic,
1202                   Deoptimization::Action_make_not_entrant);
1203   }
1204 
1205   if (stopped()) {
1206     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1207     return true;
1208   }
1209 
1210   // length is now known positive, add a cast node to make this explicit
1211   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1212   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1213       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1214       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1215   casted_length = _gvn.transform(casted_length);
1216   replace_in_map(length, casted_length);
1217   length = casted_length;
1218 
1219   // Use an unsigned comparison for the range check itself
1220   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1221   BoolTest::mask btest = BoolTest::lt;
1222   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1223   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1224   _gvn.set_type(rc, rc->Value(&_gvn));
1225   if (!rc_bool->is_Con()) {
1226     record_for_igvn(rc);
1227   }
1228   set_control(_gvn.transform(new IfTrueNode(rc)));
1229   {
1230     PreserveJVMState pjvms(this);
1231     set_control(_gvn.transform(new IfFalseNode(rc)));
1232     uncommon_trap(Deoptimization::Reason_range_check,
1233                   Deoptimization::Action_make_not_entrant);
1234   }
1235 
1236   if (stopped()) {
1237     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1238     return true;
1239   }
1240 
1241   // index is now known to be >= 0 and < length, cast it
1242   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1243       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1244       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1245   result = _gvn.transform(result);
1246   set_result(result);
1247   replace_in_map(index, result);
1248   return true;
1249 }
1250 
1251 //------------------------------inline_string_indexOf------------------------
1252 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1253   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1254     return false;
1255   }
1256   Node* src = argument(0);
1257   Node* tgt = argument(1);
1258 
1259   // Make the merge point
1260   RegionNode* result_rgn = new RegionNode(4);
1261   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1262 
1263   src = must_be_not_null(src, true);
1264   tgt = must_be_not_null(tgt, true);
1265 
1266   // Get start addr and length of source string
1267   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1268   Node* src_count = load_array_length(src);
1269 
1270   // Get start addr and length of substring
1271   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1272   Node* tgt_count = load_array_length(tgt);
1273 
1274   Node* result = nullptr;
1275   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1276 
1277   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1278     // Divide src size by 2 if String is UTF16 encoded
1279     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1280   }
1281   if (ae == StrIntrinsicNode::UU) {
1282     // Divide substring size by 2 if String is UTF16 encoded
1283     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1284   }
1285 
1286   if (call_opt_stub) {
1287     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1288                                    StubRoutines::_string_indexof_array[ae],
1289                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1290                                    src_count, tgt_start, tgt_count);
1291     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1292   } else {
1293     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1294                                result_rgn, result_phi, ae);
1295   }
1296   if (result != nullptr) {
1297     result_phi->init_req(3, result);
1298     result_rgn->init_req(3, control());
1299   }
1300   set_control(_gvn.transform(result_rgn));
1301   record_for_igvn(result_rgn);
1302   set_result(_gvn.transform(result_phi));
1303 
1304   return true;
1305 }
1306 
1307 //-----------------------------inline_string_indexOfI-----------------------
1308 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1309   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1310     return false;
1311   }
1312 
1313   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1314   Node* src         = argument(0); // byte[]
1315   Node* src_count   = argument(1); // char count
1316   Node* tgt         = argument(2); // byte[]
1317   Node* tgt_count   = argument(3); // char count
1318   Node* from_index  = argument(4); // char index
1319 
1320   src = must_be_not_null(src, true);
1321   tgt = must_be_not_null(tgt, true);
1322 
1323   // Multiply byte array index by 2 if String is UTF16 encoded
1324   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1325   src_count = _gvn.transform(new SubINode(src_count, from_index));
1326   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1327   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1328 
1329   // Range checks
1330   RegionNode* bailout = create_bailout();
1331   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1332   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1333   if (check_bailout(bailout)) {
1334     return true;
1335   }
1336 
1337   RegionNode* region = new RegionNode(5);
1338   Node* phi = new PhiNode(region, TypeInt::INT);
1339   Node* result = nullptr;
1340 
1341   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1342 
1343   if (call_opt_stub) {
1344     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1345                                    StubRoutines::_string_indexof_array[ae],
1346                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1347                                    src_count, tgt_start, tgt_count);
1348     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1349   } else {
1350     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1351                                region, phi, ae);
1352   }
1353   if (result != nullptr) {
1354     // The result is index relative to from_index if substring was found, -1 otherwise.
1355     // Generate code which will fold into cmove.
1356     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1357     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1358 
1359     Node* if_lt = generate_slow_guard(bol, nullptr);
1360     if (if_lt != nullptr) {
1361       // result == -1
1362       phi->init_req(3, result);
1363       region->init_req(3, if_lt);
1364     }
1365     if (!stopped()) {
1366       result = _gvn.transform(new AddINode(result, from_index));
1367       phi->init_req(4, result);
1368       region->init_req(4, control());
1369     }
1370   }
1371 
1372   set_control(_gvn.transform(region));
1373   record_for_igvn(region);
1374   set_result(_gvn.transform(phi));
1375   clear_upper_avx();
1376 
1377   return true;
1378 }
1379 
1380 // Create StrIndexOfNode with fast path checks
1381 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1382                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1383   // Check for substr count > string count
1384   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1385   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1386   Node* if_gt = generate_slow_guard(bol, nullptr);
1387   if (if_gt != nullptr) {
1388     phi->init_req(1, intcon(-1));
1389     region->init_req(1, if_gt);
1390   }
1391   if (!stopped()) {
1392     // Check for substr count == 0
1393     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1394     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1395     Node* if_zero = generate_slow_guard(bol, nullptr);
1396     if (if_zero != nullptr) {
1397       phi->init_req(2, intcon(0));
1398       region->init_req(2, if_zero);
1399     }
1400   }
1401   if (!stopped()) {
1402     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1403   }
1404   return nullptr;
1405 }
1406 
1407 //-----------------------------inline_string_indexOfChar-----------------------
1408 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1409   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1410     return false;
1411   }
1412   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1413     return false;
1414   }
1415   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1416   Node* src         = argument(0); // byte[]
1417   Node* int_ch      = argument(1);
1418   Node* from_index  = argument(2);
1419   Node* max         = argument(3);
1420 
1421   src = must_be_not_null(src, true);
1422 
1423   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1424   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1425   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1426 
1427   // Range checks
1428   RegionNode* bailout = create_bailout();
1429   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1430   if (check_bailout(bailout)) {
1431     return true;
1432   }
1433 
1434   // Check for int_ch >= 0
1435   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1436   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1437   {
1438     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1439     uncommon_trap(Deoptimization::Reason_intrinsic,
1440                   Deoptimization::Action_maybe_recompile);
1441   }
1442   if (stopped()) {
1443     return true;
1444   }
1445 
1446   RegionNode* region = new RegionNode(3);
1447   Node* phi = new PhiNode(region, TypeInt::INT);
1448 
1449   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1450   C->set_has_split_ifs(true); // Has chance for split-if optimization
1451   _gvn.transform(result);
1452 
1453   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1454   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1455 
1456   Node* if_lt = generate_slow_guard(bol, nullptr);
1457   if (if_lt != nullptr) {
1458     // result == -1
1459     phi->init_req(2, result);
1460     region->init_req(2, if_lt);
1461   }
1462   if (!stopped()) {
1463     result = _gvn.transform(new AddINode(result, from_index));
1464     phi->init_req(1, result);
1465     region->init_req(1, control());
1466   }
1467   set_control(_gvn.transform(region));
1468   record_for_igvn(region);
1469   set_result(_gvn.transform(phi));
1470   clear_upper_avx();
1471 
1472   return true;
1473 }
1474 //---------------------------inline_string_copy---------------------
1475 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1476 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1477 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1479 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1480 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1481 bool LibraryCallKit::inline_string_copy(bool compress) {
1482   int nargs = 5;  // 2 oops, 3 ints
1483   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1484 
1485   Node* src         = argument(0);
1486   Node* src_offset  = argument(1);
1487   Node* dst         = argument(2);
1488   Node* dst_offset  = argument(3);
1489   Node* length      = argument(4);
1490 
1491   // Check for allocation before we add nodes that would confuse
1492   // tightly_coupled_allocation()
1493   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1494 
1495   // Figure out the size and type of the elements we will be copying.
1496   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1497   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1498   if (src_type == nullptr || dst_type == nullptr) {
1499     return false;
1500   }
1501   BasicType src_elem = src_type->elem()->array_element_basic_type();
1502   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1503   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1504          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1505          "Unsupported array types for inline_string_copy");
1506 
1507   src = must_be_not_null(src, true);
1508   dst = must_be_not_null(dst, true);
1509 
1510   // Convert char[] offsets to byte[] offsets
1511   bool convert_src = (compress && src_elem == T_BYTE);
1512   bool convert_dst = (!compress && dst_elem == T_BYTE);
1513   if (convert_src) {
1514     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1515   } else if (convert_dst) {
1516     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1517   }
1518 
1519   // Range checks
1520   RegionNode* bailout = create_bailout();
1521   generate_string_range_check(src, src_offset, length, convert_src, bailout);
1522   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1523   if (check_bailout(bailout)) {
1524     return true;
1525   }
1526 
1527   Node* src_start = array_element_address(src, src_offset, src_elem);
1528   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1529   // 'src_start' points to src array + scaled offset
1530   // 'dst_start' points to dst array + scaled offset
1531   Node* count = nullptr;
1532   if (compress) {
1533     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1534   } else {
1535     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1536   }
1537 
1538   if (alloc != nullptr) {
1539     if (alloc->maybe_set_complete(&_gvn)) {
1540       // "You break it, you buy it."
1541       InitializeNode* init = alloc->initialization();
1542       assert(init->is_complete(), "we just did this");
1543       init->set_complete_with_arraycopy();
1544       assert(dst->is_CheckCastPP(), "sanity");
1545       assert(dst->in(0)->in(0) == init, "dest pinned");
1546     }
1547     // Do not let stores that initialize this object be reordered with
1548     // a subsequent store that would make this object accessible by
1549     // other threads.
1550     // Record what AllocateNode this StoreStore protects so that
1551     // escape analysis can go from the MemBarStoreStoreNode to the
1552     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1553     // based on the escape status of the AllocateNode.
1554     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1555   }
1556   if (compress) {
1557     set_result(_gvn.transform(count));
1558   }
1559   clear_upper_avx();
1560 
1561   return true;
1562 }
1563 
1564 #ifdef _LP64
1565 #define XTOP ,top() /*additional argument*/
1566 #else  //_LP64
1567 #define XTOP        /*no additional argument*/
1568 #endif //_LP64
1569 
1570 //------------------------inline_string_toBytesU--------------------------
1571 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1572 bool LibraryCallKit::inline_string_toBytesU() {
1573   // Get the arguments.
1574   assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1575   Node* value     = argument(0);
1576   Node* offset    = argument(1);
1577   Node* length    = argument(2);
1578 
1579   Node* newcopy = nullptr;
1580 
1581   // Set the original stack and the reexecute bit for the interpreter to reexecute
1582   // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1583   { PreserveReexecuteState preexecs(this);
1584     jvms()->set_should_reexecute(true);
1585 
1586     value = must_be_not_null(value, true);
1587     RegionNode* bailout = create_bailout();
1588     generate_negative_guard(offset, bailout, nullptr, true);
1589     generate_negative_guard(length, bailout, nullptr, true);
1590     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1591     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1592     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1593     if (check_bailout(bailout)) {
1594       return true;
1595     }
1596 
1597     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1598     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1599     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1600     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1601     guarantee(alloc != nullptr, "created above");
1602 
1603     // Calculate starting addresses.
1604     Node* src_start = array_element_address(value, offset, T_CHAR);
1605     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1606 
1607     // Check if dst array address is aligned to HeapWordSize
1608     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1609     // If true, then check if src array address is aligned to HeapWordSize
1610     if (aligned) {
1611       const TypeInt* toffset = gvn().type(offset)->is_int();
1612       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1613                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1614     }
1615 
1616     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1617     const char* copyfunc_name = "arraycopy";
1618     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1619     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1620                       OptoRuntime::fast_arraycopy_Type(),
1621                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1622                       src_start, dst_start, ConvI2X(length) XTOP);
1623     // Do not let reads from the cloned object float above the arraycopy.
1624     if (alloc->maybe_set_complete(&_gvn)) {
1625       // "You break it, you buy it."
1626       InitializeNode* init = alloc->initialization();
1627       assert(init->is_complete(), "we just did this");
1628       init->set_complete_with_arraycopy();
1629       assert(newcopy->is_CheckCastPP(), "sanity");
1630       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1631     }
1632     // Do not let stores that initialize this object be reordered with
1633     // a subsequent store that would make this object accessible by
1634     // other threads.
1635     // Record what AllocateNode this StoreStore protects so that
1636     // escape analysis can go from the MemBarStoreStoreNode to the
1637     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1638     // based on the escape status of the AllocateNode.
1639     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1640   } // original reexecute is set back here
1641 
1642   C->set_has_split_ifs(true); // Has chance for split-if optimization
1643   if (!stopped()) {
1644     set_result(newcopy);
1645   }
1646   clear_upper_avx();
1647 
1648   return true;
1649 }
1650 
1651 //------------------------inline_string_getCharsU--------------------------
1652 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1653 bool LibraryCallKit::inline_string_getCharsU() {
1654   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1655   // Get the arguments.
1656   Node* src       = argument(0);
1657   Node* src_begin = argument(1);
1658   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1659   Node* dst       = argument(3);
1660   Node* dst_begin = argument(4);
1661 
1662   // Check for allocation before we add nodes that would confuse
1663   // tightly_coupled_allocation()
1664   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1665 
1666   // Check if a null path was taken unconditionally.
1667   src = must_be_not_null(src, true);
1668   dst = must_be_not_null(dst, true);
1669   if (stopped()) {
1670     return true;
1671   }
1672 
1673   // Get length and convert char[] offset to byte[] offset
1674   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1675   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1676 
1677   // Range checks
1678   RegionNode* bailout = create_bailout();
1679   generate_string_range_check(src, src_begin, length, true, bailout);
1680   generate_string_range_check(dst, dst_begin, length, false, bailout);
1681   if (check_bailout(bailout)) {
1682     return true;
1683   }
1684 
1685   // Calculate starting addresses.
1686   Node* src_start = array_element_address(src, src_begin, T_BYTE);
1687   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1688 
1689   // Check if array addresses are aligned to HeapWordSize
1690   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1691   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1692   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1693                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1694 
1695   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1696   const char* copyfunc_name = "arraycopy";
1697   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1698   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1699                     OptoRuntime::fast_arraycopy_Type(),
1700                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1701                     src_start, dst_start, ConvI2X(length) XTOP);
1702   // Do not let reads from the cloned object float above the arraycopy.
1703   if (alloc != nullptr) {
1704     if (alloc->maybe_set_complete(&_gvn)) {
1705       // "You break it, you buy it."
1706       InitializeNode* init = alloc->initialization();
1707       assert(init->is_complete(), "we just did this");
1708       init->set_complete_with_arraycopy();
1709       assert(dst->is_CheckCastPP(), "sanity");
1710       assert(dst->in(0)->in(0) == init, "dest pinned");
1711     }
1712     // Do not let stores that initialize this object be reordered with
1713     // a subsequent store that would make this object accessible by
1714     // other threads.
1715     // Record what AllocateNode this StoreStore protects so that
1716     // escape analysis can go from the MemBarStoreStoreNode to the
1717     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1718     // based on the escape status of the AllocateNode.
1719     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1720   } else {
1721     insert_mem_bar(Op_MemBarCPUOrder);
1722   }
1723 
1724   C->set_has_split_ifs(true); // Has chance for split-if optimization
1725   return true;
1726 }
1727 
1728 //----------------------inline_string_char_access----------------------------
1729 // Store/Load char to/from byte[] array.
1730 // static void StringUTF16.putChar(byte[] val, int index, int c)
1731 // static char StringUTF16.getChar(byte[] val, int index)
1732 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1733   Node* ch;
1734   if (is_store) {
1735     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1736     ch = argument(2);
1737   } else {
1738     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1739     ch = nullptr;
1740   }
1741   Node* value  = argument(0);
1742   Node* index  = argument(1);
1743 
1744   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1745   // correctly requires matched array shapes.
1746   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1747           "sanity: byte[] and char[] bases agree");
1748   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1749           "sanity: byte[] and char[] scales agree");
1750 
1751   // Bail when getChar over constants is requested: constant folding would
1752   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1753   // Java method would constant fold nicely instead.
1754   if (!is_store && value->is_Con() && index->is_Con()) {
1755     return false;
1756   }
1757 
1758   // Save state and restore on bailout
1759   SavedState old_state(this);
1760 
1761   value = must_be_not_null(value, true);
1762 
1763   Node* adr = array_element_address(value, index, T_CHAR);
1764   if (adr->is_top()) {
1765     return false;
1766   }
1767   old_state.discard();
1768   if (is_store) {
1769     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1770   } else {
1771     ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1772     set_result(ch);
1773   }
1774   return true;
1775 }
1776 
1777 
1778 //------------------------------inline_math-----------------------------------
1779 // public static double Math.abs(double)
1780 // public static double Math.sqrt(double)
1781 // public static double Math.log(double)
1782 // public static double Math.log10(double)
1783 // public static double Math.round(double)
1784 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1785   Node* arg = argument(0);
1786   Node* n = nullptr;
1787   switch (id) {
1788   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1789   case vmIntrinsics::_dsqrt:
1790   case vmIntrinsics::_dsqrt_strict:
1791                               n = new SqrtDNode(C, control(),  arg);  break;
1792   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1793   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1794   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1795   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1796   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1797   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1798   default:  fatal_unexpected_iid(id);  break;
1799   }
1800   set_result(_gvn.transform(n));
1801   return true;
1802 }
1803 
1804 //------------------------------inline_math-----------------------------------
1805 // public static float Math.abs(float)
1806 // public static int Math.abs(int)
1807 // public static long Math.abs(long)
1808 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1809   Node* arg = argument(0);
1810   Node* n = nullptr;
1811   switch (id) {
1812   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1813   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1814   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1815   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1816   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1817   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1818   default:  fatal_unexpected_iid(id);  break;
1819   }
1820   set_result(_gvn.transform(n));
1821   return true;
1822 }
1823 
1824 //------------------------------runtime_math-----------------------------
1825 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1826   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1827          "must be (DD)D or (D)D type");
1828 
1829   // Inputs
1830   Node* a = argument(0);
1831   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1832 
1833   const TypePtr* no_memory_effects = nullptr;
1834   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1835                                  no_memory_effects,
1836                                  a, top(), b, b ? top() : nullptr);
1837   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1838 #ifdef ASSERT
1839   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1840   assert(value_top == top(), "second value must be top");
1841 #endif
1842 
1843   set_result(value);
1844   return true;
1845 }
1846 
1847 //------------------------------inline_math_pow-----------------------------
1848 bool LibraryCallKit::inline_math_pow() {
1849   Node* base = argument(0);
1850   Node* exp = argument(2);
1851 
1852   CallNode* pow = new PowDNode(C, base, exp);
1853   set_predefined_input_for_runtime_call(pow);
1854   pow = _gvn.transform(pow)->as_CallLeafPure();
1855   set_predefined_output_for_runtime_call(pow);
1856   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1857   record_for_igvn(pow);
1858   set_result(result);
1859   return true;
1860 }
1861 
1862 //------------------------------inline_math_native-----------------------------
1863 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1864   switch (id) {
1865   case vmIntrinsics::_dsin:
1866     return StubRoutines::dsin() != nullptr ?
1867       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1868       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1869   case vmIntrinsics::_dcos:
1870     return StubRoutines::dcos() != nullptr ?
1871       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1872       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1873   case vmIntrinsics::_dtan:
1874     return StubRoutines::dtan() != nullptr ?
1875       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1876       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1877   case vmIntrinsics::_dsinh:
1878     return StubRoutines::dsinh() != nullptr ?
1879       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1880   case vmIntrinsics::_dtanh:
1881     return StubRoutines::dtanh() != nullptr ?
1882       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1883   case vmIntrinsics::_dcbrt:
1884     return StubRoutines::dcbrt() != nullptr ?
1885       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1886   case vmIntrinsics::_dexp:
1887     return StubRoutines::dexp() != nullptr ?
1888       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1889       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1890   case vmIntrinsics::_dlog:
1891     return StubRoutines::dlog() != nullptr ?
1892       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1893       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1894   case vmIntrinsics::_dlog10:
1895     return StubRoutines::dlog10() != nullptr ?
1896       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1897       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1898 
1899   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1900   case vmIntrinsics::_ceil:
1901   case vmIntrinsics::_floor:
1902   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1903 
1904   case vmIntrinsics::_dsqrt:
1905   case vmIntrinsics::_dsqrt_strict:
1906                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1907   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1908   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1909   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1910   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1911 
1912   case vmIntrinsics::_dpow:      return inline_math_pow();
1913   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1914   case vmIntrinsics::_fcopySign: return inline_math(id);
1915   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1916   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1917   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1918 
1919    // These intrinsics are not yet correctly implemented
1920   case vmIntrinsics::_datan2:
1921     return false;
1922 
1923   default:
1924     fatal_unexpected_iid(id);
1925     return false;
1926   }
1927 }
1928 
1929 //----------------------------inline_notify-----------------------------------*
1930 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1931   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1932   address func;
1933   if (id == vmIntrinsics::_notify) {
1934     func = OptoRuntime::monitor_notify_Java();
1935   } else {
1936     func = OptoRuntime::monitor_notifyAll_Java();
1937   }
1938   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1939   make_slow_call_ex(call, env()->Throwable_klass(), false);
1940   return true;
1941 }
1942 
1943 
1944 //----------------------------inline_min_max-----------------------------------
1945 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1946   Node* a = nullptr;
1947   Node* b = nullptr;
1948   Node* n = nullptr;
1949   switch (id) {
1950     case vmIntrinsics::_min:
1951     case vmIntrinsics::_max:
1952     case vmIntrinsics::_minF:
1953     case vmIntrinsics::_maxF:
1954     case vmIntrinsics::_minF_strict:
1955     case vmIntrinsics::_maxF_strict:
1956     case vmIntrinsics::_min_strict:
1957     case vmIntrinsics::_max_strict:
1958       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1959       a = argument(0);
1960       b = argument(1);
1961       break;
1962     case vmIntrinsics::_minD:
1963     case vmIntrinsics::_maxD:
1964     case vmIntrinsics::_minD_strict:
1965     case vmIntrinsics::_maxD_strict:
1966       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1967       a = argument(0);
1968       b = argument(2);
1969       break;
1970     case vmIntrinsics::_minL:
1971     case vmIntrinsics::_maxL:
1972       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1973       a = argument(0);
1974       b = argument(2);
1975       break;
1976     default:
1977       fatal_unexpected_iid(id);
1978       break;
1979   }
1980 
1981   switch (id) {
1982     case vmIntrinsics::_min:
1983     case vmIntrinsics::_min_strict:
1984       n = new MinINode(a, b);
1985       break;
1986     case vmIntrinsics::_max:
1987     case vmIntrinsics::_max_strict:
1988       n = new MaxINode(a, b);
1989       break;
1990     case vmIntrinsics::_minF:
1991     case vmIntrinsics::_minF_strict:
1992       n = new MinFNode(a, b);
1993       break;
1994     case vmIntrinsics::_maxF:
1995     case vmIntrinsics::_maxF_strict:
1996       n = new MaxFNode(a, b);
1997       break;
1998     case vmIntrinsics::_minD:
1999     case vmIntrinsics::_minD_strict:
2000       n = new MinDNode(a, b);
2001       break;
2002     case vmIntrinsics::_maxD:
2003     case vmIntrinsics::_maxD_strict:
2004       n = new MaxDNode(a, b);
2005       break;
2006     case vmIntrinsics::_minL:
2007       n = new MinLNode(_gvn.C, a, b);
2008       break;
2009     case vmIntrinsics::_maxL:
2010       n = new MaxLNode(_gvn.C, a, b);
2011       break;
2012     default:
2013       fatal_unexpected_iid(id);
2014       break;
2015   }
2016 
2017   set_result(_gvn.transform(n));
2018   return true;
2019 }
2020 
2021 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2022   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2023                                    env()->ArithmeticException_instance())) {
2024     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2025     // so let's bail out intrinsic rather than risking deopting again.
2026     return false;
2027   }
2028 
2029   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2030   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2031   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2032   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2033 
2034   {
2035     PreserveJVMState pjvms(this);
2036     PreserveReexecuteState preexecs(this);
2037     jvms()->set_should_reexecute(true);
2038 
2039     set_control(slow_path);
2040     set_i_o(i_o());
2041 
2042     builtin_throw(Deoptimization::Reason_intrinsic,
2043                   env()->ArithmeticException_instance(),
2044                   /*allow_too_many_traps*/ false);
2045   }
2046 
2047   set_control(fast_path);
2048   set_result(math);
2049   return true;
2050 }
2051 
2052 template <typename OverflowOp>
2053 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2054   typedef typename OverflowOp::MathOp MathOp;
2055 
2056   MathOp* mathOp = new MathOp(arg1, arg2);
2057   Node* operation = _gvn.transform( mathOp );
2058   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2059   return inline_math_mathExact(operation, ofcheck);
2060 }
2061 
2062 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2063   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2064 }
2065 
2066 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2067   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2068 }
2069 
2070 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2071   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2072 }
2073 
2074 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2075   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2076 }
2077 
2078 bool LibraryCallKit::inline_math_negateExactI() {
2079   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2080 }
2081 
2082 bool LibraryCallKit::inline_math_negateExactL() {
2083   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2084 }
2085 
2086 bool LibraryCallKit::inline_math_multiplyExactI() {
2087   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2088 }
2089 
2090 bool LibraryCallKit::inline_math_multiplyExactL() {
2091   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2092 }
2093 
2094 bool LibraryCallKit::inline_math_multiplyHigh() {
2095   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2096   return true;
2097 }
2098 
2099 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2100   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2101   return true;
2102 }
2103 
2104 inline int
2105 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2106   const TypePtr* base_type = TypePtr::NULL_PTR;
2107   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2108   if (base_type == nullptr) {
2109     // Unknown type.
2110     return Type::AnyPtr;
2111   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2112     // Since this is a null+long form, we have to switch to a rawptr.
2113     base   = _gvn.transform(new CastX2PNode(offset));
2114     offset = MakeConX(0);
2115     return Type::RawPtr;
2116   } else if (base_type->base() == Type::RawPtr) {
2117     return Type::RawPtr;
2118   } else if (base_type->isa_oopptr()) {
2119     // Base is never null => always a heap address.
2120     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2121       return Type::OopPtr;
2122     }
2123     // Offset is small => always a heap address.
2124     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2125     if (offset_type != nullptr &&
2126         base_type->offset() == 0 &&     // (should always be?)
2127         offset_type->_lo >= 0 &&
2128         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2129       return Type::OopPtr;
2130     } else if (type == T_OBJECT) {
2131       // off heap access to an oop doesn't make any sense. Has to be on
2132       // heap.
2133       return Type::OopPtr;
2134     }
2135     // Otherwise, it might either be oop+off or null+addr.
2136     return Type::AnyPtr;
2137   } else {
2138     // No information:
2139     return Type::AnyPtr;
2140   }
2141 }
2142 
2143 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2144   Node* uncasted_base = base;
2145   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2146   if (kind == Type::RawPtr) {
2147     return off_heap_plus_addr(uncasted_base, offset);
2148   } else if (kind == Type::AnyPtr) {
2149     assert(base == uncasted_base, "unexpected base change");
2150     if (can_cast) {
2151       if (!_gvn.type(base)->speculative_maybe_null() &&
2152           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2153         // According to profiling, this access is always on
2154         // heap. Casting the base to not null and thus avoiding membars
2155         // around the access should allow better optimizations
2156         Node* null_ctl = top();
2157         base = null_check_oop(base, &null_ctl, true, true, true);
2158         assert(null_ctl->is_top(), "no null control here");
2159         return basic_plus_adr(base, offset);
2160       } else if (_gvn.type(base)->speculative_always_null() &&
2161                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2162         // According to profiling, this access is always off
2163         // heap.
2164         base = null_assert(base);
2165         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2166         offset = MakeConX(0);
2167         return off_heap_plus_addr(raw_base, offset);
2168       }
2169     }
2170     // We don't know if it's an on heap or off heap access. Fall back
2171     // to raw memory access.
2172     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2173     return off_heap_plus_addr(raw, offset);
2174   } else {
2175     assert(base == uncasted_base, "unexpected base change");
2176     // We know it's an on heap access so base can't be null
2177     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2178       base = must_be_not_null(base, true);
2179     }
2180     return basic_plus_adr(base, offset);
2181   }
2182 }
2183 
2184 //--------------------------inline_number_methods-----------------------------
2185 // inline int     Integer.numberOfLeadingZeros(int)
2186 // inline int        Long.numberOfLeadingZeros(long)
2187 //
2188 // inline int     Integer.numberOfTrailingZeros(int)
2189 // inline int        Long.numberOfTrailingZeros(long)
2190 //
2191 // inline int     Integer.bitCount(int)
2192 // inline int        Long.bitCount(long)
2193 //
2194 // inline char  Character.reverseBytes(char)
2195 // inline short     Short.reverseBytes(short)
2196 // inline int     Integer.reverseBytes(int)
2197 // inline long       Long.reverseBytes(long)
2198 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2199   Node* arg = argument(0);
2200   Node* n = nullptr;
2201   switch (id) {
2202   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2203   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2204   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2205   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2206   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2207   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2208   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2209   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2210   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2211   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2212   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2213   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2214   default:  fatal_unexpected_iid(id);  break;
2215   }
2216   set_result(_gvn.transform(n));
2217   return true;
2218 }
2219 
2220 //--------------------------inline_bitshuffle_methods-----------------------------
2221 // inline int Integer.compress(int, int)
2222 // inline int Integer.expand(int, int)
2223 // inline long Long.compress(long, long)
2224 // inline long Long.expand(long, long)
2225 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2226   Node* n = nullptr;
2227   switch (id) {
2228     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2229     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2230     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2231     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2232     default:  fatal_unexpected_iid(id);  break;
2233   }
2234   set_result(_gvn.transform(n));
2235   return true;
2236 }
2237 
2238 //--------------------------inline_number_methods-----------------------------
2239 // inline int Integer.compareUnsigned(int, int)
2240 // inline int    Long.compareUnsigned(long, long)
2241 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2242   Node* arg1 = argument(0);
2243   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2244   Node* n = nullptr;
2245   switch (id) {
2246     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2247     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2248     default:  fatal_unexpected_iid(id);  break;
2249   }
2250   set_result(_gvn.transform(n));
2251   return true;
2252 }
2253 
2254 //--------------------------inline_unsigned_divmod_methods-----------------------------
2255 // inline int Integer.divideUnsigned(int, int)
2256 // inline int Integer.remainderUnsigned(int, int)
2257 // inline long Long.divideUnsigned(long, long)
2258 // inline long Long.remainderUnsigned(long, long)
2259 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2260   Node* n = nullptr;
2261   switch (id) {
2262     case vmIntrinsics::_divideUnsigned_i: {
2263       zero_check_int(argument(1));
2264       // Compile-time detect of null-exception
2265       if (stopped()) {
2266         return true; // keep the graph constructed so far
2267       }
2268       n = new UDivINode(control(), argument(0), argument(1));
2269       break;
2270     }
2271     case vmIntrinsics::_divideUnsigned_l: {
2272       zero_check_long(argument(2));
2273       // Compile-time detect of null-exception
2274       if (stopped()) {
2275         return true; // keep the graph constructed so far
2276       }
2277       n = new UDivLNode(control(), argument(0), argument(2));
2278       break;
2279     }
2280     case vmIntrinsics::_remainderUnsigned_i: {
2281       zero_check_int(argument(1));
2282       // Compile-time detect of null-exception
2283       if (stopped()) {
2284         return true; // keep the graph constructed so far
2285       }
2286       n = new UModINode(control(), argument(0), argument(1));
2287       break;
2288     }
2289     case vmIntrinsics::_remainderUnsigned_l: {
2290       zero_check_long(argument(2));
2291       // Compile-time detect of null-exception
2292       if (stopped()) {
2293         return true; // keep the graph constructed so far
2294       }
2295       n = new UModLNode(control(), argument(0), argument(2));
2296       break;
2297     }
2298     default:  fatal_unexpected_iid(id);  break;
2299   }
2300   set_result(_gvn.transform(n));
2301   return true;
2302 }
2303 
2304 //----------------------------inline_unsafe_access----------------------------
2305 
2306 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2307   // Attempt to infer a sharper value type from the offset and base type.
2308   ciKlass* sharpened_klass = nullptr;
2309   bool null_free = false;
2310 
2311   // See if it is an instance field, with an object type.
2312   if (alias_type->field() != nullptr) {
2313     if (alias_type->field()->type()->is_klass()) {
2314       sharpened_klass = alias_type->field()->type()->as_klass();
2315       null_free = alias_type->field()->is_null_free();
2316     }
2317   }
2318 
2319   const TypeOopPtr* result = nullptr;
2320   // See if it is a narrow oop array.
2321   if (adr_type->isa_aryptr()) {
2322     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2323       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2324       null_free = adr_type->is_aryptr()->is_null_free();
2325       if (elem_type != nullptr && elem_type->is_loaded()) {
2326         // Sharpen the value type.
2327         result = elem_type;
2328       }
2329     }
2330   }
2331 
2332   // The sharpened class might be unloaded if there is no class loader
2333   // contraint in place.
2334   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2335     // Sharpen the value type.
2336     result = TypeOopPtr::make_from_klass(sharpened_klass);
2337     if (null_free) {
2338       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2339     }
2340   }
2341   if (result != nullptr) {
2342 #ifndef PRODUCT
2343     if (C->print_intrinsics() || C->print_inlining()) {
2344       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2345       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2346     }
2347 #endif
2348   }
2349   return result;
2350 }
2351 
2352 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2353   switch (kind) {
2354       case Relaxed:
2355         return MO_UNORDERED;
2356       case Opaque:
2357         return MO_RELAXED;
2358       case Acquire:
2359         return MO_ACQUIRE;
2360       case Release:
2361         return MO_RELEASE;
2362       case Volatile:
2363         return MO_SEQ_CST;
2364       default:
2365         ShouldNotReachHere();
2366         return 0;
2367   }
2368 }
2369 
2370 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2371   if (callee()->is_static())  return false;  // caller must have the capability!
2372   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2373   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2374   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2375   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2376 
2377   if (is_reference_type(type)) {
2378     decorators |= ON_UNKNOWN_OOP_REF;
2379   }
2380 
2381   if (unaligned) {
2382     decorators |= C2_UNALIGNED;
2383   }
2384 
2385 #ifndef PRODUCT
2386   {
2387     ResourceMark rm;
2388     // Check the signatures.
2389     ciSignature* sig = callee()->signature();
2390 #ifdef ASSERT
2391     if (!is_store) {
2392       // Object getReference(Object base, int/long offset), etc.
2393       BasicType rtype = sig->return_type()->basic_type();
2394       assert(rtype == type, "getter must return the expected value");
2395       assert(sig->count() == 2, "oop getter has 2 arguments");
2396       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2397       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2398     } else {
2399       // void putReference(Object base, int/long offset, Object x), etc.
2400       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2401       assert(sig->count() == 3, "oop putter has 3 arguments");
2402       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2403       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2404       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2405       assert(vtype == type, "putter must accept the expected value");
2406     }
2407 #endif // ASSERT
2408  }
2409 #endif //PRODUCT
2410 
2411   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2412 
2413   Node* receiver = argument(0);  // type: oop
2414 
2415   // Build address expression.
2416   Node* heap_base_oop = top();
2417 
2418   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2419   Node* base = argument(1);  // type: oop
2420   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2421   Node* offset = argument(2);  // type: long
2422   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2423   // to be plain byte offsets, which are also the same as those accepted
2424   // by oopDesc::field_addr.
2425   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2426          "fieldOffset must be byte-scaled");
2427 
2428   if (base->is_InlineType()) {
2429     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2430     InlineTypeNode* vt = base->as_InlineType();
2431     if (offset->is_Con()) {
2432       long off = find_long_con(offset, 0);
2433       ciInlineKlass* vk = vt->type()->inline_klass();
2434       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2435         return false;
2436       }
2437 
2438       ciField* field = vk->get_non_flat_field_by_offset(off);
2439       if (field != nullptr) {
2440         BasicType bt = type2field[field->type()->basic_type()];
2441         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2442           bt = T_OBJECT;
2443         }
2444         if (bt == type && !field->is_flat()) {
2445           Node* value = vt->field_value_by_offset(off, false);
2446           const Type* value_type = _gvn.type(value);
2447           if (value->is_InlineType()) {
2448             value = value->as_InlineType()->adjust_scalarization_depth(this);
2449           } else if (value_type->is_inlinetypeptr()) {
2450             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2451           }
2452           set_result(value);
2453           return true;
2454         }
2455       }
2456     }
2457     {
2458       // Re-execute the unsafe access if allocation triggers deoptimization.
2459       PreserveReexecuteState preexecs(this);
2460       jvms()->set_should_reexecute(true);
2461       vt = vt->buffer(this);
2462     }
2463     base = vt->get_oop();
2464   }
2465 
2466   // 32-bit machines ignore the high half!
2467   offset = ConvL2X(offset);
2468 
2469   // Save state and restore on bailout
2470   SavedState old_state(this);
2471 
2472   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2473   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2474 
2475   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2476     if (type != T_OBJECT) {
2477       decorators |= IN_NATIVE; // off-heap primitive access
2478     } else {
2479       return false; // off-heap oop accesses are not supported
2480     }
2481   } else {
2482     heap_base_oop = base; // on-heap or mixed access
2483   }
2484 
2485   // Can base be null? Otherwise, always on-heap access.
2486   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2487 
2488   if (!can_access_non_heap) {
2489     decorators |= IN_HEAP;
2490   }
2491 
2492   Node* val = is_store ? argument(4) : nullptr;
2493 
2494   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2495   if (adr_type == TypePtr::NULL_PTR) {
2496     return false; // off-heap access with zero address
2497   }
2498 
2499   // Try to categorize the address.
2500   Compile::AliasType* alias_type = C->alias_type(adr_type);
2501   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2502 
2503   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2504       alias_type->adr_type() == TypeAryPtr::RANGE) {
2505     return false; // not supported
2506   }
2507 
2508   bool mismatched = false;
2509   BasicType bt = T_ILLEGAL;
2510   ciField* field = nullptr;
2511   if (adr_type->isa_instptr()) {
2512     const TypeInstPtr* instptr = adr_type->is_instptr();
2513     ciInstanceKlass* k = instptr->instance_klass();
2514     int off = instptr->offset();
2515     if (instptr->const_oop() != nullptr &&
2516         k == ciEnv::current()->Class_klass() &&
2517         instptr->offset() >= (k->size_helper() * wordSize)) {
2518       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2519       field = k->get_field_by_offset(off, true);
2520     } else {
2521       field = k->get_non_flat_field_by_offset(off);
2522     }
2523     if (field != nullptr) {
2524       bt = type2field[field->type()->basic_type()];
2525     }
2526     if (bt != alias_type->basic_type()) {
2527       // Type mismatch. Is it an access to a nested flat field?
2528       field = k->get_field_by_offset(off, false);
2529       if (field != nullptr) {
2530         bt = type2field[field->type()->basic_type()];
2531       }
2532     }
2533     assert(bt == alias_type->basic_type(), "should match");
2534   } else {
2535     bt = alias_type->basic_type();
2536   }
2537 
2538   if (bt != T_ILLEGAL) {
2539     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2540     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2541       // Alias type doesn't differentiate between byte[] and boolean[]).
2542       // Use address type to get the element type.
2543       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2544     }
2545     if (is_reference_type(bt, true)) {
2546       // accessing an array field with getReference is not a mismatch
2547       bt = T_OBJECT;
2548     }
2549     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2550       // Don't intrinsify mismatched object accesses
2551       return false;
2552     }
2553     mismatched = (bt != type);
2554   } else if (alias_type->adr_type()->isa_oopptr()) {
2555     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2556   }
2557 
2558   old_state.discard();
2559   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2560 
2561   if (mismatched) {
2562     decorators |= C2_MISMATCHED;
2563   }
2564 
2565   // First guess at the value type.
2566   const Type *value_type = Type::get_const_basic_type(type);
2567 
2568   // Figure out the memory ordering.
2569   decorators |= mo_decorator_for_access_kind(kind);
2570 
2571   if (!is_store) {
2572     if (type == T_OBJECT) {
2573       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2574       if (tjp != nullptr) {
2575         value_type = tjp;
2576       }
2577     }
2578   }
2579 
2580   receiver = null_check(receiver);
2581   if (stopped()) {
2582     return true;
2583   }
2584   // Heap pointers get a null-check from the interpreter,
2585   // as a courtesy.  However, this is not guaranteed by Unsafe,
2586   // and it is not possible to fully distinguish unintended nulls
2587   // from intended ones in this API.
2588 
2589   if (!is_store) {
2590     Node* p = nullptr;
2591     // Try to constant fold a load from a constant field
2592 
2593     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2594       // final or stable field
2595       p = make_constant_from_field(field, heap_base_oop);
2596     }
2597 
2598     if (p == nullptr) { // Could not constant fold the load
2599       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2600       const TypeOopPtr* ptr = value_type->make_oopptr();
2601       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2602         // Load a non-flattened inline type from memory
2603         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2604       }
2605       // Normalize the value returned by getBoolean in the following cases
2606       if (type == T_BOOLEAN &&
2607           (mismatched ||
2608            heap_base_oop == top() ||                  // - heap_base_oop is null or
2609            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2610                                                       //   and the unsafe access is made to large offset
2611                                                       //   (i.e., larger than the maximum offset necessary for any
2612                                                       //   field access)
2613             ) {
2614           IdealKit ideal = IdealKit(this);
2615 #define __ ideal.
2616           IdealVariable normalized_result(ideal);
2617           __ declarations_done();
2618           __ set(normalized_result, p);
2619           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2620           __ set(normalized_result, ideal.ConI(1));
2621           ideal.end_if();
2622           final_sync(ideal);
2623           p = __ value(normalized_result);
2624 #undef __
2625       }
2626     }
2627     if (type == T_ADDRESS) {
2628       p = gvn().transform(new CastP2XNode(nullptr, p));
2629       p = ConvX2UL(p);
2630     }
2631     // The load node has the control of the preceding MemBarCPUOrder.  All
2632     // following nodes will have the control of the MemBarCPUOrder inserted at
2633     // the end of this method.  So, pushing the load onto the stack at a later
2634     // point is fine.
2635     set_result(p);
2636   } else {
2637     if (bt == T_ADDRESS) {
2638       // Repackage the long as a pointer.
2639       val = ConvL2X(val);
2640       val = gvn().transform(new CastX2PNode(val));
2641     }
2642     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2643   }
2644 
2645   return true;
2646 }
2647 
2648 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2649 #ifdef ASSERT
2650   {
2651     ResourceMark rm;
2652     // Check the signatures.
2653     ciSignature* sig = callee()->signature();
2654     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2655     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2656     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2657     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2658     if (is_store) {
2659       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2660       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2661       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2662     } else {
2663       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2664       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2665     }
2666  }
2667 #endif // ASSERT
2668 
2669   assert(kind == Relaxed, "Only plain accesses for now");
2670   if (callee()->is_static()) {
2671     // caller must have the capability!
2672     return false;
2673   }
2674   C->set_has_unsafe_access(true);
2675 
2676   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2677   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2678     // parameter valueType is not a constant
2679     return false;
2680   }
2681   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2682   if (!mirror_type->is_inlinetype()) {
2683     // Dead code
2684     return false;
2685   }
2686   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2687 
2688   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2689   if (layout_type == nullptr || !layout_type->is_con()) {
2690     // parameter layoutKind is not a constant
2691     return false;
2692   }
2693   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2694          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2695          "invalid layoutKind %d", layout_type->get_con());
2696   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2697   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2698          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2699          "unexpected layoutKind %d", layout_type->get_con());
2700 
2701   null_check(argument(0));
2702   if (stopped()) {
2703     return true;
2704   }
2705 
2706   Node* base = must_be_not_null(argument(1), true);
2707   Node* offset = argument(2);
2708   const Type* base_type = _gvn.type(base);
2709 
2710   Node* ptr;
2711   bool immutable_memory = false;
2712   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2713   if (base_type->isa_instptr()) {
2714     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2715     if (offset_type == nullptr || !offset_type->is_con()) {
2716       // Offset into a non-array should be a constant
2717       decorators |= C2_MISMATCHED;
2718     } else {
2719       int offset_con = checked_cast<int>(offset_type->get_con());
2720       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2721       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2722       if (field == nullptr) {
2723         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2724         decorators |= C2_MISMATCHED;
2725       } else {
2726         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2727                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2728         immutable_memory = field->is_strict() && field->is_final();
2729 
2730         if (base->is_InlineType()) {
2731           assert(!is_store, "Cannot store into a non-larval value object");
2732           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2733           return true;
2734         }
2735       }
2736     }
2737 
2738     if (base->is_InlineType()) {
2739       assert(!is_store, "Cannot store into a non-larval value object");
2740       base = base->as_InlineType()->buffer(this, true);
2741     }
2742     ptr = basic_plus_adr(base, ConvL2X(offset));
2743   } else if (base_type->isa_aryptr()) {
2744     decorators |= IS_ARRAY;
2745     if (layout == LayoutKind::REFERENCE) {
2746       if (!base_type->is_aryptr()->is_not_flat()) {
2747         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2748         // TODO 8350865 This should be a CheckCastPP, can we add a test?
2749         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2750         replace_in_map(base, new_base);
2751         base = new_base;
2752       }
2753       ptr = basic_plus_adr(base, ConvL2X(offset));
2754     } else {
2755       if (UseArrayFlattening) {
2756         // Flat array must have an exact type
2757         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2758         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2759         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2760         replace_in_map(base, new_base);
2761         base = new_base;
2762         ptr = basic_plus_adr(base, ConvL2X(offset));
2763         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2764         if (ptr_type->field_offset().get() != 0) {
2765           // TODO 8350865 This should be a CheckCastPP, can we add a test?
2766           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2767         }
2768       } else {
2769         uncommon_trap(Deoptimization::Reason_intrinsic,
2770                       Deoptimization::Action_none);
2771         return true;
2772       }
2773     }
2774   } else {
2775     decorators |= C2_MISMATCHED;
2776     ptr = basic_plus_adr(base, ConvL2X(offset));
2777   }
2778 
2779   if (is_store) {
2780     Node* value = argument(6);
2781     const Type* value_type = _gvn.type(value);
2782     if (!value_type->is_inlinetypeptr()) {
2783       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2784       Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2785       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2786       replace_in_map(value, new_value);
2787       value = new_value;
2788     }
2789 
2790     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());
2791     if (layout == LayoutKind::REFERENCE) {
2792       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2793       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2794     } else {
2795       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2796       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2797       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2798     }
2799 
2800     return true;
2801   } else {
2802     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2803     InlineTypeNode* result;
2804     if (layout == LayoutKind::REFERENCE) {
2805       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2806       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2807       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2808     } else {
2809       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2810       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2811       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2812     }
2813 
2814     set_result(result);
2815     return true;
2816   }
2817 }
2818 
2819 //----------------------------inline_unsafe_load_store----------------------------
2820 // This method serves a couple of different customers (depending on LoadStoreKind):
2821 //
2822 // LS_cmp_swap:
2823 //
2824 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2825 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2826 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2827 //
2828 // LS_cmp_swap_weak:
2829 //
2830 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2831 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2832 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2833 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2834 //
2835 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2836 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2837 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2838 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2839 //
2840 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2841 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2842 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2843 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2844 //
2845 // LS_cmp_exchange:
2846 //
2847 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2848 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2849 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2850 //
2851 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2852 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2853 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2854 //
2855 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2856 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2857 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2858 //
2859 // LS_get_add:
2860 //
2861 //   int  getAndAddInt( Object o, long offset, int  delta)
2862 //   long getAndAddLong(Object o, long offset, long delta)
2863 //
2864 // LS_get_set:
2865 //
2866 //   int    getAndSet(Object o, long offset, int    newValue)
2867 //   long   getAndSet(Object o, long offset, long   newValue)
2868 //   Object getAndSet(Object o, long offset, Object newValue)
2869 //
2870 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2871   // This basic scheme here is the same as inline_unsafe_access, but
2872   // differs in enough details that combining them would make the code
2873   // overly confusing.  (This is a true fact! I originally combined
2874   // them, but even I was confused by it!) As much code/comments as
2875   // possible are retained from inline_unsafe_access though to make
2876   // the correspondences clearer. - dl
2877 
2878   if (callee()->is_static())  return false;  // caller must have the capability!
2879 
2880   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2881   decorators |= mo_decorator_for_access_kind(access_kind);
2882 
2883 #ifndef PRODUCT
2884   BasicType rtype;
2885   {
2886     ResourceMark rm;
2887     // Check the signatures.
2888     ciSignature* sig = callee()->signature();
2889     rtype = sig->return_type()->basic_type();
2890     switch(kind) {
2891       case LS_get_add:
2892       case LS_get_set: {
2893       // Check the signatures.
2894 #ifdef ASSERT
2895       assert(rtype == type, "get and set must return the expected type");
2896       assert(sig->count() == 3, "get and set has 3 arguments");
2897       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2898       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2899       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2900       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2901 #endif // ASSERT
2902         break;
2903       }
2904       case LS_cmp_swap:
2905       case LS_cmp_swap_weak: {
2906       // Check the signatures.
2907 #ifdef ASSERT
2908       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2909       assert(sig->count() == 4, "CAS has 4 arguments");
2910       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2911       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2912 #endif // ASSERT
2913         break;
2914       }
2915       case LS_cmp_exchange: {
2916       // Check the signatures.
2917 #ifdef ASSERT
2918       assert(rtype == type, "CAS must return the expected type");
2919       assert(sig->count() == 4, "CAS has 4 arguments");
2920       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2921       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2922 #endif // ASSERT
2923         break;
2924       }
2925       default:
2926         ShouldNotReachHere();
2927     }
2928   }
2929 #endif //PRODUCT
2930 
2931   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2932 
2933   // Get arguments:
2934   Node* receiver = nullptr;
2935   Node* base     = nullptr;
2936   Node* offset   = nullptr;
2937   Node* oldval   = nullptr;
2938   Node* newval   = nullptr;
2939   switch(kind) {
2940     case LS_cmp_swap:
2941     case LS_cmp_swap_weak:
2942     case LS_cmp_exchange: {
2943       const bool two_slot_type = type2size[type] == 2;
2944       receiver = argument(0);  // type: oop
2945       base     = argument(1);  // type: oop
2946       offset   = argument(2);  // type: long
2947       oldval   = argument(4);  // type: oop, int, or long
2948       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2949       break;
2950     }
2951     case LS_get_add:
2952     case LS_get_set: {
2953       receiver = argument(0);  // type: oop
2954       base     = argument(1);  // type: oop
2955       offset   = argument(2);  // type: long
2956       oldval   = nullptr;
2957       newval   = argument(4);  // type: oop, int, or long
2958       break;
2959     }
2960     default:
2961       ShouldNotReachHere();
2962   }
2963 
2964   // Build field offset expression.
2965   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2966   // to be plain byte offsets, which are also the same as those accepted
2967   // by oopDesc::field_addr.
2968   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2969   // 32-bit machines ignore the high half of long offsets
2970   offset = ConvL2X(offset);
2971   // Save state and restore on bailout
2972   SavedState old_state(this);
2973   Node* adr = make_unsafe_address(base, offset,type, false);
2974   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2975 
2976   Compile::AliasType* alias_type = C->alias_type(adr_type);
2977   BasicType bt = alias_type->basic_type();
2978   if (bt != T_ILLEGAL &&
2979       (is_reference_type(bt) != (type == T_OBJECT))) {
2980     // Don't intrinsify mismatched object accesses.
2981     return false;
2982   }
2983 
2984   old_state.discard();
2985 
2986   // For CAS, unlike inline_unsafe_access, there seems no point in
2987   // trying to refine types. Just use the coarse types here.
2988   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2989   const Type *value_type = Type::get_const_basic_type(type);
2990 
2991   switch (kind) {
2992     case LS_get_set:
2993     case LS_cmp_exchange: {
2994       if (type == T_OBJECT) {
2995         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2996         if (tjp != nullptr) {
2997           value_type = tjp;
2998         }
2999       }
3000       break;
3001     }
3002     case LS_cmp_swap:
3003     case LS_cmp_swap_weak:
3004     case LS_get_add:
3005       break;
3006     default:
3007       ShouldNotReachHere();
3008   }
3009 
3010   // Null check receiver.
3011   receiver = null_check(receiver);
3012   if (stopped()) {
3013     return true;
3014   }
3015 
3016   int alias_idx = C->get_alias_index(adr_type);
3017 
3018   if (is_reference_type(type)) {
3019     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3020 
3021     if (oldval != nullptr && oldval->is_InlineType()) {
3022       // Re-execute the unsafe access if allocation triggers deoptimization.
3023       PreserveReexecuteState preexecs(this);
3024       jvms()->set_should_reexecute(true);
3025       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3026     }
3027     if (newval != nullptr && newval->is_InlineType()) {
3028       // Re-execute the unsafe access if allocation triggers deoptimization.
3029       PreserveReexecuteState preexecs(this);
3030       jvms()->set_should_reexecute(true);
3031       newval = newval->as_InlineType()->buffer(this)->get_oop();
3032     }
3033 
3034     // Transformation of a value which could be null pointer (CastPP #null)
3035     // could be delayed during Parse (for example, in adjust_map_after_if()).
3036     // Execute transformation here to avoid barrier generation in such case.
3037     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3038       newval = _gvn.makecon(TypePtr::NULL_PTR);
3039 
3040     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3041       // Refine the value to a null constant, when it is known to be null
3042       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3043     }
3044   }
3045 
3046   Node* result = nullptr;
3047   switch (kind) {
3048     case LS_cmp_exchange: {
3049       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3050                                             oldval, newval, value_type, type, decorators);
3051       break;
3052     }
3053     case LS_cmp_swap_weak:
3054       decorators |= C2_WEAK_CMPXCHG;
3055     case LS_cmp_swap: {
3056       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3057                                              oldval, newval, value_type, type, decorators);
3058       break;
3059     }
3060     case LS_get_set: {
3061       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3062                                      newval, value_type, type, decorators);
3063       break;
3064     }
3065     case LS_get_add: {
3066       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3067                                     newval, value_type, type, decorators);
3068       break;
3069     }
3070     default:
3071       ShouldNotReachHere();
3072   }
3073 
3074   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3075   set_result(result);
3076   return true;
3077 }
3078 
3079 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3080   // Regardless of form, don't allow previous ld/st to move down,
3081   // then issue acquire, release, or volatile mem_bar.
3082   insert_mem_bar(Op_MemBarCPUOrder);
3083   switch(id) {
3084     case vmIntrinsics::_loadFence:
3085       insert_mem_bar(Op_LoadFence);
3086       return true;
3087     case vmIntrinsics::_storeFence:
3088       insert_mem_bar(Op_StoreFence);
3089       return true;
3090     case vmIntrinsics::_storeStoreFence:
3091       insert_mem_bar(Op_StoreStoreFence);
3092       return true;
3093     case vmIntrinsics::_fullFence:
3094       insert_mem_bar(Op_MemBarFull);
3095       return true;
3096     default:
3097       fatal_unexpected_iid(id);
3098       return false;
3099   }
3100 }
3101 
3102 // private native int arrayInstanceBaseOffset0(Object[] array);
3103 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3104   Node* array = argument(1);
3105   Node* klass_node = load_object_klass(array);
3106 
3107   jint  layout_con = Klass::_lh_neutral_value;
3108   Node* layout_val = get_layout_helper(klass_node, layout_con);
3109   int   layout_is_con = (layout_val == nullptr);
3110 
3111   Node* header_size = nullptr;
3112   if (layout_is_con) {
3113     int hsize = Klass::layout_helper_header_size(layout_con);
3114     header_size = intcon(hsize);
3115   } else {
3116     Node* hss = intcon(Klass::_lh_header_size_shift);
3117     Node* hsm = intcon(Klass::_lh_header_size_mask);
3118     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3119     header_size = _gvn.transform(new AndINode(header_size, hsm));
3120   }
3121   set_result(header_size);
3122   return true;
3123 }
3124 
3125 // private native int arrayInstanceIndexScale0(Object[] array);
3126 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3127   Node* array = argument(1);
3128   Node* klass_node = load_object_klass(array);
3129 
3130   jint  layout_con = Klass::_lh_neutral_value;
3131   Node* layout_val = get_layout_helper(klass_node, layout_con);
3132   int   layout_is_con = (layout_val == nullptr);
3133 
3134   Node* element_size = nullptr;
3135   if (layout_is_con) {
3136     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3137     int elem_size = 1 << log_element_size;
3138     element_size = intcon(elem_size);
3139   } else {
3140     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3141     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3142     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3143     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3144     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3145   }
3146   set_result(element_size);
3147   return true;
3148 }
3149 
3150 // private native int arrayLayout0(Object[] array);
3151 bool LibraryCallKit::inline_arrayLayout() {
3152   RegionNode* region = new RegionNode(2);
3153   Node* phi = new PhiNode(region, TypeInt::POS);
3154 
3155   Node* array = argument(1);
3156   Node* klass_node = load_object_klass(array);
3157   generate_refArray_guard(klass_node, region);
3158   if (region->req() == 3) {
3159     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3160   }
3161 
3162   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3163   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3164   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3165 
3166   region->init_req(1, control());
3167   phi->init_req(1, layout_kind);
3168 
3169   set_control(_gvn.transform(region));
3170   set_result(_gvn.transform(phi));
3171   return true;
3172 }
3173 
3174 // private native int[] getFieldMap0(Class <?> c);
3175 //   int offset = c._klass._acmp_maps_offset;
3176 //   return (int[])c.obj_field(offset);
3177 bool LibraryCallKit::inline_getFieldMap() {
3178   Node* mirror = argument(1);
3179   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3180 
3181   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3182   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3183   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3184   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3185 
3186   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3187   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3188   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3189 
3190   set_result(map);
3191   return true;
3192 }
3193 
3194 bool LibraryCallKit::inline_onspinwait() {
3195   insert_mem_bar(Op_OnSpinWait);
3196   return true;
3197 }
3198 
3199 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3200   if (!kls->is_Con()) {
3201     return true;
3202   }
3203   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3204   if (klsptr == nullptr) {
3205     return true;
3206   }
3207   ciInstanceKlass* ik = klsptr->instance_klass();
3208   // don't need a guard for a klass that is already initialized
3209   return !ik->is_initialized();
3210 }
3211 
3212 //----------------------------inline_unsafe_writeback0-------------------------
3213 // public native void Unsafe.writeback0(long address)
3214 bool LibraryCallKit::inline_unsafe_writeback0() {
3215   if (!Matcher::has_match_rule(Op_CacheWB)) {
3216     return false;
3217   }
3218 #ifndef PRODUCT
3219   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3220   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3221   ciSignature* sig = callee()->signature();
3222   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3223 #endif
3224   null_check_receiver();  // null-check, then ignore
3225   Node *addr = argument(1);
3226   addr = new CastX2PNode(addr);
3227   addr = _gvn.transform(addr);
3228   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3229   flush = _gvn.transform(flush);
3230   set_memory(flush, TypeRawPtr::BOTTOM);
3231   return true;
3232 }
3233 
3234 //----------------------------inline_unsafe_writeback0-------------------------
3235 // public native void Unsafe.writeback0(long address)
3236 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3237   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3238     return false;
3239   }
3240   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3241     return false;
3242   }
3243 #ifndef PRODUCT
3244   assert(Matcher::has_match_rule(Op_CacheWB),
3245          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3246                 : "found match rule for CacheWBPostSync but not CacheWB"));
3247 
3248 #endif
3249   null_check_receiver();  // null-check, then ignore
3250   Node *sync;
3251   if (is_pre) {
3252     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3253   } else {
3254     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3255   }
3256   sync = _gvn.transform(sync);
3257   set_memory(sync, TypeRawPtr::BOTTOM);
3258   return true;
3259 }
3260 
3261 //----------------------------inline_unsafe_allocate---------------------------
3262 // public native Object Unsafe.allocateInstance(Class<?> cls);
3263 bool LibraryCallKit::inline_unsafe_allocate() {
3264 
3265 #if INCLUDE_JVMTI
3266   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3267     return false;
3268   }
3269 #endif //INCLUDE_JVMTI
3270 
3271   if (callee()->is_static())  return false;  // caller must have the capability!
3272 
3273   null_check_receiver();  // null-check, then ignore
3274   Node* cls = null_check(argument(1));
3275   if (stopped())  return true;
3276 
3277   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3278   kls = null_check(kls);
3279   if (stopped())  return true;  // argument was like int.class
3280 
3281 #if INCLUDE_JVMTI
3282     // Don't try to access new allocated obj in the intrinsic.
3283     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3284     // Deoptimize and allocate in interpreter instead.
3285     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3286     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3287     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3288     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3289     {
3290       BuildCutout unless(this, tst, PROB_MAX);
3291       uncommon_trap(Deoptimization::Reason_intrinsic,
3292                     Deoptimization::Action_make_not_entrant);
3293     }
3294     if (stopped()) {
3295       return true;
3296     }
3297 #endif //INCLUDE_JVMTI
3298 
3299   Node* test = nullptr;
3300   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3301     // Note:  The argument might still be an illegal value like
3302     // Serializable.class or Object[].class.   The runtime will handle it.
3303     // But we must make an explicit check for initialization.
3304     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3305     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3306     // can generate code to load it as unsigned byte.
3307     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3308     Node* bits = intcon(InstanceKlass::fully_initialized);
3309     test = _gvn.transform(new SubINode(inst, bits));
3310     // The 'test' is non-zero if we need to take a slow path.
3311   }
3312   Node* obj = new_instance(kls, test);
3313   set_result(obj);
3314   return true;
3315 }
3316 
3317 //------------------------inline_native_time_funcs--------------
3318 // inline code for System.currentTimeMillis() and System.nanoTime()
3319 // these have the same type and signature
3320 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3321   const TypeFunc* tf = OptoRuntime::void_long_Type();
3322   const TypePtr* no_memory_effects = nullptr;
3323   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3324   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3325 #ifdef ASSERT
3326   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3327   assert(value_top == top(), "second value must be top");
3328 #endif
3329   set_result(value);
3330   return true;
3331 }
3332 
3333 //--------------------inline_native_vthread_start_transition--------------------
3334 // inline void startTransition(boolean is_mount);
3335 // inline void startFinalTransition();
3336 // Pseudocode of implementation:
3337 //
3338 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3339 // carrier->set_is_in_vthread_transition(true);
3340 // OrderAccess::storeload();
3341 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3342 //                        + global_vthread_transition_disable_count();
3343 // if (disable_requests > 0) {
3344 //   slow path: runtime call
3345 // }
3346 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3347   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3348   IdealKit ideal(this);
3349 
3350   Node* thread = ideal.thread();
3351   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3352   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3353   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3354   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3355   insert_mem_bar(Op_MemBarStoreLoad);
3356   ideal.sync_kit(this);
3357 
3358   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3359   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3360   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3361   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3362   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3363   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3364 
3365   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3366     sync_kit(ideal);
3367     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3368     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3369     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3370     ideal.sync_kit(this);
3371   }
3372   ideal.end_if();
3373 
3374   final_sync(ideal);
3375   return true;
3376 }
3377 
3378 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3379   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3380   IdealKit ideal(this);
3381 
3382   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3383   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3384 
3385   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3386     sync_kit(ideal);
3387     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3388     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3389     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3390     ideal.sync_kit(this);
3391   } ideal.else_(); {
3392     Node* thread = ideal.thread();
3393     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3394     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3395 
3396     sync_kit(ideal);
3397     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3398     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3399     ideal.sync_kit(this);
3400   } ideal.end_if();
3401 
3402   final_sync(ideal);
3403   return true;
3404 }
3405 
3406 #if INCLUDE_JVMTI
3407 
3408 // Always update the is_disable_suspend bit.
3409 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3410   if (!DoJVMTIVirtualThreadTransitions) {
3411     return true;
3412   }
3413   IdealKit ideal(this);
3414 
3415   {
3416     // unconditionally update the is_disable_suspend bit in current JavaThread
3417     Node* thread = ideal.thread();
3418     Node* arg = argument(0); // argument for notification
3419     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3420     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3421 
3422     sync_kit(ideal);
3423     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3424     ideal.sync_kit(this);
3425   }
3426   final_sync(ideal);
3427 
3428   return true;
3429 }
3430 
3431 #endif // INCLUDE_JVMTI
3432 
3433 #ifdef JFR_HAVE_INTRINSICS
3434 
3435 /**
3436  * if oop->klass != null
3437  *   // normal class
3438  *   epoch = _epoch_state ? 2 : 1
3439  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3440  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3441  *   }
3442  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3443  * else
3444  *   // primitive class
3445  *   if oop->array_klass != null
3446  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3447  *   else
3448  *     id = LAST_TYPE_ID + 1 // void class path
3449  *   if (!signaled)
3450  *     signaled = true
3451  */
3452 bool LibraryCallKit::inline_native_classID() {
3453   Node* cls = argument(0);
3454 
3455   IdealKit ideal(this);
3456 #define __ ideal.
3457   IdealVariable result(ideal); __ declarations_done();
3458   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3459                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3460                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3461 
3462 
3463   __ if_then(kls, BoolTest::ne, null()); {
3464     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3465     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3466 
3467     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3468     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3469     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3470     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3471     mask = _gvn.transform(new OrLNode(mask, epoch));
3472     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3473 
3474     float unlikely  = PROB_UNLIKELY(0.999);
3475     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3476       sync_kit(ideal);
3477       make_runtime_call(RC_LEAF,
3478                         OptoRuntime::class_id_load_barrier_Type(),
3479                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3480                         "class id load barrier",
3481                         TypePtr::BOTTOM,
3482                         kls);
3483       ideal.sync_kit(this);
3484     } __ end_if();
3485 
3486     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3487   } __ else_(); {
3488     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3489                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3490                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3491     __ if_then(array_kls, BoolTest::ne, null()); {
3492       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3493       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3494       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3495       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3496     } __ else_(); {
3497       // void class case
3498       ideal.set(result, longcon(LAST_TYPE_ID + 1));
3499     } __ end_if();
3500 
3501     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3502     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3503     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3504       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3505     } __ end_if();
3506   } __ end_if();
3507 
3508   final_sync(ideal);
3509   set_result(ideal.value(result));
3510 #undef __
3511   return true;
3512 }
3513 
3514 //------------------------inline_native_jvm_commit------------------
3515 bool LibraryCallKit::inline_native_jvm_commit() {
3516   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3517 
3518   // Save input memory and i_o state.
3519   Node* input_memory_state = reset_memory();
3520   set_all_memory(input_memory_state);
3521   Node* input_io_state = i_o();
3522 
3523   // TLS.
3524   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3525   // Jfr java buffer.
3526   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3527   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3528   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3529 
3530   // Load the current value of the notified field in the JfrThreadLocal.
3531   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3532   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3533 
3534   // Test for notification.
3535   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3536   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3537   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3538 
3539   // True branch, is notified.
3540   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3541   set_control(is_notified);
3542 
3543   // Reset notified state.
3544   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3545   Node* notified_reset_memory = reset_memory();
3546 
3547   // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3548   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3549   // Convert the machine-word to a long.
3550   Node* current_pos = ConvX2L(current_pos_X);
3551 
3552   // False branch, not notified.
3553   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3554   set_control(not_notified);
3555   set_all_memory(input_memory_state);
3556 
3557   // Arg is the next position as a long.
3558   Node* arg = argument(0);
3559   // Convert long to machine-word.
3560   Node* next_pos_X = ConvL2X(arg);
3561 
3562   // Store the next_position to the underlying jfr java buffer.
3563   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3564 
3565   Node* commit_memory = reset_memory();
3566   set_all_memory(commit_memory);
3567 
3568   // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3569   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3570   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3571   Node* lease_constant = _gvn.intcon(4);
3572 
3573   // And flags with lease constant.
3574   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3575 
3576   // Branch on lease to conditionalize returning the leased java buffer.
3577   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3578   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3579   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3580 
3581   // False branch, not a lease.
3582   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3583 
3584   // True branch, is lease.
3585   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3586   set_control(is_lease);
3587 
3588   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3589   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3590                                               OptoRuntime::void_void_Type(),
3591                                               SharedRuntime::jfr_return_lease(),
3592                                               "return_lease", TypePtr::BOTTOM);
3593   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3594 
3595   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3596   record_for_igvn(lease_compare_rgn);
3597   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3598   record_for_igvn(lease_compare_mem);
3599   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3600   record_for_igvn(lease_compare_io);
3601   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3602   record_for_igvn(lease_result_value);
3603 
3604   // Update control and phi nodes.
3605   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3606   lease_compare_rgn->init_req(_false_path, not_lease);
3607 
3608   lease_compare_mem->init_req(_true_path, reset_memory());
3609   lease_compare_mem->init_req(_false_path, commit_memory);
3610 
3611   lease_compare_io->init_req(_true_path, i_o());
3612   lease_compare_io->init_req(_false_path, input_io_state);
3613 
3614   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3615   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3616 
3617   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3618   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3619   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3620   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3621 
3622   // Update control and phi nodes.
3623   result_rgn->init_req(_true_path, is_notified);
3624   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3625 
3626   result_mem->init_req(_true_path, notified_reset_memory);
3627   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3628 
3629   result_io->init_req(_true_path, input_io_state);
3630   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3631 
3632   result_value->init_req(_true_path, current_pos);
3633   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3634 
3635   // Set output state.
3636   set_control(_gvn.transform(result_rgn));
3637   set_all_memory(_gvn.transform(result_mem));
3638   set_i_o(_gvn.transform(result_io));
3639   set_result(result_rgn, result_value);
3640   return true;
3641 }
3642 
3643 /*
3644  * The intrinsic is a model of this pseudo-code:
3645  *
3646  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3647  * jobject h_event_writer = tl->java_event_writer();
3648  * if (h_event_writer == nullptr) {
3649  *   return nullptr;
3650  * }
3651  * oop threadObj = Thread::threadObj();
3652  * oop vthread = java_lang_Thread::vthread(threadObj);
3653  * traceid tid;
3654  * bool pinVirtualThread;
3655  * bool excluded;
3656  * if (vthread != threadObj) {  // i.e. current thread is virtual
3657  *   tid = java_lang_Thread::tid(vthread);
3658  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3659  *   pinVirtualThread = VMContinuations;
3660  *   excluded = vthread_epoch_raw & excluded_mask;
3661  *   if (!excluded) {
3662  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3663  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3664  *     if (vthread_epoch != current_epoch) {
3665  *       write_checkpoint();
3666  *     }
3667  *   }
3668  * } else {
3669  *   tid = java_lang_Thread::tid(threadObj);
3670  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3671  *   pinVirtualThread = false;
3672  *   excluded = thread_epoch_raw & excluded_mask;
3673  * }
3674  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3675  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3676  * if (tid_in_event_writer != tid) {
3677  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3678  *   setField(event_writer, "excluded", excluded);
3679  *   setField(event_writer, "threadID", tid);
3680  * }
3681  * return event_writer
3682  */
3683 bool LibraryCallKit::inline_native_getEventWriter() {
3684   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3685 
3686   // Save input memory and i_o state.
3687   Node* input_memory_state = reset_memory();
3688   set_all_memory(input_memory_state);
3689   Node* input_io_state = i_o();
3690 
3691   // The most significant bit of the u2 is used to denote thread exclusion
3692   Node* excluded_shift = _gvn.intcon(15);
3693   Node* excluded_mask = _gvn.intcon(1 << 15);
3694   // The epoch generation is the range [1-32767]
3695   Node* epoch_mask = _gvn.intcon(32767);
3696 
3697   // TLS
3698   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3699 
3700   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3701   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3702 
3703   // Load the eventwriter jobject handle.
3704   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3705 
3706   // Null check the jobject handle.
3707   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3708   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3709   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3710 
3711   // False path, jobj is null.
3712   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3713 
3714   // True path, jobj is not null.
3715   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3716 
3717   set_control(jobj_is_not_null);
3718 
3719   // Load the threadObj for the CarrierThread.
3720   Node* threadObj = generate_current_thread(tls_ptr);
3721 
3722   // Load the vthread.
3723   Node* vthread = generate_virtual_thread(tls_ptr);
3724 
3725   // If vthread != threadObj, this is a virtual thread.
3726   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3727   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3728   IfNode* iff_vthread_not_equal_threadObj =
3729     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3730 
3731   // False branch, fallback to threadObj.
3732   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3733   set_control(vthread_equal_threadObj);
3734 
3735   // Load the tid field from the vthread object.
3736   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3737 
3738   // Load the raw epoch value from the threadObj.
3739   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3740   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3741                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3742                                              TypeInt::CHAR, T_CHAR,
3743                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3744 
3745   // Mask off the excluded information from the epoch.
3746   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3747 
3748   // True branch, this is a virtual thread.
3749   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3750   set_control(vthread_not_equal_threadObj);
3751 
3752   // Load the tid field from the vthread object.
3753   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3754 
3755   // Continuation support determines if a virtual thread should be pinned.
3756   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3757   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3758 
3759   // Load the raw epoch value from the vthread.
3760   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3761   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3762                                            TypeInt::CHAR, T_CHAR,
3763                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3764 
3765   // Mask off the excluded information from the epoch.
3766   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3767 
3768   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3769   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3770   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3771   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3772 
3773   // False branch, vthread is excluded, no need to write epoch info.
3774   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3775 
3776   // True branch, vthread is included, update epoch info.
3777   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3778   set_control(included);
3779 
3780   // Get epoch value.
3781   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3782 
3783   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3784   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3785   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3786 
3787   // Compare the epoch in the vthread to the current epoch generation.
3788   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3789   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3790   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3791 
3792   // False path, epoch is equal, checkpoint information is valid.
3793   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3794 
3795   // True path, epoch is not equal, write a checkpoint for the vthread.
3796   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3797 
3798   set_control(epoch_is_not_equal);
3799 
3800   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3801   // The call also updates the native thread local thread id and the vthread with the current epoch.
3802   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3803                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3804                                                   SharedRuntime::jfr_write_checkpoint(),
3805                                                   "write_checkpoint", TypePtr::BOTTOM);
3806   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3807 
3808   // vthread epoch != current epoch
3809   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3810   record_for_igvn(epoch_compare_rgn);
3811   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3812   record_for_igvn(epoch_compare_mem);
3813   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3814   record_for_igvn(epoch_compare_io);
3815 
3816   // Update control and phi nodes.
3817   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3818   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3819   epoch_compare_mem->init_req(_true_path, reset_memory());
3820   epoch_compare_mem->init_req(_false_path, input_memory_state);
3821   epoch_compare_io->init_req(_true_path, i_o());
3822   epoch_compare_io->init_req(_false_path, input_io_state);
3823 
3824   // excluded != true
3825   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3826   record_for_igvn(exclude_compare_rgn);
3827   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3828   record_for_igvn(exclude_compare_mem);
3829   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3830   record_for_igvn(exclude_compare_io);
3831 
3832   // Update control and phi nodes.
3833   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3834   exclude_compare_rgn->init_req(_false_path, excluded);
3835   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3836   exclude_compare_mem->init_req(_false_path, input_memory_state);
3837   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3838   exclude_compare_io->init_req(_false_path, input_io_state);
3839 
3840   // vthread != threadObj
3841   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3842   record_for_igvn(vthread_compare_rgn);
3843   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3844   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3845   record_for_igvn(vthread_compare_io);
3846   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3847   record_for_igvn(tid);
3848   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3849   record_for_igvn(exclusion);
3850   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3851   record_for_igvn(pinVirtualThread);
3852 
3853   // Update control and phi nodes.
3854   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3855   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3856   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3857   vthread_compare_mem->init_req(_false_path, input_memory_state);
3858   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3859   vthread_compare_io->init_req(_false_path, input_io_state);
3860   tid->init_req(_true_path, vthread_tid);
3861   tid->init_req(_false_path, thread_obj_tid);
3862   exclusion->init_req(_true_path, vthread_is_excluded);
3863   exclusion->init_req(_false_path, threadObj_is_excluded);
3864   pinVirtualThread->init_req(_true_path, continuation_support);
3865   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3866 
3867   // Update branch state.
3868   set_control(_gvn.transform(vthread_compare_rgn));
3869   set_all_memory(_gvn.transform(vthread_compare_mem));
3870   set_i_o(_gvn.transform(vthread_compare_io));
3871 
3872   // Load the event writer oop by dereferencing the jobject handle.
3873   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3874   assert(klass_EventWriter->is_loaded(), "invariant");
3875   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3876   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3877   const TypeOopPtr* const xtype = aklass->as_instance_type();
3878   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3879   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3880 
3881   // Load the current thread id from the event writer object.
3882   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3883   // Get the field offset to, conditionally, store an updated tid value later.
3884   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3885   // Get the field offset to, conditionally, store an updated exclusion value later.
3886   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3887   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3888   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3889 
3890   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3891   record_for_igvn(event_writer_tid_compare_rgn);
3892   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3893   record_for_igvn(event_writer_tid_compare_mem);
3894   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3895   record_for_igvn(event_writer_tid_compare_io);
3896 
3897   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3898   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3899   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3900   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3901 
3902   // False path, tids are the same.
3903   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3904 
3905   // True path, tid is not equal, need to update the tid in the event writer.
3906   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3907   record_for_igvn(tid_is_not_equal);
3908 
3909   // Store the pin state to the event writer.
3910   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3911 
3912   // Store the exclusion state to the event writer.
3913   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3914   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3915 
3916   // Store the tid to the event writer.
3917   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3918 
3919   // Update control and phi nodes.
3920   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3921   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3922   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3923   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3924   event_writer_tid_compare_io->init_req(_true_path, i_o());
3925   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3926 
3927   // Result of top level CFG, Memory, IO and Value.
3928   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3929   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3930   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3931   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3932 
3933   // Result control.
3934   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3935   result_rgn->init_req(_false_path, jobj_is_null);
3936 
3937   // Result memory.
3938   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3939   result_mem->init_req(_false_path, input_memory_state);
3940 
3941   // Result IO.
3942   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3943   result_io->init_req(_false_path, input_io_state);
3944 
3945   // Result value.
3946   result_value->init_req(_true_path, event_writer); // return event writer oop
3947   result_value->init_req(_false_path, null()); // return null
3948 
3949   // Set output state.
3950   set_control(_gvn.transform(result_rgn));
3951   set_all_memory(_gvn.transform(result_mem));
3952   set_i_o(_gvn.transform(result_io));
3953   set_result(result_rgn, result_value);
3954   return true;
3955 }
3956 
3957 /*
3958  * The intrinsic is a model of this pseudo-code:
3959  *
3960  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3961  * if (carrierThread != thread) { // is virtual thread
3962  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3963  *   bool excluded = vthread_epoch_raw & excluded_mask;
3964  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3965  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3966  *   if (!excluded) {
3967  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3968  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3969  *   }
3970  *   AtomicAccess::release_store(&tl->_vthread, true);
3971  *   return;
3972  * }
3973  * AtomicAccess::release_store(&tl->_vthread, false);
3974  */
3975 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3976   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3977 
3978   Node* input_memory_state = reset_memory();
3979   set_all_memory(input_memory_state);
3980 
3981   // The most significant bit of the u2 is used to denote thread exclusion
3982   Node* excluded_mask = _gvn.intcon(1 << 15);
3983   // The epoch generation is the range [1-32767]
3984   Node* epoch_mask = _gvn.intcon(32767);
3985 
3986   Node* const carrierThread = generate_current_thread(jt);
3987   // If thread != carrierThread, this is a virtual thread.
3988   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3989   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3990   IfNode* iff_thread_not_equal_carrierThread =
3991     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3992 
3993   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3994 
3995   // False branch, is carrierThread.
3996   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3997   // Store release
3998   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3999 
4000   set_all_memory(input_memory_state);
4001 
4002   // True branch, is virtual thread.
4003   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4004   set_control(thread_not_equal_carrierThread);
4005 
4006   // Load the raw epoch value from the vthread.
4007   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4008   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4009                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4010 
4011   // Mask off the excluded information from the epoch.
4012   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4013 
4014   // Load the tid field from the thread.
4015   Node* tid = load_field_from_object(thread, "tid", "J");
4016 
4017   // Store the vthread tid to the jfr thread local.
4018   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4019   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4020 
4021   // Branch is_excluded to conditionalize updating the epoch .
4022   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4023   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4024   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4025 
4026   // True branch, vthread is excluded, no need to write epoch info.
4027   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4028   set_control(excluded);
4029   Node* vthread_is_excluded = _gvn.intcon(1);
4030 
4031   // False branch, vthread is included, update epoch info.
4032   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4033   set_control(included);
4034   Node* vthread_is_included = _gvn.intcon(0);
4035 
4036   // Get epoch value.
4037   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4038 
4039   // Store the vthread epoch to the jfr thread local.
4040   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4041   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4042 
4043   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4044   record_for_igvn(excluded_rgn);
4045   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4046   record_for_igvn(excluded_mem);
4047   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4048   record_for_igvn(exclusion);
4049 
4050   // Merge the excluded control and memory.
4051   excluded_rgn->init_req(_true_path, excluded);
4052   excluded_rgn->init_req(_false_path, included);
4053   excluded_mem->init_req(_true_path, tid_memory);
4054   excluded_mem->init_req(_false_path, included_memory);
4055   exclusion->init_req(_true_path, vthread_is_excluded);
4056   exclusion->init_req(_false_path, vthread_is_included);
4057 
4058   // Set intermediate state.
4059   set_control(_gvn.transform(excluded_rgn));
4060   set_all_memory(excluded_mem);
4061 
4062   // Store the vthread exclusion state to the jfr thread local.
4063   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4064   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4065 
4066   // Store release
4067   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4068 
4069   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4070   record_for_igvn(thread_compare_rgn);
4071   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4072   record_for_igvn(thread_compare_mem);
4073   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4074   record_for_igvn(vthread);
4075 
4076   // Merge the thread_compare control and memory.
4077   thread_compare_rgn->init_req(_true_path, control());
4078   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4079   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4080   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4081 
4082   // Set output state.
4083   set_control(_gvn.transform(thread_compare_rgn));
4084   set_all_memory(_gvn.transform(thread_compare_mem));
4085 }
4086 
4087 #endif // JFR_HAVE_INTRINSICS
4088 
4089 //------------------------inline_native_currentCarrierThread------------------
4090 bool LibraryCallKit::inline_native_currentCarrierThread() {
4091   Node* junk = nullptr;
4092   set_result(generate_current_thread(junk));
4093   return true;
4094 }
4095 
4096 //------------------------inline_native_currentThread------------------
4097 bool LibraryCallKit::inline_native_currentThread() {
4098   Node* junk = nullptr;
4099   set_result(generate_virtual_thread(junk));
4100   return true;
4101 }
4102 
4103 //------------------------inline_native_setVthread------------------
4104 bool LibraryCallKit::inline_native_setCurrentThread() {
4105   assert(C->method()->changes_current_thread(),
4106          "method changes current Thread but is not annotated ChangesCurrentThread");
4107   Node* arr = argument(1);
4108   Node* thread = _gvn.transform(new ThreadLocalNode());
4109   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4110   Node* thread_obj_handle
4111     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4112   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4113   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4114 
4115   // Change the _monitor_owner_id of the JavaThread
4116   Node* tid = load_field_from_object(arr, "tid", "J");
4117   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4118   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4119 
4120   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4121   return true;
4122 }
4123 
4124 const Type* LibraryCallKit::scopedValueCache_type() {
4125   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4126   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4127   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4128 
4129   // Because we create the scopedValue cache lazily we have to make the
4130   // type of the result BotPTR.
4131   bool xk = etype->klass_is_exact();
4132   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4133   return objects_type;
4134 }
4135 
4136 Node* LibraryCallKit::scopedValueCache_helper() {
4137   Node* thread = _gvn.transform(new ThreadLocalNode());
4138   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4139   // We cannot use immutable_memory() because we might flip onto a
4140   // different carrier thread, at which point we'll need to use that
4141   // carrier thread's cache.
4142   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4143   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4144   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4145 }
4146 
4147 //------------------------inline_native_scopedValueCache------------------
4148 bool LibraryCallKit::inline_native_scopedValueCache() {
4149   Node* cache_obj_handle = scopedValueCache_helper();
4150   const Type* objects_type = scopedValueCache_type();
4151   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4152 
4153   return true;
4154 }
4155 
4156 //------------------------inline_native_setScopedValueCache------------------
4157 bool LibraryCallKit::inline_native_setScopedValueCache() {
4158   Node* arr = argument(0);
4159   Node* cache_obj_handle = scopedValueCache_helper();
4160   const Type* objects_type = scopedValueCache_type();
4161 
4162   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4163   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4164 
4165   return true;
4166 }
4167 
4168 //------------------------inline_native_Continuation_pin and unpin-----------
4169 
4170 // Shared implementation routine for both pin and unpin.
4171 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4172   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4173 
4174   // Save input memory.
4175   Node* input_memory_state = reset_memory();
4176   set_all_memory(input_memory_state);
4177 
4178   // TLS
4179   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4180   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4181   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4182 
4183   // Null check the last continuation object.
4184   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4185   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4186   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4187 
4188   // False path, last continuation is null.
4189   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4190 
4191   // True path, last continuation is not null.
4192   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4193 
4194   set_control(continuation_is_not_null);
4195 
4196   // Load the pin count from the last continuation.
4197   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4198   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4199 
4200   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4201   Node* pin_count_rhs;
4202   if (unpin) {
4203     pin_count_rhs = _gvn.intcon(0);
4204   } else {
4205     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4206   }
4207   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4208   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4209   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4210 
4211   // True branch, pin count over/underflow.
4212   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4213   {
4214     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4215     // which will throw IllegalStateException for pin count over/underflow.
4216     // No memory changed so far - we can use memory create by reset_memory()
4217     // at the beginning of this intrinsic. No need to call reset_memory() again.
4218     PreserveJVMState pjvms(this);
4219     set_control(pin_count_over_underflow);
4220     uncommon_trap(Deoptimization::Reason_intrinsic,
4221                   Deoptimization::Action_none);
4222     assert(stopped(), "invariant");
4223   }
4224 
4225   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4226   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4227   set_control(valid_pin_count);
4228 
4229   Node* next_pin_count;
4230   if (unpin) {
4231     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4232   } else {
4233     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4234   }
4235 
4236   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4237 
4238   // Result of top level CFG and Memory.
4239   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4240   record_for_igvn(result_rgn);
4241   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4242   record_for_igvn(result_mem);
4243 
4244   result_rgn->init_req(_true_path, valid_pin_count);
4245   result_rgn->init_req(_false_path, continuation_is_null);
4246   result_mem->init_req(_true_path, reset_memory());
4247   result_mem->init_req(_false_path, input_memory_state);
4248 
4249   // Set output state.
4250   set_control(_gvn.transform(result_rgn));
4251   set_all_memory(_gvn.transform(result_mem));
4252 
4253   return true;
4254 }
4255 
4256 //---------------------------load_mirror_from_klass----------------------------
4257 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4258 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4259   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4260   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4261   // mirror = ((OopHandle)mirror)->resolve();
4262   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4263 }
4264 
4265 //-----------------------load_klass_from_mirror_common-------------------------
4266 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4267 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4268 // and branch to the given path on the region.
4269 // If never_see_null, take an uncommon trap on null, so we can optimistically
4270 // compile for the non-null case.
4271 // If the region is null, force never_see_null = true.
4272 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4273                                                     bool never_see_null,
4274                                                     RegionNode* region,
4275                                                     int null_path,
4276                                                     int offset) {
4277   if (region == nullptr)  never_see_null = true;
4278   Node* p = basic_plus_adr(mirror, offset);
4279   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4280   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4281   Node* null_ctl = top();
4282   kls = null_check_oop(kls, &null_ctl, never_see_null);
4283   if (region != nullptr) {
4284     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4285     region->init_req(null_path, null_ctl);
4286   } else {
4287     assert(null_ctl == top(), "no loose ends");
4288   }
4289   return kls;
4290 }
4291 
4292 //--------------------(inline_native_Class_query helpers)---------------------
4293 // Use this for JVM_ACC_INTERFACE.
4294 // Fall through if (mods & mask) == bits, take the guard otherwise.
4295 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4296                                                  ByteSize offset, const Type* type, BasicType bt) {
4297   // Branch around if the given klass has the given modifier bit set.
4298   // Like generate_guard, adds a new path onto the region.
4299   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4300   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4301   Node* mask = intcon(modifier_mask);
4302   Node* bits = intcon(modifier_bits);
4303   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4304   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4305   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4306   return generate_fair_guard(bol, region);
4307 }
4308 
4309 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4310   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4311                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4312 }
4313 
4314 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4315 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4316   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4317                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4318 }
4319 
4320 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4321   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4322 }
4323 
4324 //-------------------------inline_native_Class_query-------------------
4325 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4326   const Type* return_type = TypeInt::BOOL;
4327   Node* prim_return_value = top();  // what happens if it's a primitive class?
4328   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4329   bool expect_prim = false;     // most of these guys expect to work on refs
4330 
4331   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4332 
4333   Node* mirror = argument(0);
4334   Node* obj    = top();
4335 
4336   switch (id) {
4337   case vmIntrinsics::_isInstance:
4338     // nothing is an instance of a primitive type
4339     prim_return_value = intcon(0);
4340     obj = argument(1);
4341     break;
4342   case vmIntrinsics::_isHidden:
4343     prim_return_value = intcon(0);
4344     break;
4345   case vmIntrinsics::_getSuperclass:
4346     prim_return_value = null();
4347     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4348     break;
4349   default:
4350     fatal_unexpected_iid(id);
4351     break;
4352   }
4353 
4354   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4355   if (mirror_con == nullptr)  return false;  // cannot happen?
4356 
4357 #ifndef PRODUCT
4358   if (C->print_intrinsics() || C->print_inlining()) {
4359     ciType* k = mirror_con->java_mirror_type();
4360     if (k) {
4361       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4362       k->print_name();
4363       tty->cr();
4364     }
4365   }
4366 #endif
4367 
4368   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4369   RegionNode* region = new RegionNode(PATH_LIMIT);
4370   record_for_igvn(region);
4371   PhiNode* phi = new PhiNode(region, return_type);
4372 
4373   // The mirror will never be null of Reflection.getClassAccessFlags, however
4374   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4375   // if it is. See bug 4774291.
4376 
4377   // For Reflection.getClassAccessFlags(), the null check occurs in
4378   // the wrong place; see inline_unsafe_access(), above, for a similar
4379   // situation.
4380   mirror = null_check(mirror);
4381   // If mirror or obj is dead, only null-path is taken.
4382   if (stopped())  return true;
4383 
4384   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4385 
4386   // Now load the mirror's klass metaobject, and null-check it.
4387   // Side-effects region with the control path if the klass is null.
4388   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4389   // If kls is null, we have a primitive mirror.
4390   phi->init_req(_prim_path, prim_return_value);
4391   if (stopped()) { set_result(region, phi); return true; }
4392   bool safe_for_replace = (region->in(_prim_path) == top());
4393 
4394   Node* p;  // handy temp
4395   Node* null_ctl;
4396 
4397   // Now that we have the non-null klass, we can perform the real query.
4398   // For constant classes, the query will constant-fold in LoadNode::Value.
4399   Node* query_value = top();
4400   switch (id) {
4401   case vmIntrinsics::_isInstance:
4402     // nothing is an instance of a primitive type
4403     query_value = gen_instanceof(obj, kls, safe_for_replace);
4404     break;
4405 
4406   case vmIntrinsics::_isHidden:
4407     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4408     if (generate_hidden_class_guard(kls, region) != nullptr)
4409       // A guard was added.  If the guard is taken, it was an hidden class.
4410       phi->add_req(intcon(1));
4411     // If we fall through, it's a plain class.
4412     query_value = intcon(0);
4413     break;
4414 
4415 
4416   case vmIntrinsics::_getSuperclass:
4417     // The rules here are somewhat unfortunate, but we can still do better
4418     // with random logic than with a JNI call.
4419     // Interfaces store null or Object as _super, but must report null.
4420     // Arrays store an intermediate super as _super, but must report Object.
4421     // Other types can report the actual _super.
4422     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4423     if (generate_array_guard(kls, region) != nullptr) {
4424       // A guard was added.  If the guard is taken, it was an array.
4425       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4426     }
4427     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4428     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4429     if (generate_interface_guard(kls, region) != nullptr) {
4430       // A guard was added.  If the guard is taken, it was an interface.
4431       phi->add_req(null());
4432     }
4433     // If we fall through, it's a plain class.  Get its _super.
4434     if (!stopped()) {
4435       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4436       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4437       null_ctl = top();
4438       kls = null_check_oop(kls, &null_ctl);
4439       if (null_ctl != top()) {
4440         // If the guard is taken, Object.superClass is null (both klass and mirror).
4441         region->add_req(null_ctl);
4442         phi   ->add_req(null());
4443       }
4444       if (!stopped()) {
4445         query_value = load_mirror_from_klass(kls);
4446       }
4447     }
4448     break;
4449 
4450   default:
4451     fatal_unexpected_iid(id);
4452     break;
4453   }
4454 
4455   // Fall-through is the normal case of a query to a real class.
4456   phi->init_req(1, query_value);
4457   region->init_req(1, control());
4458 
4459   C->set_has_split_ifs(true); // Has chance for split-if optimization
4460   set_result(region, phi);
4461   return true;
4462 }
4463 
4464 
4465 //-------------------------inline_Class_cast-------------------
4466 bool LibraryCallKit::inline_Class_cast() {
4467   Node* mirror = argument(0); // Class
4468   Node* obj    = argument(1);
4469   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4470   if (mirror_con == nullptr) {
4471     return false;  // dead path (mirror->is_top()).
4472   }
4473   if (obj == nullptr || obj->is_top()) {
4474     return false;  // dead path
4475   }
4476   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4477 
4478   // First, see if Class.cast() can be folded statically.
4479   // java_mirror_type() returns non-null for compile-time Class constants.
4480   ciType* tm = mirror_con->java_mirror_type();
4481   if (tm != nullptr && tm->is_klass() &&
4482       tp != nullptr) {
4483     if (!tp->is_loaded()) {
4484       // Don't use intrinsic when class is not loaded.
4485       return false;
4486     } else {
4487       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4488       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4489       if (static_res == Compile::SSC_always_true) {
4490         // isInstance() is true - fold the code.
4491         set_result(obj);
4492         return true;
4493       } else if (static_res == Compile::SSC_always_false) {
4494         // Don't use intrinsic, have to throw ClassCastException.
4495         // If the reference is null, the non-intrinsic bytecode will
4496         // be optimized appropriately.
4497         return false;
4498       }
4499     }
4500   }
4501 
4502   // Bailout intrinsic and do normal inlining if exception path is frequent.
4503   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4504     return false;
4505   }
4506 
4507   // Generate dynamic checks.
4508   // Class.cast() is java implementation of _checkcast bytecode.
4509   // Do checkcast (Parse::do_checkcast()) optimizations here.
4510 
4511   mirror = null_check(mirror);
4512   // If mirror is dead, only null-path is taken.
4513   if (stopped()) {
4514     return true;
4515   }
4516 
4517   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4518   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4519   RegionNode* region = new RegionNode(PATH_LIMIT);
4520   record_for_igvn(region);
4521 
4522   // Now load the mirror's klass metaobject, and null-check it.
4523   // If kls is null, we have a primitive mirror and
4524   // nothing is an instance of a primitive type.
4525   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4526 
4527   Node* res = top();
4528   Node* io = i_o();
4529   Node* mem = merged_memory();
4530   SafePointNode* new_cast_failure_map = nullptr;
4531 
4532   if (!stopped()) {
4533 
4534     Node* bad_type_ctrl = top();
4535     // Do checkcast optimizations.
4536     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4537     region->init_req(_bad_type_path, bad_type_ctrl);
4538   }
4539   if (region->in(_prim_path) != top() ||
4540       region->in(_bad_type_path) != top() ||
4541       region->in(_npe_path) != top()) {
4542     // Let Interpreter throw ClassCastException.
4543     PreserveJVMState pjvms(this);
4544     if (new_cast_failure_map != nullptr) {
4545       // The current map on the success path could have been modified. Use the dedicated failure path map.
4546       set_map(new_cast_failure_map);
4547     }
4548     set_control(_gvn.transform(region));
4549     // Set IO and memory because gen_checkcast may override them when buffering inline types
4550     set_i_o(io);
4551     set_all_memory(mem);
4552     uncommon_trap(Deoptimization::Reason_intrinsic,
4553                   Deoptimization::Action_maybe_recompile);
4554   }
4555   if (!stopped()) {
4556     set_result(res);
4557   }
4558   return true;
4559 }
4560 
4561 
4562 //--------------------------inline_native_subtype_check------------------------
4563 // This intrinsic takes the JNI calls out of the heart of
4564 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4565 bool LibraryCallKit::inline_native_subtype_check() {
4566   // Pull both arguments off the stack.
4567   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4568   args[0] = argument(0);
4569   args[1] = argument(1);
4570   Node* klasses[2];             // corresponding Klasses: superk, subk
4571   klasses[0] = klasses[1] = top();
4572 
4573   enum {
4574     // A full decision tree on {superc is prim, subc is prim}:
4575     _prim_0_path = 1,           // {P,N} => false
4576                                 // {P,P} & superc!=subc => false
4577     _prim_same_path,            // {P,P} & superc==subc => true
4578     _prim_1_path,               // {N,P} => false
4579     _ref_subtype_path,          // {N,N} & subtype check wins => true
4580     _both_ref_path,             // {N,N} & subtype check loses => false
4581     PATH_LIMIT
4582   };
4583 
4584   RegionNode* region = new RegionNode(PATH_LIMIT);
4585   RegionNode* prim_region = new RegionNode(2);
4586   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4587   record_for_igvn(region);
4588   record_for_igvn(prim_region);
4589 
4590   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4591   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4592   int class_klass_offset = java_lang_Class::klass_offset();
4593 
4594   // First null-check both mirrors and load each mirror's klass metaobject.
4595   int which_arg;
4596   for (which_arg = 0; which_arg <= 1; which_arg++) {
4597     Node* arg = args[which_arg];
4598     arg = null_check(arg);
4599     if (stopped())  break;
4600     args[which_arg] = arg;
4601 
4602     Node* p = basic_plus_adr(arg, class_klass_offset);
4603     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4604     klasses[which_arg] = _gvn.transform(kls);
4605   }
4606 
4607   // Having loaded both klasses, test each for null.
4608   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4609   for (which_arg = 0; which_arg <= 1; which_arg++) {
4610     Node* kls = klasses[which_arg];
4611     Node* null_ctl = top();
4612     kls = null_check_oop(kls, &null_ctl, never_see_null);
4613     if (which_arg == 0) {
4614       prim_region->init_req(1, null_ctl);
4615     } else {
4616       region->init_req(_prim_1_path, null_ctl);
4617     }
4618     if (stopped())  break;
4619     klasses[which_arg] = kls;
4620   }
4621 
4622   if (!stopped()) {
4623     // now we have two reference types, in klasses[0..1]
4624     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4625     Node* superk = klasses[0];  // the receiver
4626     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4627     region->set_req(_ref_subtype_path, control());
4628   }
4629 
4630   // If both operands are primitive (both klasses null), then
4631   // we must return true when they are identical primitives.
4632   // It is convenient to test this after the first null klass check.
4633   // This path is also used if superc is a value mirror.
4634   set_control(_gvn.transform(prim_region));
4635   if (!stopped()) {
4636     // Since superc is primitive, make a guard for the superc==subc case.
4637     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4638     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4639     generate_fair_guard(bol_eq, region);
4640     if (region->req() == PATH_LIMIT+1) {
4641       // A guard was added.  If the added guard is taken, superc==subc.
4642       region->swap_edges(PATH_LIMIT, _prim_same_path);
4643       region->del_req(PATH_LIMIT);
4644     }
4645     region->set_req(_prim_0_path, control()); // Not equal after all.
4646   }
4647 
4648   // these are the only paths that produce 'true':
4649   phi->set_req(_prim_same_path,   intcon(1));
4650   phi->set_req(_ref_subtype_path, intcon(1));
4651 
4652   // pull together the cases:
4653   assert(region->req() == PATH_LIMIT, "sane region");
4654   for (uint i = 1; i < region->req(); i++) {
4655     Node* ctl = region->in(i);
4656     if (ctl == nullptr || ctl == top()) {
4657       region->set_req(i, top());
4658       phi   ->set_req(i, top());
4659     } else if (phi->in(i) == nullptr) {
4660       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4661     }
4662   }
4663 
4664   set_control(_gvn.transform(region));
4665   set_result(_gvn.transform(phi));
4666   return true;
4667 }
4668 
4669 //---------------------generate_array_guard_common------------------------
4670 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4671 
4672   if (stopped()) {
4673     return nullptr;
4674   }
4675 
4676   // Like generate_guard, adds a new path onto the region.
4677   jint  layout_con = 0;
4678   Node* layout_val = get_layout_helper(kls, layout_con);
4679   if (layout_val == nullptr) {
4680     bool query = 0;
4681     switch(kind) {
4682       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4683       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4684       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4685       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4686       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4687       default:
4688         ShouldNotReachHere();
4689     }
4690     if (!query) {
4691       return nullptr;                       // never a branch
4692     } else {                             // always a branch
4693       Node* always_branch = control();
4694       if (region != nullptr)
4695         region->add_req(always_branch);
4696       set_control(top());
4697       return always_branch;
4698     }
4699   }
4700   unsigned int value = 0;
4701   BoolTest::mask btest = BoolTest::illegal;
4702   switch(kind) {
4703     case RefArray:
4704     case NonRefArray: {
4705       value = Klass::_lh_array_tag_ref_value;
4706       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4707       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4708       break;
4709     }
4710     case TypeArray: {
4711       value = Klass::_lh_array_tag_type_value;
4712       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4713       btest = BoolTest::eq;
4714       break;
4715     }
4716     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4717     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4718     default:
4719       ShouldNotReachHere();
4720   }
4721   // Now test the correct condition.
4722   jint nval = (jint)value;
4723   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4724   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4725   Node* ctrl = generate_fair_guard(bol, region);
4726   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4727   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4728     // Keep track of the fact that 'obj' is an array to prevent
4729     // array specific accesses from floating above the guard.
4730     *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4731   }
4732   return ctrl;
4733 }
4734 
4735 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4736 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4737 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4738 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4739   assert(null_free || atomic, "nullable implies atomic");
4740   Node* componentType = argument(0);
4741   Node* length = argument(1);
4742   Node* init_val = null_free ? argument(2) : nullptr;
4743 
4744   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4745   if (tp != nullptr) {
4746     ciInstanceKlass* ik = tp->instance_klass();
4747     if (ik == C->env()->Class_klass()) {
4748       ciType* t = tp->java_mirror_type();
4749       if (t != nullptr && t->is_inlinetype()) {
4750 
4751         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4752         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4753 
4754         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4755         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4756           return false;
4757         }
4758 
4759         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4760           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4761           if (null_free) {
4762             if (init_val->is_InlineType()) {
4763               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4764                 // Zeroing is enough because the init value is the all-zero value
4765                 init_val = nullptr;
4766               } else {
4767                 init_val = init_val->as_InlineType()->buffer(this);
4768               }
4769             }
4770             if (init_val != nullptr) {
4771 #ifdef ASSERT
4772               init_val = null_check(init_val);
4773               Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4774               {
4775                 PreserveJVMState pjvms(this);
4776                 set_control(wrong_type_ctl);
4777                 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4778                 stop_and_kill_map();
4779               }
4780 #endif
4781               init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4782             }
4783           }
4784           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4785           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4786           assert(arytype->is_null_free() == null_free, "inconsistency");
4787           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4788           set_result(obj);
4789           return true;
4790         }
4791       }
4792     }
4793   }
4794   return false;
4795 }
4796 
4797 // public static native boolean ValueClass::isFlatArray(Object array);
4798 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4799 // public static native boolean ValueClass::isAtomicArray(Object array);
4800 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4801   Node* array = argument(0);
4802 
4803   Node* bol;
4804   switch(check) {
4805     case IsFlat:
4806       bol = flat_array_test(load_object_klass(array));
4807       break;
4808     case IsNullRestricted:
4809       bol = null_free_array_test(array);
4810       break;
4811     case IsAtomic: {
4812       // See conditions in JVM_IsAtomicArray
4813       // 1. If not flat, then atomic, or else...
4814       RegionNode* atomic_region = new RegionNode(1);
4815       RegionNode* non_atomic_region = new RegionNode(1);
4816       Node* array_klass = load_object_klass(array);
4817       Node* is_flat_bol = flat_array_test(array_klass);
4818       IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
4819       atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
4820       set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
4821 
4822       // 2. ...if the layout is atomic, then atomic, or else...
4823       Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
4824 
4825       // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
4826       int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4827       Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
4828       Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
4829       int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
4830       Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
4831       Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
4832 
4833       // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
4834       Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
4835       Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
4836       IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
4837       Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
4838       Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
4839 
4840       Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
4841       Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
4842       Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
4843       IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
4844       Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
4845       Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
4846       atomic_region->add_req(is_naturally_atomic_ctl);
4847       non_atomic_region->add_req(is_not_naturally_atomic_ctl);
4848 
4849       Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
4850       Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
4851       Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
4852       IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
4853       Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
4854       Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
4855       atomic_region->add_req(is_empty_inline_type_ctl);
4856       non_atomic_region->add_req(is_nonempty_inline_type_ctl);
4857 
4858       // ...non-atomic, but we tried everything.
4859       RegionNode* decision = new RegionNode(3);
4860       decision->set_req(1, _gvn.transform(atomic_region));
4861       decision->set_req(2, _gvn.transform(non_atomic_region));
4862       PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
4863       result->set_req(2, intcon(0));
4864       set_control(_gvn.transform(decision));
4865       set_result(_gvn.transform(result));
4866       return true;
4867     }
4868     default:
4869       ShouldNotReachHere();
4870   }
4871 
4872   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4873   set_result(res);
4874   return true;
4875 }
4876 
4877 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4878 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4879 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4880   RegionNode* region = new RegionNode(2);
4881   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4882 
4883   if (type_array_guard) {
4884     generate_typeArray_guard(klass_node, region);
4885     if (region->req() == 3) {
4886       phi->add_req(klass_node);
4887     }
4888   }
4889   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4890   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4891 
4892   // Can be null if not initialized yet, just deopt
4893   Node* null_ctl = top();
4894   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4895 
4896   region->init_req(1, control());
4897   phi->init_req(1, refined_klass);
4898 
4899   set_control(_gvn.transform(region));
4900   return _gvn.transform(phi);
4901 }
4902 
4903 // Load the non-refined array klass from an ObjArrayKlass.
4904 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4905   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4906   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4907     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4908   }
4909 
4910   RegionNode* region = new RegionNode(2);
4911   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4912 
4913   generate_typeArray_guard(klass_node, region);
4914   if (region->req() == 3) {
4915     phi->add_req(klass_node);
4916   }
4917   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4918   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4919 
4920   region->init_req(1, control());
4921   phi->init_req(1, super_klass);
4922 
4923   set_control(_gvn.transform(region));
4924   return _gvn.transform(phi);
4925 }
4926 
4927 //-----------------------inline_native_newArray--------------------------
4928 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4929 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4930 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4931   Node* mirror;
4932   Node* count_val;
4933   if (uninitialized) {
4934     null_check_receiver();
4935     mirror    = argument(1);
4936     count_val = argument(2);
4937   } else {
4938     mirror    = argument(0);
4939     count_val = argument(1);
4940   }
4941 
4942   mirror = null_check(mirror);
4943   // If mirror or obj is dead, only null-path is taken.
4944   if (stopped())  return true;
4945 
4946   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4947   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4948   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4949   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4950   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4951 
4952   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4953   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4954                                                   result_reg, _slow_path);
4955   Node* normal_ctl   = control();
4956   Node* no_array_ctl = result_reg->in(_slow_path);
4957 
4958   // Generate code for the slow case.  We make a call to newArray().
4959   set_control(no_array_ctl);
4960   if (!stopped()) {
4961     // Either the input type is void.class, or else the
4962     // array klass has not yet been cached.  Either the
4963     // ensuing call will throw an exception, or else it
4964     // will cache the array klass for next time.
4965     PreserveJVMState pjvms(this);
4966     CallJavaNode* slow_call = nullptr;
4967     if (uninitialized) {
4968       // Generate optimized virtual call (holder class 'Unsafe' is final)
4969       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4970     } else {
4971       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4972     }
4973     Node* slow_result = set_results_for_java_call(slow_call);
4974     // this->control() comes from set_results_for_java_call
4975     result_reg->set_req(_slow_path, control());
4976     result_val->set_req(_slow_path, slow_result);
4977     result_io ->set_req(_slow_path, i_o());
4978     result_mem->set_req(_slow_path, reset_memory());
4979   }
4980 
4981   set_control(normal_ctl);
4982   if (!stopped()) {
4983     // Normal case:  The array type has been cached in the java.lang.Class.
4984     // The following call works fine even if the array type is polymorphic.
4985     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4986 
4987     klass_node = load_default_refined_array_klass(klass_node);
4988 
4989     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4990     result_reg->init_req(_normal_path, control());
4991     result_val->init_req(_normal_path, obj);
4992     result_io ->init_req(_normal_path, i_o());
4993     result_mem->init_req(_normal_path, reset_memory());
4994 
4995     if (uninitialized) {
4996       // Mark the allocation so that zeroing is skipped
4997       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4998       alloc->maybe_set_complete(&_gvn);
4999     }
5000   }
5001 
5002   // Return the combined state.
5003   set_i_o(        _gvn.transform(result_io)  );
5004   set_all_memory( _gvn.transform(result_mem));
5005 
5006   C->set_has_split_ifs(true); // Has chance for split-if optimization
5007   set_result(result_reg, result_val);
5008   return true;
5009 }
5010 
5011 //----------------------inline_native_getLength--------------------------
5012 // public static native int java.lang.reflect.Array.getLength(Object array);
5013 bool LibraryCallKit::inline_native_getLength() {
5014   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5015 
5016   Node* array = null_check(argument(0));
5017   // If array is dead, only null-path is taken.
5018   if (stopped())  return true;
5019 
5020   // Deoptimize if it is a non-array.
5021   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5022 
5023   if (non_array != nullptr) {
5024     PreserveJVMState pjvms(this);
5025     set_control(non_array);
5026     uncommon_trap(Deoptimization::Reason_intrinsic,
5027                   Deoptimization::Action_maybe_recompile);
5028   }
5029 
5030   // If control is dead, only non-array-path is taken.
5031   if (stopped())  return true;
5032 
5033   // The works fine even if the array type is polymorphic.
5034   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5035   Node* result = load_array_length(array);
5036 
5037   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5038   set_result(result);
5039   return true;
5040 }
5041 
5042 //------------------------inline_array_copyOf----------------------------
5043 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5044 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5045 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5046   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5047 
5048   // Get the arguments.
5049   Node* original          = argument(0);
5050   Node* start             = is_copyOfRange? argument(1): intcon(0);
5051   Node* end               = is_copyOfRange? argument(2): argument(1);
5052   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5053 
5054   Node* newcopy = nullptr;
5055 
5056   // Set the original stack and the reexecute bit for the interpreter to reexecute
5057   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5058   { PreserveReexecuteState preexecs(this);
5059     jvms()->set_should_reexecute(true);
5060 
5061     array_type_mirror = null_check(array_type_mirror);
5062     original          = null_check(original);
5063 
5064     // Check if a null path was taken unconditionally.
5065     if (stopped())  return true;
5066 
5067     Node* orig_length = load_array_length(original);
5068 
5069     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5070     klass_node = null_check(klass_node);
5071 
5072     RegionNode* bailout = new RegionNode(1);
5073     record_for_igvn(bailout);
5074 
5075     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5076     // Bail out if that is so.
5077     // Inline type array may have object field that would require a
5078     // write barrier. Conservatively, go to slow path.
5079     // TODO 8251971: Optimize for the case when flat src/dst are later found
5080     // to not contain oops (i.e., move this check to the macro expansion phase).
5081     // TODO 8382226: Revisit for flat abstract value class arrays
5082     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5083     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5084     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5085     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5086                         // Can src array be flat and contain oops?
5087                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5088                         // Can dest array be flat and contain oops?
5089                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5090     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5091 
5092     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5093 
5094     if (not_objArray != nullptr) {
5095       // Improve the klass node's type from the new optimistic assumption:
5096       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5097       bool not_flat = !UseArrayFlattening;
5098       bool not_null_free = !Arguments::is_valhalla_enabled();
5099       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5100       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5101       refined_klass_node = _gvn.transform(cast);
5102     }
5103 
5104     // Bail out if either start or end is negative.
5105     generate_negative_guard(start, bailout, &start);
5106     generate_negative_guard(end,   bailout, &end);
5107 
5108     Node* length = end;
5109     if (_gvn.type(start) != TypeInt::ZERO) {
5110       length = _gvn.transform(new SubINode(end, start));
5111     }
5112 
5113     // Bail out if length is negative (i.e., if start > end).
5114     // Without this the new_array would throw
5115     // NegativeArraySizeException but IllegalArgumentException is what
5116     // should be thrown
5117     generate_negative_guard(length, bailout, &length);
5118 
5119     // Handle inline type arrays
5120     // TODO 8251971 This is too strong
5121     generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5122     generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5123     generate_fair_guard(null_free_array_test(original), bailout);
5124 
5125     // Bail out if start is larger than the original length
5126     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5127     generate_negative_guard(orig_tail, bailout, &orig_tail);
5128 
5129     if (bailout->req() > 1) {
5130       PreserveJVMState pjvms(this);
5131       set_control(_gvn.transform(bailout));
5132       uncommon_trap(Deoptimization::Reason_intrinsic,
5133                     Deoptimization::Action_maybe_recompile);
5134     }
5135 
5136     if (!stopped()) {
5137       // How many elements will we copy from the original?
5138       // The answer is MinI(orig_tail, length).
5139       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5140 
5141       // Generate a direct call to the right arraycopy function(s).
5142       // We know the copy is disjoint but we might not know if the
5143       // oop stores need checking.
5144       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5145       // This will fail a store-check if x contains any non-nulls.
5146 
5147       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5148       // loads/stores but it is legal only if we're sure the
5149       // Arrays.copyOf would succeed. So we need all input arguments
5150       // to the copyOf to be validated, including that the copy to the
5151       // new array won't trigger an ArrayStoreException. That subtype
5152       // check can be optimized if we know something on the type of
5153       // the input array from type speculation.
5154       if (_gvn.type(klass_node)->singleton()) {
5155         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5156         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5157 
5158         int test = C->static_subtype_check(superk, subk);
5159         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5160           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5161           if (t_original->speculative_type() != nullptr) {
5162             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5163           }
5164         }
5165       }
5166 
5167       bool validated = false;
5168       // Reason_class_check rather than Reason_intrinsic because we
5169       // want to intrinsify even if this traps.
5170       if (!too_many_traps(Deoptimization::Reason_class_check)) {
5171         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5172 
5173         if (not_subtype_ctrl != top()) {
5174           PreserveJVMState pjvms(this);
5175           set_control(not_subtype_ctrl);
5176           uncommon_trap(Deoptimization::Reason_class_check,
5177                         Deoptimization::Action_make_not_entrant);
5178           assert(stopped(), "Should be stopped");
5179         }
5180         validated = true;
5181       }
5182 
5183       if (!stopped()) {
5184         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5185 
5186         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5187                                                 load_object_klass(original), klass_node);
5188         if (!is_copyOfRange) {
5189           ac->set_copyof(validated);
5190         } else {
5191           ac->set_copyofrange(validated);
5192         }
5193         Node* n = _gvn.transform(ac);
5194         if (n == ac) {
5195           ac->connect_outputs(this);
5196         } else {
5197           assert(validated, "shouldn't transform if all arguments not validated");
5198           set_all_memory(n);
5199         }
5200       }
5201     }
5202   } // original reexecute is set back here
5203 
5204   C->set_has_split_ifs(true); // Has chance for split-if optimization
5205   if (!stopped()) {
5206     set_result(newcopy);
5207   }
5208   return true;
5209 }
5210 
5211 
5212 //----------------------generate_virtual_guard---------------------------
5213 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5214 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5215                                              RegionNode* slow_region) {
5216   ciMethod* method = callee();
5217   int vtable_index = method->vtable_index();
5218   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5219          "bad index %d", vtable_index);
5220   // Get the Method* out of the appropriate vtable entry.
5221   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5222                      vtable_index*vtableEntry::size_in_bytes() +
5223                      in_bytes(vtableEntry::method_offset());
5224   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5225   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5226 
5227   // Compare the target method with the expected method (e.g., Object.hashCode).
5228   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5229 
5230   Node* native_call = makecon(native_call_addr);
5231   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5232   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5233 
5234   return generate_slow_guard(test_native, slow_region);
5235 }
5236 
5237 //-----------------------generate_method_call----------------------------
5238 // Use generate_method_call to make a slow-call to the real
5239 // method if the fast path fails.  An alternative would be to
5240 // use a stub like OptoRuntime::slow_arraycopy_Java.
5241 // This only works for expanding the current library call,
5242 // not another intrinsic.  (E.g., don't use this for making an
5243 // arraycopy call inside of the copyOf intrinsic.)
5244 CallJavaNode*
5245 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5246   // When compiling the intrinsic method itself, do not use this technique.
5247   guarantee(callee() != C->method(), "cannot make slow-call to self");
5248 
5249   ciMethod* method = callee();
5250   // ensure the JVMS we have will be correct for this call
5251   guarantee(method_id == method->intrinsic_id(), "must match");
5252 
5253   const TypeFunc* tf = TypeFunc::make(method);
5254   if (res_not_null) {
5255     assert(tf->return_type() == T_OBJECT, "");
5256     const TypeTuple* range = tf->range_cc();
5257     const Type** fields = TypeTuple::fields(range->cnt());
5258     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5259     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5260     tf = TypeFunc::make(tf->domain_cc(), new_range);
5261   }
5262   CallJavaNode* slow_call;
5263   if (is_static) {
5264     assert(!is_virtual, "");
5265     slow_call = new CallStaticJavaNode(C, tf,
5266                            SharedRuntime::get_resolve_static_call_stub(), method);
5267   } else if (is_virtual) {
5268     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5269     int vtable_index = Method::invalid_vtable_index;
5270     if (UseInlineCaches) {
5271       // Suppress the vtable call
5272     } else {
5273       // hashCode and clone are not a miranda methods,
5274       // so the vtable index is fixed.
5275       // No need to use the linkResolver to get it.
5276        vtable_index = method->vtable_index();
5277        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5278               "bad index %d", vtable_index);
5279     }
5280     slow_call = new CallDynamicJavaNode(tf,
5281                           SharedRuntime::get_resolve_virtual_call_stub(),
5282                           method, vtable_index);
5283   } else {  // neither virtual nor static:  opt_virtual
5284     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5285     slow_call = new CallStaticJavaNode(C, tf,
5286                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5287     slow_call->set_optimized_virtual(true);
5288   }
5289   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5290     // To be able to issue a direct call (optimized virtual or virtual)
5291     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5292     // about the method being invoked should be attached to the call site to
5293     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5294     slow_call->set_override_symbolic_info(true);
5295   }
5296   set_arguments_for_java_call(slow_call);
5297   set_edges_for_java_call(slow_call);
5298   return slow_call;
5299 }
5300 
5301 
5302 /**
5303  * Build special case code for calls to hashCode on an object. This call may
5304  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5305  * slightly different code.
5306  */
5307 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5308   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5309   assert(!(is_virtual && is_static), "either virtual, special, or static");
5310 
5311   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5312 
5313   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5314   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5315   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5316   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5317   Node* obj = argument(0);
5318 
5319   // Don't intrinsify hashcode on inline types for now.
5320   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5321   if (gvn().type(obj)->is_inlinetypeptr()) {
5322     return false;
5323   }
5324 
5325   if (!is_static) {
5326     // Check for hashing null object
5327     obj = null_check_receiver();
5328     if (stopped())  return true;        // unconditionally null
5329     result_reg->init_req(_null_path, top());
5330     result_val->init_req(_null_path, top());
5331   } else {
5332     // Do a null check, and return zero if null.
5333     // System.identityHashCode(null) == 0
5334     Node* null_ctl = top();
5335     obj = null_check_oop(obj, &null_ctl);
5336     result_reg->init_req(_null_path, null_ctl);
5337     result_val->init_req(_null_path, _gvn.intcon(0));
5338   }
5339 
5340   // Unconditionally null?  Then return right away.
5341   if (stopped()) {
5342     set_control( result_reg->in(_null_path));
5343     if (!stopped())
5344       set_result(result_val->in(_null_path));
5345     return true;
5346   }
5347 
5348   // We only go to the fast case code if we pass a number of guards.  The
5349   // paths which do not pass are accumulated in the slow_region.
5350   RegionNode* slow_region = new RegionNode(1);
5351   record_for_igvn(slow_region);
5352 
5353   // If this is a virtual call, we generate a funny guard.  We pull out
5354   // the vtable entry corresponding to hashCode() from the target object.
5355   // If the target method which we are calling happens to be the native
5356   // Object hashCode() method, we pass the guard.  We do not need this
5357   // guard for non-virtual calls -- the caller is known to be the native
5358   // Object hashCode().
5359   if (is_virtual) {
5360     // After null check, get the object's klass.
5361     Node* obj_klass = load_object_klass(obj);
5362     generate_virtual_guard(obj_klass, slow_region);
5363   }
5364 
5365   // Get the header out of the object, use LoadMarkNode when available
5366   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5367   // The control of the load must be null. Otherwise, the load can move before
5368   // the null check after castPP removal.
5369   Node* no_ctrl = nullptr;
5370   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5371 
5372   if (!UseObjectMonitorTable) {
5373     // Test the header to see if it is safe to read w.r.t. locking.
5374     // We cannot use the inline type mask as this may check bits that are overriden
5375     // by an object monitor's pointer when inflating locking.
5376     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5377     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5378     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5379     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5380     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5381 
5382     generate_slow_guard(test_monitor, slow_region);
5383   }
5384 
5385   // Get the hash value and check to see that it has been properly assigned.
5386   // We depend on hash_mask being at most 32 bits and avoid the use of
5387   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5388   // vm: see markWord.hpp.
5389   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5390   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5391   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5392   // This hack lets the hash bits live anywhere in the mark object now, as long
5393   // as the shift drops the relevant bits into the low 32 bits.  Note that
5394   // Java spec says that HashCode is an int so there's no point in capturing
5395   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5396   hshifted_header      = ConvX2I(hshifted_header);
5397   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5398 
5399   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5400   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5401   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5402 
5403   generate_slow_guard(test_assigned, slow_region);
5404 
5405   Node* init_mem = reset_memory();
5406   // fill in the rest of the null path:
5407   result_io ->init_req(_null_path, i_o());
5408   result_mem->init_req(_null_path, init_mem);
5409 
5410   result_val->init_req(_fast_path, hash_val);
5411   result_reg->init_req(_fast_path, control());
5412   result_io ->init_req(_fast_path, i_o());
5413   result_mem->init_req(_fast_path, init_mem);
5414 
5415   // Generate code for the slow case.  We make a call to hashCode().
5416   set_control(_gvn.transform(slow_region));
5417   if (!stopped()) {
5418     // No need for PreserveJVMState, because we're using up the present state.
5419     set_all_memory(init_mem);
5420     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5421     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5422     Node* slow_result = set_results_for_java_call(slow_call);
5423     // this->control() comes from set_results_for_java_call
5424     result_reg->init_req(_slow_path, control());
5425     result_val->init_req(_slow_path, slow_result);
5426     result_io  ->set_req(_slow_path, i_o());
5427     result_mem ->set_req(_slow_path, reset_memory());
5428   }
5429 
5430   // Return the combined state.
5431   set_i_o(        _gvn.transform(result_io)  );
5432   set_all_memory( _gvn.transform(result_mem));
5433 
5434   set_result(result_reg, result_val);
5435   return true;
5436 }
5437 
5438 //---------------------------inline_native_getClass----------------------------
5439 // public final native Class<?> java.lang.Object.getClass();
5440 //
5441 // Build special case code for calls to getClass on an object.
5442 bool LibraryCallKit::inline_native_getClass() {
5443   Node* obj = argument(0);
5444   if (obj->is_InlineType()) {
5445     const Type* t = _gvn.type(obj);
5446     if (t->maybe_null()) {
5447       null_check(obj);
5448     }
5449     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5450     return true;
5451   }
5452   obj = null_check_receiver();
5453   if (stopped())  return true;
5454   set_result(load_mirror_from_klass(load_object_klass(obj)));
5455   return true;
5456 }
5457 
5458 //-----------------inline_native_Reflection_getCallerClass---------------------
5459 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5460 //
5461 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5462 //
5463 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5464 // in that it must skip particular security frames and checks for
5465 // caller sensitive methods.
5466 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5467 #ifndef PRODUCT
5468   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5469     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5470   }
5471 #endif
5472 
5473   if (!jvms()->has_method()) {
5474 #ifndef PRODUCT
5475     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5476       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5477     }
5478 #endif
5479     return false;
5480   }
5481 
5482   // Walk back up the JVM state to find the caller at the required
5483   // depth.
5484   JVMState* caller_jvms = jvms();
5485 
5486   // Cf. JVM_GetCallerClass
5487   // NOTE: Start the loop at depth 1 because the current JVM state does
5488   // not include the Reflection.getCallerClass() frame.
5489   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5490     ciMethod* m = caller_jvms->method();
5491     switch (n) {
5492     case 0:
5493       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5494       break;
5495     case 1:
5496       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5497       if (!m->caller_sensitive()) {
5498 #ifndef PRODUCT
5499         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5500           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5501         }
5502 #endif
5503         return false;  // bail-out; let JVM_GetCallerClass do the work
5504       }
5505       break;
5506     default:
5507       if (!m->is_ignored_by_security_stack_walk()) {
5508         // We have reached the desired frame; return the holder class.
5509         // Acquire method holder as java.lang.Class and push as constant.
5510         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5511         ciInstance* caller_mirror = caller_klass->java_mirror();
5512         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5513 
5514 #ifndef PRODUCT
5515         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5516           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());
5517           tty->print_cr("  JVM state at this point:");
5518           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5519             ciMethod* m = jvms()->of_depth(i)->method();
5520             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5521           }
5522         }
5523 #endif
5524         return true;
5525       }
5526       break;
5527     }
5528   }
5529 
5530 #ifndef PRODUCT
5531   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5532     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5533     tty->print_cr("  JVM state at this point:");
5534     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5535       ciMethod* m = jvms()->of_depth(i)->method();
5536       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5537     }
5538   }
5539 #endif
5540 
5541   return false;  // bail-out; let JVM_GetCallerClass do the work
5542 }
5543 
5544 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5545   Node* arg = argument(0);
5546   Node* result = nullptr;
5547 
5548   switch (id) {
5549   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5550   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5551   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5552   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5553   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5554   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5555 
5556   case vmIntrinsics::_doubleToLongBits: {
5557     // two paths (plus control) merge in a wood
5558     RegionNode *r = new RegionNode(3);
5559     Node *phi = new PhiNode(r, TypeLong::LONG);
5560 
5561     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5562     // Build the boolean node
5563     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5564 
5565     // Branch either way.
5566     // NaN case is less traveled, which makes all the difference.
5567     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5568     Node *opt_isnan = _gvn.transform(ifisnan);
5569     assert( opt_isnan->is_If(), "Expect an IfNode");
5570     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5571     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5572 
5573     set_control(iftrue);
5574 
5575     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5576     Node *slow_result = longcon(nan_bits); // return NaN
5577     phi->init_req(1, _gvn.transform( slow_result ));
5578     r->init_req(1, iftrue);
5579 
5580     // Else fall through
5581     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5582     set_control(iffalse);
5583 
5584     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5585     r->init_req(2, iffalse);
5586 
5587     // Post merge
5588     set_control(_gvn.transform(r));
5589     record_for_igvn(r);
5590 
5591     C->set_has_split_ifs(true); // Has chance for split-if optimization
5592     result = phi;
5593     assert(result->bottom_type()->isa_long(), "must be");
5594     break;
5595   }
5596 
5597   case vmIntrinsics::_floatToIntBits: {
5598     // two paths (plus control) merge in a wood
5599     RegionNode *r = new RegionNode(3);
5600     Node *phi = new PhiNode(r, TypeInt::INT);
5601 
5602     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5603     // Build the boolean node
5604     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5605 
5606     // Branch either way.
5607     // NaN case is less traveled, which makes all the difference.
5608     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5609     Node *opt_isnan = _gvn.transform(ifisnan);
5610     assert( opt_isnan->is_If(), "Expect an IfNode");
5611     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5612     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5613 
5614     set_control(iftrue);
5615 
5616     static const jint nan_bits = 0x7fc00000;
5617     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5618     phi->init_req(1, _gvn.transform( slow_result ));
5619     r->init_req(1, iftrue);
5620 
5621     // Else fall through
5622     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5623     set_control(iffalse);
5624 
5625     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5626     r->init_req(2, iffalse);
5627 
5628     // Post merge
5629     set_control(_gvn.transform(r));
5630     record_for_igvn(r);
5631 
5632     C->set_has_split_ifs(true); // Has chance for split-if optimization
5633     result = phi;
5634     assert(result->bottom_type()->isa_int(), "must be");
5635     break;
5636   }
5637 
5638   default:
5639     fatal_unexpected_iid(id);
5640     break;
5641   }
5642   set_result(_gvn.transform(result));
5643   return true;
5644 }
5645 
5646 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5647   Node* arg = argument(0);
5648   Node* result = nullptr;
5649 
5650   switch (id) {
5651   case vmIntrinsics::_floatIsInfinite:
5652     result = new IsInfiniteFNode(arg);
5653     break;
5654   case vmIntrinsics::_floatIsFinite:
5655     result = new IsFiniteFNode(arg);
5656     break;
5657   case vmIntrinsics::_doubleIsInfinite:
5658     result = new IsInfiniteDNode(arg);
5659     break;
5660   case vmIntrinsics::_doubleIsFinite:
5661     result = new IsFiniteDNode(arg);
5662     break;
5663   default:
5664     fatal_unexpected_iid(id);
5665     break;
5666   }
5667   set_result(_gvn.transform(result));
5668   return true;
5669 }
5670 
5671 //----------------------inline_unsafe_copyMemory-------------------------
5672 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5673 
5674 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5675   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5676   const Type*       base_t = gvn.type(base);
5677 
5678   bool in_native = (base_t == TypePtr::NULL_PTR);
5679   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5680   bool is_mixed  = !in_heap && !in_native;
5681 
5682   if (is_mixed) {
5683     return true; // mixed accesses can touch both on-heap and off-heap memory
5684   }
5685   if (in_heap) {
5686     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5687     if (!is_prim_array) {
5688       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5689       // there's not enough type information available to determine proper memory slice for it.
5690       return true;
5691     }
5692   }
5693   return false;
5694 }
5695 
5696 bool LibraryCallKit::inline_unsafe_copyMemory() {
5697   if (callee()->is_static())  return false;  // caller must have the capability!
5698   null_check_receiver();  // null-check receiver
5699   if (stopped())  return true;
5700 
5701   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5702 
5703   Node* src_base =         argument(1);  // type: oop
5704   Node* src_off  = ConvL2X(argument(2)); // type: long
5705   Node* dst_base =         argument(4);  // type: oop
5706   Node* dst_off  = ConvL2X(argument(5)); // type: long
5707   Node* size     = ConvL2X(argument(7)); // type: long
5708 
5709   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5710          "fieldOffset must be byte-scaled");
5711 
5712   Node* src_addr = make_unsafe_address(src_base, src_off);
5713   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5714 
5715   Node* thread = _gvn.transform(new ThreadLocalNode());
5716   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5717   BasicType doing_unsafe_access_bt = T_BYTE;
5718   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5719 
5720   // update volatile field
5721   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5722 
5723   int flags = RC_LEAF | RC_NO_FP;
5724 
5725   const TypePtr* dst_type = TypePtr::BOTTOM;
5726 
5727   // Adjust memory effects of the runtime call based on input values.
5728   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5729       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5730     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5731 
5732     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5733     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5734       flags |= RC_NARROW_MEM; // narrow in memory
5735     }
5736   }
5737 
5738   // Call it.  Note that the length argument is not scaled.
5739   make_runtime_call(flags,
5740                     OptoRuntime::fast_arraycopy_Type(),
5741                     StubRoutines::unsafe_arraycopy(),
5742                     "unsafe_arraycopy",
5743                     dst_type,
5744                     src_addr, dst_addr, size XTOP);
5745 
5746   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5747 
5748   return true;
5749 }
5750 
5751 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5752 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5753 bool LibraryCallKit::inline_unsafe_setMemory() {
5754   if (callee()->is_static())  return false;  // caller must have the capability!
5755   null_check_receiver();  // null-check receiver
5756   if (stopped())  return true;
5757 
5758   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5759 
5760   Node* dst_base =         argument(1);  // type: oop
5761   Node* dst_off  = ConvL2X(argument(2)); // type: long
5762   Node* size     = ConvL2X(argument(4)); // type: long
5763   Node* byte     =         argument(6);  // type: byte
5764 
5765   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5766          "fieldOffset must be byte-scaled");
5767 
5768   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5769 
5770   Node* thread = _gvn.transform(new ThreadLocalNode());
5771   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5772   BasicType doing_unsafe_access_bt = T_BYTE;
5773   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5774 
5775   // update volatile field
5776   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5777 
5778   int flags = RC_LEAF | RC_NO_FP;
5779 
5780   const TypePtr* dst_type = TypePtr::BOTTOM;
5781 
5782   // Adjust memory effects of the runtime call based on input values.
5783   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5784     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5785 
5786     flags |= RC_NARROW_MEM; // narrow in memory
5787   }
5788 
5789   // Call it.  Note that the length argument is not scaled.
5790   make_runtime_call(flags,
5791                     OptoRuntime::unsafe_setmemory_Type(),
5792                     StubRoutines::unsafe_setmemory(),
5793                     "unsafe_setmemory",
5794                     dst_type,
5795                     dst_addr, size XTOP, byte);
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 #undef XTOP
5803 
5804 //------------------------clone_coping-----------------------------------
5805 // Helper function for inline_native_clone.
5806 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5807   assert(obj_size != nullptr, "");
5808   Node* raw_obj = alloc_obj->in(1);
5809   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5810 
5811   AllocateNode* alloc = nullptr;
5812   if (ReduceBulkZeroing &&
5813       // If we are implementing an array clone without knowing its source type
5814       // (can happen when compiling the array-guarded branch of a reflective
5815       // Object.clone() invocation), initialize the array within the allocation.
5816       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5817       // to a runtime clone call that assumes fully initialized source arrays.
5818       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5819     // We will be completely responsible for initializing this object -
5820     // mark Initialize node as complete.
5821     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5822     // The object was just allocated - there should be no any stores!
5823     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5824     // Mark as complete_with_arraycopy so that on AllocateNode
5825     // expansion, we know this AllocateNode is initialized by an array
5826     // copy and a StoreStore barrier exists after the array copy.
5827     alloc->initialization()->set_complete_with_arraycopy();
5828   }
5829 
5830   Node* size = _gvn.transform(obj_size);
5831   access_clone(obj, alloc_obj, size, is_array);
5832 
5833   // Do not let reads from the cloned object float above the arraycopy.
5834   if (alloc != nullptr) {
5835     // Do not let stores that initialize this object be reordered with
5836     // a subsequent store that would make this object accessible by
5837     // other threads.
5838     // Record what AllocateNode this StoreStore protects so that
5839     // escape analysis can go from the MemBarStoreStoreNode to the
5840     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5841     // based on the escape status of the AllocateNode.
5842     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5843   } else {
5844     insert_mem_bar(Op_MemBarCPUOrder);
5845   }
5846 }
5847 
5848 //------------------------inline_native_clone----------------------------
5849 // protected native Object java.lang.Object.clone();
5850 //
5851 // Here are the simple edge cases:
5852 //  null receiver => normal trap
5853 //  virtual and clone was overridden => slow path to out-of-line clone
5854 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5855 //
5856 // The general case has two steps, allocation and copying.
5857 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5858 //
5859 // Copying also has two cases, oop arrays and everything else.
5860 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5861 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5862 //
5863 // These steps fold up nicely if and when the cloned object's klass
5864 // can be sharply typed as an object array, a type array, or an instance.
5865 //
5866 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5867   PhiNode* result_val;
5868 
5869   // Set the reexecute bit for the interpreter to reexecute
5870   // the bytecode that invokes Object.clone if deoptimization happens.
5871   { PreserveReexecuteState preexecs(this);
5872     jvms()->set_should_reexecute(true);
5873 
5874     Node* obj = argument(0);
5875     obj = null_check_receiver();
5876     if (stopped())  return true;
5877 
5878     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5879     if (obj_type->is_inlinetypeptr()) {
5880       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5881       // no identity.
5882       set_result(obj);
5883       return true;
5884     }
5885 
5886     // If we are going to clone an instance, we need its exact type to
5887     // know the number and types of fields to convert the clone to
5888     // loads/stores. Maybe a speculative type can help us.
5889     if (!obj_type->klass_is_exact() &&
5890         obj_type->speculative_type() != nullptr &&
5891         obj_type->speculative_type()->is_instance_klass() &&
5892         !obj_type->speculative_type()->is_inlinetype()) {
5893       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5894       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5895           !spec_ik->has_injected_fields()) {
5896         if (!obj_type->isa_instptr() ||
5897             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5898           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5899         }
5900       }
5901     }
5902 
5903     // Conservatively insert a memory barrier on all memory slices.
5904     // Do not let writes into the original float below the clone.
5905     insert_mem_bar(Op_MemBarCPUOrder);
5906 
5907     // paths into result_reg:
5908     enum {
5909       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5910       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5911       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5912       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5913       PATH_LIMIT
5914     };
5915     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5916     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5917     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5918     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5919     record_for_igvn(result_reg);
5920 
5921     Node* obj_klass = load_object_klass(obj);
5922     // We only go to the fast case code if we pass a number of guards.
5923     // The paths which do not pass are accumulated in the slow_region.
5924     RegionNode* slow_region = new RegionNode(1);
5925     record_for_igvn(slow_region);
5926 
5927     Node* array_obj = obj;
5928     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5929     if (array_ctl != nullptr) {
5930       // It's an array.
5931       PreserveJVMState pjvms(this);
5932       set_control(array_ctl);
5933 
5934       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5935       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5936       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5937           obj_type->can_be_inline_array() &&
5938           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5939         // Flat inline type array may have object field that would require a
5940         // write barrier. Conservatively, go to slow path.
5941         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5942       }
5943 
5944       if (!stopped()) {
5945         Node* obj_length = load_array_length(array_obj);
5946         Node* array_size = nullptr; // Size of the array without object alignment padding.
5947         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5948 
5949         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5950         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5951           // If it is an oop array, it requires very special treatment,
5952           // because gc barriers are required when accessing the array.
5953           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5954           if (is_obja != nullptr) {
5955             PreserveJVMState pjvms2(this);
5956             set_control(is_obja);
5957             // Generate a direct call to the right arraycopy function(s).
5958             // Clones are always tightly coupled.
5959             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5960             ac->set_clone_oop_array();
5961             Node* n = _gvn.transform(ac);
5962             assert(n == ac, "cannot disappear");
5963             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5964 
5965             result_reg->init_req(_objArray_path, control());
5966             result_val->init_req(_objArray_path, alloc_obj);
5967             result_i_o ->set_req(_objArray_path, i_o());
5968             result_mem ->set_req(_objArray_path, reset_memory());
5969           }
5970         }
5971         // Otherwise, there are no barriers to worry about.
5972         // (We can dispense with card marks if we know the allocation
5973         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5974         //  causes the non-eden paths to take compensating steps to
5975         //  simulate a fresh allocation, so that no further
5976         //  card marks are required in compiled code to initialize
5977         //  the object.)
5978 
5979         if (!stopped()) {
5980           copy_to_clone(obj, alloc_obj, array_size, true);
5981 
5982           // Present the results of the copy.
5983           result_reg->init_req(_array_path, control());
5984           result_val->init_req(_array_path, alloc_obj);
5985           result_i_o ->set_req(_array_path, i_o());
5986           result_mem ->set_req(_array_path, reset_memory());
5987         }
5988       }
5989     }
5990 
5991     if (!stopped()) {
5992       // It's an instance (we did array above).  Make the slow-path tests.
5993       // If this is a virtual call, we generate a funny guard.  We grab
5994       // the vtable entry corresponding to clone() from the target object.
5995       // If the target method which we are calling happens to be the
5996       // Object clone() method, we pass the guard.  We do not need this
5997       // guard for non-virtual calls; the caller is known to be the native
5998       // Object clone().
5999       if (is_virtual) {
6000         generate_virtual_guard(obj_klass, slow_region);
6001       }
6002 
6003       // The object must be easily cloneable and must not have a finalizer.
6004       // Both of these conditions may be checked in a single test.
6005       // We could optimize the test further, but we don't care.
6006       generate_misc_flags_guard(obj_klass,
6007                                 // Test both conditions:
6008                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6009                                 // Must be cloneable but not finalizer:
6010                                 KlassFlags::_misc_is_cloneable_fast,
6011                                 slow_region);
6012     }
6013 
6014     if (!stopped()) {
6015       // It's an instance, and it passed the slow-path tests.
6016       PreserveJVMState pjvms(this);
6017       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6018       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6019       // is reexecuted if deoptimization occurs and there could be problems when merging
6020       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6021       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6022 
6023       copy_to_clone(obj, alloc_obj, obj_size, false);
6024 
6025       // Present the results of the slow call.
6026       result_reg->init_req(_instance_path, control());
6027       result_val->init_req(_instance_path, alloc_obj);
6028       result_i_o ->set_req(_instance_path, i_o());
6029       result_mem ->set_req(_instance_path, reset_memory());
6030     }
6031 
6032     // Generate code for the slow case.  We make a call to clone().
6033     set_control(_gvn.transform(slow_region));
6034     if (!stopped()) {
6035       PreserveJVMState pjvms(this);
6036       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6037       // We need to deoptimize on exception (see comment above)
6038       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6039       // this->control() comes from set_results_for_java_call
6040       result_reg->init_req(_slow_path, control());
6041       result_val->init_req(_slow_path, slow_result);
6042       result_i_o ->set_req(_slow_path, i_o());
6043       result_mem ->set_req(_slow_path, reset_memory());
6044     }
6045 
6046     // Return the combined state.
6047     set_control(    _gvn.transform(result_reg));
6048     set_i_o(        _gvn.transform(result_i_o));
6049     set_all_memory( _gvn.transform(result_mem));
6050   } // original reexecute is set back here
6051 
6052   set_result(_gvn.transform(result_val));
6053   return true;
6054 }
6055 
6056 // If we have a tightly coupled allocation, the arraycopy may take care
6057 // of the array initialization. If one of the guards we insert between
6058 // the allocation and the arraycopy causes a deoptimization, an
6059 // uninitialized array will escape the compiled method. To prevent that
6060 // we set the JVM state for uncommon traps between the allocation and
6061 // the arraycopy to the state before the allocation so, in case of
6062 // deoptimization, we'll reexecute the allocation and the
6063 // initialization.
6064 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6065   if (alloc != nullptr) {
6066     ciMethod* trap_method = alloc->jvms()->method();
6067     int trap_bci = alloc->jvms()->bci();
6068 
6069     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6070         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6071       // Make sure there's no store between the allocation and the
6072       // arraycopy otherwise visible side effects could be rexecuted
6073       // in case of deoptimization and cause incorrect execution.
6074       bool no_interfering_store = true;
6075       Node* mem = alloc->in(TypeFunc::Memory);
6076       if (mem->is_MergeMem()) {
6077         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6078           Node* n = mms.memory();
6079           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6080             assert(n->is_Store(), "what else?");
6081             no_interfering_store = false;
6082             break;
6083           }
6084         }
6085       } else {
6086         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6087           Node* n = mms.memory();
6088           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6089             assert(n->is_Store(), "what else?");
6090             no_interfering_store = false;
6091             break;
6092           }
6093         }
6094       }
6095 
6096       if (no_interfering_store) {
6097         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6098 
6099         JVMState* saved_jvms = jvms();
6100         saved_reexecute_sp = _reexecute_sp;
6101 
6102         set_jvms(sfpt->jvms());
6103         _reexecute_sp = jvms()->sp();
6104 
6105         return saved_jvms;
6106       }
6107     }
6108   }
6109   return nullptr;
6110 }
6111 
6112 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6113 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6114 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6115   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6116   uint size = alloc->req();
6117   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6118   old_jvms->set_map(sfpt);
6119   for (uint i = 0; i < size; i++) {
6120     sfpt->init_req(i, alloc->in(i));
6121   }
6122   int adjustment = 1;
6123   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6124   if (ary_klass_ptr->is_null_free()) {
6125     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6126     // also requires the componentType and initVal on stack for re-execution.
6127     // Re-create and push the componentType.
6128     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6129     ciInstance* instance = klass->component_mirror_instance();
6130     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6131     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6132     adjustment++;
6133   }
6134   // re-push array length for deoptimization
6135   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6136   if (ary_klass_ptr->is_null_free()) {
6137     // Re-create and push the initVal.
6138     Node* init_val = alloc->in(AllocateNode::InitValue);
6139     if (init_val == nullptr) {
6140       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6141     } else if (UseCompressedOops) {
6142       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6143     }
6144     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6145     adjustment++;
6146   }
6147   old_jvms->set_sp(old_jvms->sp() + adjustment);
6148   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6149   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6150   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6151   old_jvms->set_should_reexecute(true);
6152 
6153   sfpt->set_i_o(map()->i_o());
6154   sfpt->set_memory(map()->memory());
6155   sfpt->set_control(map()->control());
6156   return sfpt;
6157 }
6158 
6159 // In case of a deoptimization, we restart execution at the
6160 // allocation, allocating a new array. We would leave an uninitialized
6161 // array in the heap that GCs wouldn't expect. Move the allocation
6162 // after the traps so we don't allocate the array if we
6163 // deoptimize. This is possible because tightly_coupled_allocation()
6164 // guarantees there's no observer of the allocated array at this point
6165 // and the control flow is simple enough.
6166 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6167                                                     int saved_reexecute_sp, uint new_idx) {
6168   if (saved_jvms_before_guards != nullptr && !stopped()) {
6169     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6170 
6171     assert(alloc != nullptr, "only with a tightly coupled allocation");
6172     // restore JVM state to the state at the arraycopy
6173     saved_jvms_before_guards->map()->set_control(map()->control());
6174     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6175     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6176     // If we've improved the types of some nodes (null check) while
6177     // emitting the guards, propagate them to the current state
6178     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6179     set_jvms(saved_jvms_before_guards);
6180     _reexecute_sp = saved_reexecute_sp;
6181 
6182     // Remove the allocation from above the guards
6183     CallProjections* callprojs = alloc->extract_projections(true);
6184     InitializeNode* init = alloc->initialization();
6185     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6186     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6187     init->replace_mem_projs_by(alloc_mem, C);
6188 
6189     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6190     // the allocation (i.e. is only valid if the allocation succeeds):
6191     // 1) replace CastIINode with AllocateArrayNode's length here
6192     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6193     //
6194     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6195     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6196     Node* init_control = init->proj_out(TypeFunc::Control);
6197     Node* alloc_length = alloc->Ideal_length();
6198 #ifdef ASSERT
6199     Node* prev_cast = nullptr;
6200 #endif
6201     for (uint i = 0; i < init_control->outcnt(); i++) {
6202       Node* init_out = init_control->raw_out(i);
6203       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6204 #ifdef ASSERT
6205         if (prev_cast == nullptr) {
6206           prev_cast = init_out;
6207         } else {
6208           if (prev_cast->cmp(*init_out) == false) {
6209             prev_cast->dump();
6210             init_out->dump();
6211             assert(false, "not equal CastIINode");
6212           }
6213         }
6214 #endif
6215         C->gvn_replace_by(init_out, alloc_length);
6216       }
6217     }
6218     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6219 
6220     // move the allocation here (after the guards)
6221     _gvn.hash_delete(alloc);
6222     alloc->set_req(TypeFunc::Control, control());
6223     alloc->set_req(TypeFunc::I_O, i_o());
6224     Node *mem = reset_memory();
6225     set_all_memory(mem);
6226     alloc->set_req(TypeFunc::Memory, mem);
6227     set_control(init->proj_out_or_null(TypeFunc::Control));
6228     set_i_o(callprojs->fallthrough_ioproj);
6229 
6230     // Update memory as done in GraphKit::set_output_for_allocation()
6231     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6232     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6233     if (ary_type->isa_aryptr() && length_type != nullptr) {
6234       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6235     }
6236     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6237     int            elemidx  = C->get_alias_index(telemref);
6238     // Need to properly move every memory projection for the Initialize
6239 #ifdef ASSERT
6240     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6241     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6242 #endif
6243     auto move_proj = [&](ProjNode* proj) {
6244       int alias_idx = C->get_alias_index(proj->adr_type());
6245       assert(alias_idx == Compile::AliasIdxRaw ||
6246              alias_idx == elemidx ||
6247              alias_idx == mark_idx ||
6248              alias_idx == klass_idx, "should be raw memory or array element type");
6249       set_memory(proj, alias_idx);
6250     };
6251     init->for_each_proj(move_proj, TypeFunc::Memory);
6252 
6253     Node* allocx = _gvn.transform(alloc);
6254     assert(allocx == alloc, "where has the allocation gone?");
6255     assert(dest->is_CheckCastPP(), "not an allocation result?");
6256 
6257     _gvn.hash_delete(dest);
6258     dest->set_req(0, control());
6259     Node* destx = _gvn.transform(dest);
6260     assert(destx == dest, "where has the allocation result gone?");
6261 
6262     array_ideal_length(alloc, ary_type, true);
6263   }
6264 }
6265 
6266 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6267 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6268 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6269 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6270 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6271 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6272 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6273                                                                        JVMState* saved_jvms_before_guards) {
6274   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6275     // There is at least one unrelated uncommon trap which needs to be replaced.
6276     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6277 
6278     JVMState* saved_jvms = jvms();
6279     const int saved_reexecute_sp = _reexecute_sp;
6280     set_jvms(sfpt->jvms());
6281     _reexecute_sp = jvms()->sp();
6282 
6283     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6284 
6285     // Restore state
6286     set_jvms(saved_jvms);
6287     _reexecute_sp = saved_reexecute_sp;
6288   }
6289 }
6290 
6291 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6292 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6293 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6294   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6295   while (if_proj->is_IfProj()) {
6296     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6297     if (uncommon_trap != nullptr) {
6298       create_new_uncommon_trap(uncommon_trap);
6299     }
6300     assert(if_proj->in(0)->is_If(), "must be If");
6301     if_proj = if_proj->in(0)->in(0);
6302   }
6303   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6304          "must have reached control projection of init node");
6305 }
6306 
6307 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6308   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6309   assert(trap_request != 0, "no valid UCT trap request");
6310   PreserveJVMState pjvms(this);
6311   set_control(uncommon_trap_call->in(0));
6312   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6313                 Deoptimization::trap_request_action(trap_request));
6314   assert(stopped(), "Should be stopped");
6315   _gvn.hash_delete(uncommon_trap_call);
6316   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6317 }
6318 
6319 // Common checks for array sorting intrinsics arguments.
6320 // Returns `true` if checks passed.
6321 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6322   // check address of the class
6323   if (elementType == nullptr || elementType->is_top()) {
6324     return false;  // dead path
6325   }
6326   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6327   if (elem_klass == nullptr) {
6328     return false;  // dead path
6329   }
6330   // java_mirror_type() returns non-null for compile-time Class constants only
6331   ciType* elem_type = elem_klass->java_mirror_type();
6332   if (elem_type == nullptr) {
6333     return false;
6334   }
6335   bt = elem_type->basic_type();
6336   // Disable the intrinsic if the CPU does not support SIMD sort
6337   if (!Matcher::supports_simd_sort(bt)) {
6338     return false;
6339   }
6340   // check address of the array
6341   if (obj == nullptr || obj->is_top()) {
6342     return false;  // dead path
6343   }
6344   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6345   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6346     return false; // failed input validation
6347   }
6348   return true;
6349 }
6350 
6351 //------------------------------inline_array_partition-----------------------
6352 bool LibraryCallKit::inline_array_partition() {
6353   address stubAddr = StubRoutines::select_array_partition_function();
6354   if (stubAddr == nullptr) {
6355     return false; // Intrinsic's stub is not implemented on this platform
6356   }
6357   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6358 
6359   // no receiver because it is a static method
6360   Node* elementType     = argument(0);
6361   Node* obj             = argument(1);
6362   Node* offset          = argument(2); // long
6363   Node* fromIndex       = argument(4);
6364   Node* toIndex         = argument(5);
6365   Node* indexPivot1     = argument(6);
6366   Node* indexPivot2     = argument(7);
6367   // PartitionOperation:  argument(8) is ignored
6368 
6369   Node* pivotIndices = nullptr;
6370   BasicType bt = T_ILLEGAL;
6371 
6372   if (!check_array_sort_arguments(elementType, obj, bt)) {
6373     return false;
6374   }
6375   null_check(obj);
6376   // If obj is dead, only null-path is taken.
6377   if (stopped()) {
6378     return true;
6379   }
6380   // Set the original stack and the reexecute bit for the interpreter to reexecute
6381   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6382   { PreserveReexecuteState preexecs(this);
6383     jvms()->set_should_reexecute(true);
6384 
6385     Node* obj_adr = make_unsafe_address(obj, offset);
6386 
6387     // create the pivotIndices array of type int and size = 2
6388     Node* size = intcon(2);
6389     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6390     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6391     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6392     guarantee(alloc != nullptr, "created above");
6393     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6394 
6395     // pass the basic type enum to the stub
6396     Node* elemType = intcon(bt);
6397 
6398     // Call the stub
6399     const char *stubName = "array_partition_stub";
6400     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6401                       stubAddr, stubName, TypePtr::BOTTOM,
6402                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6403                       indexPivot1, indexPivot2);
6404 
6405   } // original reexecute is set back here
6406 
6407   if (!stopped()) {
6408     set_result(pivotIndices);
6409   }
6410 
6411   return true;
6412 }
6413 
6414 
6415 //------------------------------inline_array_sort-----------------------
6416 bool LibraryCallKit::inline_array_sort() {
6417   address stubAddr = StubRoutines::select_arraysort_function();
6418   if (stubAddr == nullptr) {
6419     return false; // Intrinsic's stub is not implemented on this platform
6420   }
6421   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6422 
6423   // no receiver because it is a static method
6424   Node* elementType     = argument(0);
6425   Node* obj             = argument(1);
6426   Node* offset          = argument(2); // long
6427   Node* fromIndex       = argument(4);
6428   Node* toIndex         = argument(5);
6429   // SortOperation:       argument(6) is ignored
6430 
6431   BasicType bt = T_ILLEGAL;
6432 
6433   if (!check_array_sort_arguments(elementType, obj, bt)) {
6434     return false;
6435   }
6436   null_check(obj);
6437   // If obj is dead, only null-path is taken.
6438   if (stopped()) {
6439     return true;
6440   }
6441   Node* obj_adr = make_unsafe_address(obj, offset);
6442 
6443   // pass the basic type enum to the stub
6444   Node* elemType = intcon(bt);
6445 
6446   // Call the stub.
6447   const char *stubName = "arraysort_stub";
6448   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6449                     stubAddr, stubName, TypePtr::BOTTOM,
6450                     obj_adr, elemType, fromIndex, toIndex);
6451 
6452   return true;
6453 }
6454 
6455 
6456 //------------------------------inline_arraycopy-----------------------
6457 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6458 //                                                      Object dest, int destPos,
6459 //                                                      int length);
6460 bool LibraryCallKit::inline_arraycopy() {
6461   // Get the arguments.
6462   Node* src         = argument(0);  // type: oop
6463   Node* src_offset  = argument(1);  // type: int
6464   Node* dest        = argument(2);  // type: oop
6465   Node* dest_offset = argument(3);  // type: int
6466   Node* length      = argument(4);  // type: int
6467 
6468   uint new_idx = C->unique();
6469 
6470   // Check for allocation before we add nodes that would confuse
6471   // tightly_coupled_allocation()
6472   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6473 
6474   int saved_reexecute_sp = -1;
6475   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6476   // See arraycopy_restore_alloc_state() comment
6477   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6478   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6479   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6480   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6481 
6482   // The following tests must be performed
6483   // (1) src and dest are arrays.
6484   // (2) src and dest arrays must have elements of the same BasicType
6485   // (3) src and dest must not be null.
6486   // (4) src_offset must not be negative.
6487   // (5) dest_offset must not be negative.
6488   // (6) length must not be negative.
6489   // (7) src_offset + length must not exceed length of src.
6490   // (8) dest_offset + length must not exceed length of dest.
6491   // (9) each element of an oop array must be assignable
6492 
6493   // (3) src and dest must not be null.
6494   // always do this here because we need the JVM state for uncommon traps
6495   Node* null_ctl = top();
6496   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6497   assert(null_ctl->is_top(), "no null control here");
6498   dest = null_check(dest, T_ARRAY);
6499 
6500   if (!can_emit_guards) {
6501     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6502     // guards but the arraycopy node could still take advantage of a
6503     // tightly allocated allocation. tightly_coupled_allocation() is
6504     // called again to make sure it takes the null check above into
6505     // account: the null check is mandatory and if it caused an
6506     // uncommon trap to be emitted then the allocation can't be
6507     // considered tightly coupled in this context.
6508     alloc = tightly_coupled_allocation(dest);
6509   }
6510 
6511   bool validated = false;
6512 
6513   const Type* src_type  = _gvn.type(src);
6514   const Type* dest_type = _gvn.type(dest);
6515   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6516   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6517 
6518   // Do we have the type of src?
6519   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6520   // Do we have the type of dest?
6521   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6522   // Is the type for src from speculation?
6523   bool src_spec = false;
6524   // Is the type for dest from speculation?
6525   bool dest_spec = false;
6526 
6527   if ((!has_src || !has_dest) && can_emit_guards) {
6528     // We don't have sufficient type information, let's see if
6529     // speculative types can help. We need to have types for both src
6530     // and dest so that it pays off.
6531 
6532     // Do we already have or could we have type information for src
6533     bool could_have_src = has_src;
6534     // Do we already have or could we have type information for dest
6535     bool could_have_dest = has_dest;
6536 
6537     ciKlass* src_k = nullptr;
6538     if (!has_src) {
6539       src_k = src_type->speculative_type_not_null();
6540       if (src_k != nullptr && src_k->is_array_klass()) {
6541         could_have_src = true;
6542       }
6543     }
6544 
6545     ciKlass* dest_k = nullptr;
6546     if (!has_dest) {
6547       dest_k = dest_type->speculative_type_not_null();
6548       if (dest_k != nullptr && dest_k->is_array_klass()) {
6549         could_have_dest = true;
6550       }
6551     }
6552 
6553     if (could_have_src && could_have_dest) {
6554       // This is going to pay off so emit the required guards
6555       if (!has_src) {
6556         src = maybe_cast_profiled_obj(src, src_k, true);
6557         src_type  = _gvn.type(src);
6558         top_src  = src_type->isa_aryptr();
6559         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6560         src_spec = true;
6561       }
6562       if (!has_dest) {
6563         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6564         dest_type  = _gvn.type(dest);
6565         top_dest  = dest_type->isa_aryptr();
6566         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6567         dest_spec = true;
6568       }
6569     }
6570   }
6571 
6572   if (has_src && has_dest && can_emit_guards) {
6573     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6574     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6575     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6576     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6577 
6578     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6579       // If both arrays are object arrays then having the exact types
6580       // for both will remove the need for a subtype check at runtime
6581       // before the call and may make it possible to pick a faster copy
6582       // routine (without a subtype check on every element)
6583       // Do we have the exact type of src?
6584       bool could_have_src = src_spec;
6585       // Do we have the exact type of dest?
6586       bool could_have_dest = dest_spec;
6587       ciKlass* src_k = nullptr;
6588       ciKlass* dest_k = nullptr;
6589       if (!src_spec) {
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       if (!dest_spec) {
6596         dest_k = dest_type->speculative_type_not_null();
6597         if (dest_k != nullptr && dest_k->is_array_klass()) {
6598           could_have_dest = true;
6599         }
6600       }
6601       if (could_have_src && could_have_dest) {
6602         // If we can have both exact types, emit the missing guards
6603         if (could_have_src && !src_spec) {
6604           src = maybe_cast_profiled_obj(src, src_k, true);
6605           src_type = _gvn.type(src);
6606           top_src = src_type->isa_aryptr();
6607         }
6608         if (could_have_dest && !dest_spec) {
6609           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6610           dest_type = _gvn.type(dest);
6611           top_dest = dest_type->isa_aryptr();
6612         }
6613       }
6614     }
6615   }
6616 
6617   ciMethod* trap_method = method();
6618   int trap_bci = bci();
6619   if (saved_jvms_before_guards != nullptr) {
6620     trap_method = alloc->jvms()->method();
6621     trap_bci = alloc->jvms()->bci();
6622   }
6623 
6624   bool negative_length_guard_generated = false;
6625 
6626   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6627       can_emit_guards && !src->is_top() && !dest->is_top()) {
6628     // validate arguments: enables transformation the ArrayCopyNode
6629     validated = true;
6630 
6631     RegionNode* slow_region = new RegionNode(1);
6632     record_for_igvn(slow_region);
6633 
6634     // (1) src and dest are arrays.
6635     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6636     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6637 
6638     // (2) src and dest arrays must have elements of the same BasicType
6639     // done at macro expansion or at Ideal transformation time
6640 
6641     // (4) src_offset must not be negative.
6642     generate_negative_guard(src_offset, slow_region);
6643 
6644     // (5) dest_offset must not be negative.
6645     generate_negative_guard(dest_offset, slow_region);
6646 
6647     // (7) src_offset + length must not exceed length of src.
6648     generate_limit_guard(src_offset, length,
6649                          load_array_length(src),
6650                          slow_region);
6651 
6652     // (8) dest_offset + length must not exceed length of dest.
6653     generate_limit_guard(dest_offset, length,
6654                          load_array_length(dest),
6655                          slow_region);
6656 
6657     // (6) length must not be negative.
6658     // This is also checked in generate_arraycopy() during macro expansion, but
6659     // we also have to check it here for the case where the ArrayCopyNode will
6660     // be eliminated by Escape Analysis.
6661     if (EliminateAllocations) {
6662       generate_negative_guard(length, slow_region);
6663       negative_length_guard_generated = true;
6664     }
6665 
6666     // (9) each element of an oop array must be assignable
6667     Node* dest_klass = load_object_klass(dest);
6668     Node* refined_dest_klass = dest_klass;
6669     if (src != dest) {
6670       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6671       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6672       slow_region->add_req(not_subtype_ctrl);
6673     }
6674 
6675     // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6676     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6677     Node* src_klass = load_object_klass(src);
6678     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6679     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6680                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6681                                                    MemNode::unordered));
6682     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6683     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6684                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6685                                                     MemNode::unordered));
6686 
6687     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6688     jint props_value = (jint)props_null_restricted.value();
6689 
6690     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6691     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6692     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6693 
6694     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6695     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6696     generate_fair_guard(tst, slow_region);
6697 
6698     // TODO 8251971 This is too strong
6699     generate_fair_guard(flat_array_test(src), slow_region);
6700     generate_fair_guard(flat_array_test(dest), slow_region);
6701 
6702     {
6703       PreserveJVMState pjvms(this);
6704       set_control(_gvn.transform(slow_region));
6705       uncommon_trap(Deoptimization::Reason_intrinsic,
6706                     Deoptimization::Action_make_not_entrant);
6707       assert(stopped(), "Should be stopped");
6708     }
6709 
6710     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6711     if (dest_klass_t == nullptr) {
6712       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6713       // are in a dead path.
6714       uncommon_trap(Deoptimization::Reason_intrinsic,
6715                     Deoptimization::Action_make_not_entrant);
6716       return true;
6717     }
6718 
6719     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6720     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6721     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6722   }
6723 
6724   if (stopped()) {
6725     return true;
6726   }
6727 
6728   Node* dest_klass = load_object_klass(dest);
6729   dest_klass = load_non_refined_array_klass(dest_klass);
6730 
6731   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6732                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6733                                           // so the compiler has a chance to eliminate them: during macro expansion,
6734                                           // we have to set their control (CastPP nodes are eliminated).
6735                                           load_object_klass(src), dest_klass,
6736                                           load_array_length(src), load_array_length(dest));
6737 
6738   ac->set_arraycopy(validated);
6739 
6740   Node* n = _gvn.transform(ac);
6741   if (n == ac) {
6742     ac->connect_outputs(this);
6743   } else {
6744     assert(validated, "shouldn't transform if all arguments not validated");
6745     set_all_memory(n);
6746   }
6747   clear_upper_avx();
6748 
6749 
6750   return true;
6751 }
6752 
6753 
6754 // Helper function which determines if an arraycopy immediately follows
6755 // an allocation, with no intervening tests or other escapes for the object.
6756 AllocateArrayNode*
6757 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6758   if (stopped())             return nullptr;  // no fast path
6759   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6760 
6761   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6762   if (alloc == nullptr)  return nullptr;
6763 
6764   Node* rawmem = memory(Compile::AliasIdxRaw);
6765   // Is the allocation's memory state untouched?
6766   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6767     // Bail out if there have been raw-memory effects since the allocation.
6768     // (Example:  There might have been a call or safepoint.)
6769     return nullptr;
6770   }
6771   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6772   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6773     return nullptr;
6774   }
6775 
6776   // There must be no unexpected observers of this allocation.
6777   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6778     Node* obs = ptr->fast_out(i);
6779     if (obs != this->map()) {
6780       return nullptr;
6781     }
6782   }
6783 
6784   // This arraycopy must unconditionally follow the allocation of the ptr.
6785   Node* alloc_ctl = ptr->in(0);
6786   Node* ctl = control();
6787   while (ctl != alloc_ctl) {
6788     // There may be guards which feed into the slow_region.
6789     // Any other control flow means that we might not get a chance
6790     // to finish initializing the allocated object.
6791     // Various low-level checks bottom out in uncommon traps. These
6792     // are considered safe since we've already checked above that
6793     // there is no unexpected observer of this allocation.
6794     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6795       assert(ctl->in(0)->is_If(), "must be If");
6796       ctl = ctl->in(0)->in(0);
6797     } else {
6798       return nullptr;
6799     }
6800   }
6801 
6802   // If we get this far, we have an allocation which immediately
6803   // precedes the arraycopy, and we can take over zeroing the new object.
6804   // The arraycopy will finish the initialization, and provide
6805   // a new control state to which we will anchor the destination pointer.
6806 
6807   return alloc;
6808 }
6809 
6810 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6811   if (node->is_IfProj()) {
6812     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6813     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6814       Node* obs = other_proj->fast_out(j);
6815       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6816           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6817         return obs->as_CallStaticJava();
6818       }
6819     }
6820   }
6821   return nullptr;
6822 }
6823 
6824 //-------------inline_encodeISOArray-----------------------------------
6825 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6826 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6827 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6828 // encode char[] to byte[] in ISO_8859_1 or ASCII
6829 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6830   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6831   // no receiver since it is static method
6832   Node *src         = argument(0);
6833   Node *src_offset  = argument(1);
6834   Node *dst         = argument(2);
6835   Node *dst_offset  = argument(3);
6836   Node *length      = argument(4);
6837 
6838   // Cast source & target arrays to not-null
6839   src = must_be_not_null(src, true);
6840   dst = must_be_not_null(dst, true);
6841   if (stopped()) {
6842     return true;
6843   }
6844 
6845   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6846   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6847   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6848       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6849     // failed array check
6850     return false;
6851   }
6852 
6853   // Figure out the size and type of the elements we will be copying.
6854   BasicType src_elem = src_type->elem()->array_element_basic_type();
6855   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6856   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6857     return false;
6858   }
6859 
6860   // Check source & target bounds
6861   RegionNode* bailout = create_bailout();
6862   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6863   generate_string_range_check(dst, dst_offset, length, false, bailout);
6864   if (check_bailout(bailout)) {
6865     return true;
6866   }
6867 
6868   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6869   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6870   // 'src_start' points to src array + scaled offset
6871   // 'dst_start' points to dst array + scaled offset
6872 
6873   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6874   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6875   enc = _gvn.transform(enc);
6876   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6877   set_memory(res_mem, mtype);
6878   set_result(enc);
6879   clear_upper_avx();
6880 
6881   return true;
6882 }
6883 
6884 //-------------inline_multiplyToLen-----------------------------------
6885 bool LibraryCallKit::inline_multiplyToLen() {
6886   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6887 
6888   address stubAddr = StubRoutines::multiplyToLen();
6889   if (stubAddr == nullptr) {
6890     return false; // Intrinsic's stub is not implemented on this platform
6891   }
6892   const char* stubName = "multiplyToLen";
6893 
6894   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6895 
6896   // no receiver because it is a static method
6897   Node* x    = argument(0);
6898   Node* xlen = argument(1);
6899   Node* y    = argument(2);
6900   Node* ylen = argument(3);
6901   Node* z    = argument(4);
6902 
6903   x = must_be_not_null(x, true);
6904   y = must_be_not_null(y, true);
6905 
6906   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6907   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6908   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6909       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6910     // failed array check
6911     return false;
6912   }
6913 
6914   BasicType x_elem = x_type->elem()->array_element_basic_type();
6915   BasicType y_elem = y_type->elem()->array_element_basic_type();
6916   if (x_elem != T_INT || y_elem != T_INT) {
6917     return false;
6918   }
6919 
6920   Node* x_start = array_element_address(x, intcon(0), x_elem);
6921   Node* y_start = array_element_address(y, intcon(0), y_elem);
6922   // 'x_start' points to x array + scaled xlen
6923   // 'y_start' points to y array + scaled ylen
6924 
6925   Node* z_start = array_element_address(z, intcon(0), T_INT);
6926 
6927   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6928                                  OptoRuntime::multiplyToLen_Type(),
6929                                  stubAddr, stubName, TypePtr::BOTTOM,
6930                                  x_start, xlen, y_start, ylen, z_start);
6931 
6932   C->set_has_split_ifs(true); // Has chance for split-if optimization
6933   set_result(z);
6934   return true;
6935 }
6936 
6937 //-------------inline_squareToLen------------------------------------
6938 bool LibraryCallKit::inline_squareToLen() {
6939   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6940 
6941   address stubAddr = StubRoutines::squareToLen();
6942   if (stubAddr == nullptr) {
6943     return false; // Intrinsic's stub is not implemented on this platform
6944   }
6945   const char* stubName = "squareToLen";
6946 
6947   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6948 
6949   Node* x    = argument(0);
6950   Node* len  = argument(1);
6951   Node* z    = argument(2);
6952   Node* zlen = argument(3);
6953 
6954   x = must_be_not_null(x, true);
6955   z = must_be_not_null(z, true);
6956 
6957   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6958   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6959   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6960       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6961     // failed array check
6962     return false;
6963   }
6964 
6965   BasicType x_elem = x_type->elem()->array_element_basic_type();
6966   BasicType z_elem = z_type->elem()->array_element_basic_type();
6967   if (x_elem != T_INT || z_elem != T_INT) {
6968     return false;
6969   }
6970 
6971 
6972   Node* x_start = array_element_address(x, intcon(0), x_elem);
6973   Node* z_start = array_element_address(z, intcon(0), z_elem);
6974 
6975   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6976                                   OptoRuntime::squareToLen_Type(),
6977                                   stubAddr, stubName, TypePtr::BOTTOM,
6978                                   x_start, len, z_start, zlen);
6979 
6980   set_result(z);
6981   return true;
6982 }
6983 
6984 //-------------inline_mulAdd------------------------------------------
6985 bool LibraryCallKit::inline_mulAdd() {
6986   assert(UseMulAddIntrinsic, "not implemented on this platform");
6987 
6988   address stubAddr = StubRoutines::mulAdd();
6989   if (stubAddr == nullptr) {
6990     return false; // Intrinsic's stub is not implemented on this platform
6991   }
6992   const char* stubName = "mulAdd";
6993 
6994   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6995 
6996   Node* out      = argument(0);
6997   Node* in       = argument(1);
6998   Node* offset   = argument(2);
6999   Node* len      = argument(3);
7000   Node* k        = argument(4);
7001 
7002   in = must_be_not_null(in, true);
7003   out = must_be_not_null(out, true);
7004 
7005   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7006   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7007   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7008        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7009     // failed array check
7010     return false;
7011   }
7012 
7013   BasicType out_elem = out_type->elem()->array_element_basic_type();
7014   BasicType in_elem = in_type->elem()->array_element_basic_type();
7015   if (out_elem != T_INT || in_elem != T_INT) {
7016     return false;
7017   }
7018 
7019   Node* outlen = load_array_length(out);
7020   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7021   Node* out_start = array_element_address(out, intcon(0), out_elem);
7022   Node* in_start = array_element_address(in, intcon(0), in_elem);
7023 
7024   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7025                                   OptoRuntime::mulAdd_Type(),
7026                                   stubAddr, stubName, TypePtr::BOTTOM,
7027                                   out_start,in_start, new_offset, len, k);
7028   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7029   set_result(result);
7030   return true;
7031 }
7032 
7033 //-------------inline_montgomeryMultiply-----------------------------------
7034 bool LibraryCallKit::inline_montgomeryMultiply() {
7035   address stubAddr = StubRoutines::montgomeryMultiply();
7036   if (stubAddr == nullptr) {
7037     return false; // Intrinsic's stub is not implemented on this platform
7038   }
7039 
7040   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7041   const char* stubName = "montgomery_multiply";
7042 
7043   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7044 
7045   Node* a    = argument(0);
7046   Node* b    = argument(1);
7047   Node* n    = argument(2);
7048   Node* len  = argument(3);
7049   Node* inv  = argument(4);
7050   Node* m    = argument(6);
7051 
7052   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7053   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7054   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7055   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7056   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7057       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7058       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7059       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7060     // failed array check
7061     return false;
7062   }
7063 
7064   BasicType a_elem = a_type->elem()->array_element_basic_type();
7065   BasicType b_elem = b_type->elem()->array_element_basic_type();
7066   BasicType n_elem = n_type->elem()->array_element_basic_type();
7067   BasicType m_elem = m_type->elem()->array_element_basic_type();
7068   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7069     return false;
7070   }
7071 
7072   // Make the call
7073   {
7074     Node* a_start = array_element_address(a, intcon(0), a_elem);
7075     Node* b_start = array_element_address(b, intcon(0), b_elem);
7076     Node* n_start = array_element_address(n, intcon(0), n_elem);
7077     Node* m_start = array_element_address(m, intcon(0), m_elem);
7078 
7079     Node* call = make_runtime_call(RC_LEAF,
7080                                    OptoRuntime::montgomeryMultiply_Type(),
7081                                    stubAddr, stubName, TypePtr::BOTTOM,
7082                                    a_start, b_start, n_start, len, inv, top(),
7083                                    m_start);
7084     set_result(m);
7085   }
7086 
7087   return true;
7088 }
7089 
7090 bool LibraryCallKit::inline_montgomerySquare() {
7091   address stubAddr = StubRoutines::montgomerySquare();
7092   if (stubAddr == nullptr) {
7093     return false; // Intrinsic's stub is not implemented on this platform
7094   }
7095 
7096   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7097   const char* stubName = "montgomery_square";
7098 
7099   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7100 
7101   Node* a    = argument(0);
7102   Node* n    = argument(1);
7103   Node* len  = argument(2);
7104   Node* inv  = argument(3);
7105   Node* m    = argument(5);
7106 
7107   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7108   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7109   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7110   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7111       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7112       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7113     // failed array check
7114     return false;
7115   }
7116 
7117   BasicType a_elem = a_type->elem()->array_element_basic_type();
7118   BasicType n_elem = n_type->elem()->array_element_basic_type();
7119   BasicType m_elem = m_type->elem()->array_element_basic_type();
7120   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7121     return false;
7122   }
7123 
7124   // Make the call
7125   {
7126     Node* a_start = array_element_address(a, intcon(0), a_elem);
7127     Node* n_start = array_element_address(n, intcon(0), n_elem);
7128     Node* m_start = array_element_address(m, intcon(0), m_elem);
7129 
7130     Node* call = make_runtime_call(RC_LEAF,
7131                                    OptoRuntime::montgomerySquare_Type(),
7132                                    stubAddr, stubName, TypePtr::BOTTOM,
7133                                    a_start, n_start, len, inv, top(),
7134                                    m_start);
7135     set_result(m);
7136   }
7137 
7138   return true;
7139 }
7140 
7141 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7142   address stubAddr = nullptr;
7143   const char* stubName = nullptr;
7144 
7145   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7146   if (stubAddr == nullptr) {
7147     return false; // Intrinsic's stub is not implemented on this platform
7148   }
7149 
7150   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7151 
7152   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7153 
7154   Node* newArr = argument(0);
7155   Node* oldArr = argument(1);
7156   Node* newIdx = argument(2);
7157   Node* shiftCount = argument(3);
7158   Node* numIter = argument(4);
7159 
7160   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7161   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7162   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7163       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7164     return false;
7165   }
7166 
7167   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7168   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7169   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7170     return false;
7171   }
7172 
7173   // Make the call
7174   {
7175     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7176     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7177 
7178     Node* call = make_runtime_call(RC_LEAF,
7179                                    OptoRuntime::bigIntegerShift_Type(),
7180                                    stubAddr,
7181                                    stubName,
7182                                    TypePtr::BOTTOM,
7183                                    newArr_start,
7184                                    oldArr_start,
7185                                    newIdx,
7186                                    shiftCount,
7187                                    numIter);
7188   }
7189 
7190   return true;
7191 }
7192 
7193 //-------------inline_vectorizedMismatch------------------------------
7194 bool LibraryCallKit::inline_vectorizedMismatch() {
7195   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7196 
7197   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7198   Node* obja    = argument(0); // Object
7199   Node* aoffset = argument(1); // long
7200   Node* objb    = argument(3); // Object
7201   Node* boffset = argument(4); // long
7202   Node* length  = argument(6); // int
7203   Node* scale   = argument(7); // int
7204 
7205   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7206   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7207   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7208       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7209       scale == top()) {
7210     return false; // failed input validation
7211   }
7212 
7213   Node* obja_adr = make_unsafe_address(obja, aoffset);
7214   Node* objb_adr = make_unsafe_address(objb, boffset);
7215 
7216   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7217   //
7218   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7219   //    if (length <= inline_limit) {
7220   //      inline_path:
7221   //        vmask   = VectorMaskGen length
7222   //        vload1  = LoadVectorMasked obja, vmask
7223   //        vload2  = LoadVectorMasked objb, vmask
7224   //        result1 = VectorCmpMasked vload1, vload2, vmask
7225   //    } else {
7226   //      call_stub_path:
7227   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7228   //    }
7229   //    exit_block:
7230   //      return Phi(result1, result2);
7231   //
7232   enum { inline_path = 1,  // input is small enough to process it all at once
7233          stub_path   = 2,  // input is too large; call into the VM
7234          PATH_LIMIT  = 3
7235   };
7236 
7237   Node* exit_block = new RegionNode(PATH_LIMIT);
7238   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7239   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7240 
7241   Node* call_stub_path = control();
7242 
7243   BasicType elem_bt = T_ILLEGAL;
7244 
7245   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7246   if (scale_t->is_con()) {
7247     switch (scale_t->get_con()) {
7248       case 0: elem_bt = T_BYTE;  break;
7249       case 1: elem_bt = T_SHORT; break;
7250       case 2: elem_bt = T_INT;   break;
7251       case 3: elem_bt = T_LONG;  break;
7252 
7253       default: elem_bt = T_ILLEGAL; break; // not supported
7254     }
7255   }
7256 
7257   int inline_limit = 0;
7258   bool do_partial_inline = false;
7259 
7260   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7261     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7262     do_partial_inline = inline_limit >= 16;
7263   }
7264 
7265   if (do_partial_inline) {
7266     assert(elem_bt != T_ILLEGAL, "sanity");
7267 
7268     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7269         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7270         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7271 
7272       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7273       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7274       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7275 
7276       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7277 
7278       if (!stopped()) {
7279         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7280 
7281         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7282         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7283         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7284         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7285 
7286         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7287         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7288         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7289         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7290 
7291         exit_block->init_req(inline_path, control());
7292         memory_phi->init_req(inline_path, map()->memory());
7293         result_phi->init_req(inline_path, result);
7294 
7295         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7296         clear_upper_avx();
7297       }
7298     }
7299   }
7300 
7301   if (call_stub_path != nullptr) {
7302     set_control(call_stub_path);
7303 
7304     Node* call = make_runtime_call(RC_LEAF,
7305                                    OptoRuntime::vectorizedMismatch_Type(),
7306                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7307                                    obja_adr, objb_adr, length, scale);
7308 
7309     exit_block->init_req(stub_path, control());
7310     memory_phi->init_req(stub_path, map()->memory());
7311     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7312   }
7313 
7314   exit_block = _gvn.transform(exit_block);
7315   memory_phi = _gvn.transform(memory_phi);
7316   result_phi = _gvn.transform(result_phi);
7317 
7318   record_for_igvn(exit_block);
7319   record_for_igvn(memory_phi);
7320   record_for_igvn(result_phi);
7321 
7322   set_control(exit_block);
7323   set_all_memory(memory_phi);
7324   set_result(result_phi);
7325 
7326   return true;
7327 }
7328 
7329 //------------------------------inline_vectorizedHashcode----------------------------
7330 bool LibraryCallKit::inline_vectorizedHashCode() {
7331   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7332 
7333   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7334   Node* array          = argument(0);
7335   Node* offset         = argument(1);
7336   Node* length         = argument(2);
7337   Node* initialValue   = argument(3);
7338   Node* basic_type     = argument(4);
7339 
7340   if (basic_type == top()) {
7341     return false; // failed input validation
7342   }
7343 
7344   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7345   if (!basic_type_t->is_con()) {
7346     return false; // Only intrinsify if mode argument is constant
7347   }
7348 
7349   array = must_be_not_null(array, true);
7350 
7351   BasicType bt = (BasicType)basic_type_t->get_con();
7352 
7353   // Resolve address of first element
7354   Node* array_start = array_element_address(array, offset, bt);
7355 
7356   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7357     array_start, length, initialValue, basic_type)));
7358   clear_upper_avx();
7359 
7360   return true;
7361 }
7362 
7363 /**
7364  * Calculate CRC32 for byte.
7365  * int java.util.zip.CRC32.update(int crc, int b)
7366  */
7367 bool LibraryCallKit::inline_updateCRC32() {
7368   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7369   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7370   // no receiver since it is static method
7371   Node* crc  = argument(0); // type: int
7372   Node* b    = argument(1); // type: int
7373 
7374   /*
7375    *    int c = ~ crc;
7376    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7377    *    b = b ^ (c >>> 8);
7378    *    crc = ~b;
7379    */
7380 
7381   Node* M1 = intcon(-1);
7382   crc = _gvn.transform(new XorINode(crc, M1));
7383   Node* result = _gvn.transform(new XorINode(crc, b));
7384   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7385 
7386   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7387   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7388   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7389   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7390 
7391   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7392   result = _gvn.transform(new XorINode(crc, result));
7393   result = _gvn.transform(new XorINode(result, M1));
7394   set_result(result);
7395   return true;
7396 }
7397 
7398 /**
7399  * Calculate CRC32 for byte[] array.
7400  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7401  */
7402 bool LibraryCallKit::inline_updateBytesCRC32() {
7403   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7404   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7405   // no receiver since it is static method
7406   Node* crc     = argument(0); // type: int
7407   Node* src     = argument(1); // type: oop
7408   Node* offset  = argument(2); // type: int
7409   Node* length  = argument(3); // type: int
7410 
7411   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7412   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7413     // failed array check
7414     return false;
7415   }
7416 
7417   // Figure out the size and type of the elements we will be copying.
7418   BasicType src_elem = src_type->elem()->array_element_basic_type();
7419   if (src_elem != T_BYTE) {
7420     return false;
7421   }
7422 
7423   // 'src_start' points to src array + scaled offset
7424   src = must_be_not_null(src, true);
7425   Node* src_start = array_element_address(src, offset, src_elem);
7426 
7427   // We assume that range check is done by caller.
7428   // TODO: generate range check (offset+length < src.length) in debug VM.
7429 
7430   // Call the stub.
7431   address stubAddr = StubRoutines::updateBytesCRC32();
7432   const char *stubName = "updateBytesCRC32";
7433 
7434   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7435                                  stubAddr, stubName, TypePtr::BOTTOM,
7436                                  crc, src_start, length);
7437   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7438   set_result(result);
7439   return true;
7440 }
7441 
7442 /**
7443  * Calculate CRC32 for ByteBuffer.
7444  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7445  */
7446 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7447   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7448   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7449   // no receiver since it is static method
7450   Node* crc     = argument(0); // type: int
7451   Node* src     = argument(1); // type: long
7452   Node* offset  = argument(3); // type: int
7453   Node* length  = argument(4); // type: int
7454 
7455   src = ConvL2X(src);  // adjust Java long to machine word
7456   Node* base = _gvn.transform(new CastX2PNode(src));
7457   offset = ConvI2X(offset);
7458 
7459   // 'src_start' points to src array + scaled offset
7460   Node* src_start = off_heap_plus_addr(base, offset);
7461 
7462   // Call the stub.
7463   address stubAddr = StubRoutines::updateBytesCRC32();
7464   const char *stubName = "updateBytesCRC32";
7465 
7466   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7467                                  stubAddr, stubName, TypePtr::BOTTOM,
7468                                  crc, src_start, length);
7469   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7470   set_result(result);
7471   return true;
7472 }
7473 
7474 //------------------------------get_table_from_crc32c_class-----------------------
7475 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7476   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7477   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7478 
7479   return table;
7480 }
7481 
7482 //------------------------------inline_updateBytesCRC32C-----------------------
7483 //
7484 // Calculate CRC32C for byte[] array.
7485 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7486 //
7487 bool LibraryCallKit::inline_updateBytesCRC32C() {
7488   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7489   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7490   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7491   // no receiver since it is a static method
7492   Node* crc     = argument(0); // type: int
7493   Node* src     = argument(1); // type: oop
7494   Node* offset  = argument(2); // type: int
7495   Node* end     = argument(3); // type: int
7496 
7497   Node* length = _gvn.transform(new SubINode(end, offset));
7498 
7499   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7500   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7501     // failed array check
7502     return false;
7503   }
7504 
7505   // Figure out the size and type of the elements we will be copying.
7506   BasicType src_elem = src_type->elem()->array_element_basic_type();
7507   if (src_elem != T_BYTE) {
7508     return false;
7509   }
7510 
7511   // 'src_start' points to src array + scaled offset
7512   src = must_be_not_null(src, true);
7513   Node* src_start = array_element_address(src, offset, src_elem);
7514 
7515   // static final int[] byteTable in class CRC32C
7516   Node* table = get_table_from_crc32c_class(callee()->holder());
7517   table = must_be_not_null(table, true);
7518   Node* table_start = array_element_address(table, intcon(0), T_INT);
7519 
7520   // We assume that range check is done by caller.
7521   // TODO: generate range check (offset+length < src.length) in debug VM.
7522 
7523   // Call the stub.
7524   address stubAddr = StubRoutines::updateBytesCRC32C();
7525   const char *stubName = "updateBytesCRC32C";
7526 
7527   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7528                                  stubAddr, stubName, TypePtr::BOTTOM,
7529                                  crc, src_start, length, table_start);
7530   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7531   set_result(result);
7532   return true;
7533 }
7534 
7535 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7536 //
7537 // Calculate CRC32C for DirectByteBuffer.
7538 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7539 //
7540 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7541   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7542   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7543   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7544   // no receiver since it is a static method
7545   Node* crc     = argument(0); // type: int
7546   Node* src     = argument(1); // type: long
7547   Node* offset  = argument(3); // type: int
7548   Node* end     = argument(4); // type: int
7549 
7550   Node* length = _gvn.transform(new SubINode(end, offset));
7551 
7552   src = ConvL2X(src);  // adjust Java long to machine word
7553   Node* base = _gvn.transform(new CastX2PNode(src));
7554   offset = ConvI2X(offset);
7555 
7556   // 'src_start' points to src array + scaled offset
7557   Node* src_start = off_heap_plus_addr(base, offset);
7558 
7559   // static final int[] byteTable in class CRC32C
7560   Node* table = get_table_from_crc32c_class(callee()->holder());
7561   table = must_be_not_null(table, true);
7562   Node* table_start = array_element_address(table, intcon(0), T_INT);
7563 
7564   // Call the stub.
7565   address stubAddr = StubRoutines::updateBytesCRC32C();
7566   const char *stubName = "updateBytesCRC32C";
7567 
7568   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7569                                  stubAddr, stubName, TypePtr::BOTTOM,
7570                                  crc, src_start, length, table_start);
7571   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7572   set_result(result);
7573   return true;
7574 }
7575 
7576 //------------------------------inline_updateBytesAdler32----------------------
7577 //
7578 // Calculate Adler32 checksum for byte[] array.
7579 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7580 //
7581 bool LibraryCallKit::inline_updateBytesAdler32() {
7582   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7583   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7584   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7585   // no receiver since it is static method
7586   Node* crc     = argument(0); // type: int
7587   Node* src     = argument(1); // type: oop
7588   Node* offset  = argument(2); // type: int
7589   Node* length  = argument(3); // type: int
7590 
7591   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7592   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7593     // failed array check
7594     return false;
7595   }
7596 
7597   // Figure out the size and type of the elements we will be copying.
7598   BasicType src_elem = src_type->elem()->array_element_basic_type();
7599   if (src_elem != T_BYTE) {
7600     return false;
7601   }
7602 
7603   // 'src_start' points to src array + scaled offset
7604   Node* src_start = array_element_address(src, offset, src_elem);
7605 
7606   // We assume that range check is done by caller.
7607   // TODO: generate range check (offset+length < src.length) in debug VM.
7608 
7609   // Call the stub.
7610   address stubAddr = StubRoutines::updateBytesAdler32();
7611   const char *stubName = "updateBytesAdler32";
7612 
7613   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7614                                  stubAddr, stubName, TypePtr::BOTTOM,
7615                                  crc, src_start, length);
7616   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7617   set_result(result);
7618   return true;
7619 }
7620 
7621 //------------------------------inline_updateByteBufferAdler32---------------
7622 //
7623 // Calculate Adler32 checksum for DirectByteBuffer.
7624 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7625 //
7626 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7627   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7628   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7629   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7630   // no receiver since it is static method
7631   Node* crc     = argument(0); // type: int
7632   Node* src     = argument(1); // type: long
7633   Node* offset  = argument(3); // type: int
7634   Node* length  = argument(4); // type: int
7635 
7636   src = ConvL2X(src);  // adjust Java long to machine word
7637   Node* base = _gvn.transform(new CastX2PNode(src));
7638   offset = ConvI2X(offset);
7639 
7640   // 'src_start' points to src array + scaled offset
7641   Node* src_start = off_heap_plus_addr(base, offset);
7642 
7643   // Call the stub.
7644   address stubAddr = StubRoutines::updateBytesAdler32();
7645   const char *stubName = "updateBytesAdler32";
7646 
7647   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7648                                  stubAddr, stubName, TypePtr::BOTTOM,
7649                                  crc, src_start, length);
7650 
7651   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7652   set_result(result);
7653   return true;
7654 }
7655 
7656 //----------------------------inline_reference_get0----------------------------
7657 // public T java.lang.ref.Reference.get();
7658 bool LibraryCallKit::inline_reference_get0() {
7659   const int referent_offset = java_lang_ref_Reference::referent_offset();
7660 
7661   // Get the argument:
7662   Node* reference_obj = null_check_receiver();
7663   if (stopped()) return true;
7664 
7665   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7666   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7667                                         decorators, /*is_static*/ false,
7668                                         env()->Reference_klass());
7669   if (result == nullptr) return false;
7670 
7671   // Add memory barrier to prevent commoning reads from this field
7672   // across safepoint since GC can change its value.
7673   insert_mem_bar(Op_MemBarCPUOrder);
7674 
7675   set_result(result);
7676   return true;
7677 }
7678 
7679 //----------------------------inline_reference_refersTo0----------------------------
7680 // bool java.lang.ref.Reference.refersTo0();
7681 // bool java.lang.ref.PhantomReference.refersTo0();
7682 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7683   // Get arguments:
7684   Node* reference_obj = null_check_receiver();
7685   Node* other_obj = argument(1);
7686   if (stopped()) return true;
7687 
7688   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7689   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7690   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7691                                           decorators, /*is_static*/ false,
7692                                           env()->Reference_klass());
7693   if (referent == nullptr) return false;
7694 
7695   // Add memory barrier to prevent commoning reads from this field
7696   // across safepoint since GC can change its value.
7697   insert_mem_bar(Op_MemBarCPUOrder);
7698 
7699   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7700   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7701   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7702 
7703   RegionNode* region = new RegionNode(3);
7704   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7705 
7706   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7707   region->init_req(1, if_true);
7708   phi->init_req(1, intcon(1));
7709 
7710   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7711   region->init_req(2, if_false);
7712   phi->init_req(2, intcon(0));
7713 
7714   set_control(_gvn.transform(region));
7715   record_for_igvn(region);
7716   set_result(_gvn.transform(phi));
7717   return true;
7718 }
7719 
7720 //----------------------------inline_reference_clear0----------------------------
7721 // void java.lang.ref.Reference.clear0();
7722 // void java.lang.ref.PhantomReference.clear0();
7723 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7724   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7725 
7726   // Get arguments
7727   Node* reference_obj = null_check_receiver();
7728   if (stopped()) return true;
7729 
7730   // Common access parameters
7731   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7732   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7733   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7734   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7735   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7736 
7737   Node* referent = access_load_at(reference_obj,
7738                                   referent_field_addr,
7739                                   referent_field_addr_type,
7740                                   val_type,
7741                                   T_OBJECT,
7742                                   decorators);
7743 
7744   IdealKit ideal(this);
7745 #define __ ideal.
7746   __ if_then(referent, BoolTest::ne, null());
7747     sync_kit(ideal);
7748     access_store_at(reference_obj,
7749                     referent_field_addr,
7750                     referent_field_addr_type,
7751                     null(),
7752                     val_type,
7753                     T_OBJECT,
7754                     decorators);
7755     __ sync_kit(this);
7756   __ end_if();
7757   final_sync(ideal);
7758 #undef __
7759 
7760   return true;
7761 }
7762 
7763 //-----------------------inline_reference_reachabilityFence-----------------
7764 // bool java.lang.ref.Reference.reachabilityFence();
7765 bool LibraryCallKit::inline_reference_reachabilityFence() {
7766   Node* referent = argument(0);
7767   insert_reachability_fence(referent);
7768   return true;
7769 }
7770 
7771 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7772                                              DecoratorSet decorators, bool is_static,
7773                                              ciInstanceKlass* fromKls) {
7774   if (fromKls == nullptr) {
7775     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7776     assert(tinst != nullptr, "obj is null");
7777     assert(tinst->is_loaded(), "obj is not loaded");
7778     fromKls = tinst->instance_klass();
7779   }
7780   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7781                                               ciSymbol::make(fieldTypeString),
7782                                               is_static);
7783 
7784   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7785   if (field == nullptr) return (Node *) nullptr;
7786 
7787   if (is_static) {
7788     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7789     fromObj = makecon(tip);
7790   }
7791 
7792   // Next code  copied from Parse::do_get_xxx():
7793 
7794   // Compute address and memory type.
7795   int offset  = field->offset_in_bytes();
7796   bool is_vol = field->is_volatile();
7797   ciType* field_klass = field->type();
7798   assert(field_klass->is_loaded(), "should be loaded");
7799   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7800   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7801   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7802     "slice of address and input slice don't match");
7803   BasicType bt = field->layout_type();
7804 
7805   // Build the resultant type of the load
7806   const Type *type;
7807   if (bt == T_OBJECT) {
7808     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7809   } else {
7810     type = Type::get_const_basic_type(bt);
7811   }
7812 
7813   if (is_vol) {
7814     decorators |= MO_SEQ_CST;
7815   }
7816 
7817   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7818 }
7819 
7820 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7821                                                  bool is_exact /* true */, bool is_static /* false */,
7822                                                  ciInstanceKlass * fromKls /* nullptr */) {
7823   if (fromKls == nullptr) {
7824     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7825     assert(tinst != nullptr, "obj is null");
7826     assert(tinst->is_loaded(), "obj is not loaded");
7827     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7828     fromKls = tinst->instance_klass();
7829   }
7830   else {
7831     assert(is_static, "only for static field access");
7832   }
7833   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7834     ciSymbol::make(fieldTypeString),
7835     is_static);
7836 
7837   assert(field != nullptr, "undefined field");
7838   assert(!field->is_volatile(), "not defined for volatile fields");
7839 
7840   if (is_static) {
7841     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7842     fromObj = makecon(tip);
7843   }
7844 
7845   // Next code  copied from Parse::do_get_xxx():
7846 
7847   // Compute address and memory type.
7848   int offset = field->offset_in_bytes();
7849   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7850 
7851   return adr;
7852 }
7853 
7854 //------------------------------inline_aescrypt_Block-----------------------
7855 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7856   address stubAddr = nullptr;
7857   const char *stubName;
7858   bool is_decrypt = false;
7859   assert(UseAES, "need AES instruction support");
7860 
7861   switch(id) {
7862   case vmIntrinsics::_aescrypt_encryptBlock:
7863     stubAddr = StubRoutines::aescrypt_encryptBlock();
7864     stubName = "aescrypt_encryptBlock";
7865     break;
7866   case vmIntrinsics::_aescrypt_decryptBlock:
7867     stubAddr = StubRoutines::aescrypt_decryptBlock();
7868     stubName = "aescrypt_decryptBlock";
7869     is_decrypt = true;
7870     break;
7871   default:
7872     break;
7873   }
7874   if (stubAddr == nullptr) return false;
7875 
7876   Node* aescrypt_object = argument(0);
7877   Node* src             = argument(1);
7878   Node* src_offset      = argument(2);
7879   Node* dest            = argument(3);
7880   Node* dest_offset     = argument(4);
7881 
7882   src = must_be_not_null(src, true);
7883   dest = must_be_not_null(dest, true);
7884 
7885   // (1) src and dest are arrays.
7886   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7887   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7888   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7889          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7890 
7891   // for the quick and dirty code we will skip all the checks.
7892   // we are just trying to get the call to be generated.
7893   Node* src_start  = src;
7894   Node* dest_start = dest;
7895   if (src_offset != nullptr || dest_offset != nullptr) {
7896     assert(src_offset != nullptr && dest_offset != nullptr, "");
7897     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7898     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7899   }
7900 
7901   // now need to get the start of its expanded key array
7902   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7903   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7904   if (k_start == nullptr) return false;
7905 
7906   // Call the stub.
7907   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7908                     stubAddr, stubName, TypePtr::BOTTOM,
7909                     src_start, dest_start, k_start);
7910 
7911   return true;
7912 }
7913 
7914 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7915 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7916   address stubAddr = nullptr;
7917   const char *stubName = nullptr;
7918   bool is_decrypt = false;
7919   assert(UseAES, "need AES instruction support");
7920 
7921   switch(id) {
7922   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7923     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7924     stubName = "cipherBlockChaining_encryptAESCrypt";
7925     break;
7926   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7927     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7928     stubName = "cipherBlockChaining_decryptAESCrypt";
7929     is_decrypt = true;
7930     break;
7931   default:
7932     break;
7933   }
7934   if (stubAddr == nullptr) return false;
7935 
7936   Node* cipherBlockChaining_object = argument(0);
7937   Node* src                        = argument(1);
7938   Node* src_offset                 = argument(2);
7939   Node* len                        = argument(3);
7940   Node* dest                       = argument(4);
7941   Node* dest_offset                = argument(5);
7942 
7943   src = must_be_not_null(src, false);
7944   dest = must_be_not_null(dest, false);
7945 
7946   // (1) src and dest are arrays.
7947   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7948   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7949   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7950          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7951 
7952   // checks are the responsibility of the caller
7953   Node* src_start  = src;
7954   Node* dest_start = dest;
7955   if (src_offset != nullptr || dest_offset != nullptr) {
7956     assert(src_offset != nullptr && dest_offset != nullptr, "");
7957     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7958     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7959   }
7960 
7961   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7962   // (because of the predicated logic executed earlier).
7963   // so we cast it here safely.
7964   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7965 
7966   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7967   if (embeddedCipherObj == nullptr) return false;
7968 
7969   // cast it to what we know it will be at runtime
7970   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7971   assert(tinst != nullptr, "CBC obj is null");
7972   assert(tinst->is_loaded(), "CBC obj is not loaded");
7973   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7974   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7975 
7976   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7977   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7978   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7979   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7980   aescrypt_object = _gvn.transform(aescrypt_object);
7981 
7982   // we need to get the start of the aescrypt_object's expanded key array
7983   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7984   if (k_start == nullptr) return false;
7985 
7986   // similarly, get the start address of the r vector
7987   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7988   if (objRvec == nullptr) return false;
7989   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7990 
7991   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7992   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7993                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7994                                      stubAddr, stubName, TypePtr::BOTTOM,
7995                                      src_start, dest_start, k_start, r_start, len);
7996 
7997   // return cipher length (int)
7998   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7999   set_result(retvalue);
8000   return true;
8001 }
8002 
8003 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8004 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8005   address stubAddr = nullptr;
8006   const char *stubName = nullptr;
8007   bool is_decrypt = false;
8008   assert(UseAES, "need AES instruction support");
8009 
8010   switch (id) {
8011   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8012     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8013     stubName = "electronicCodeBook_encryptAESCrypt";
8014     break;
8015   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8016     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8017     stubName = "electronicCodeBook_decryptAESCrypt";
8018     is_decrypt = true;
8019     break;
8020   default:
8021     break;
8022   }
8023 
8024   if (stubAddr == nullptr) return false;
8025 
8026   Node* electronicCodeBook_object = argument(0);
8027   Node* src                       = argument(1);
8028   Node* src_offset                = argument(2);
8029   Node* len                       = argument(3);
8030   Node* dest                      = argument(4);
8031   Node* dest_offset               = argument(5);
8032 
8033   // (1) src and dest are arrays.
8034   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8035   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8036   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8037          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8038 
8039   // checks are the responsibility of the caller
8040   Node* src_start = src;
8041   Node* dest_start = dest;
8042   if (src_offset != nullptr || dest_offset != nullptr) {
8043     assert(src_offset != nullptr && dest_offset != nullptr, "");
8044     src_start = array_element_address(src, src_offset, T_BYTE);
8045     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8046   }
8047 
8048   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8049   // (because of the predicated logic executed earlier).
8050   // so we cast it here safely.
8051   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8052 
8053   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8054   if (embeddedCipherObj == nullptr) return false;
8055 
8056   // cast it to what we know it will be at runtime
8057   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8058   assert(tinst != nullptr, "ECB obj is null");
8059   assert(tinst->is_loaded(), "ECB obj is not loaded");
8060   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8061   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8062 
8063   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8064   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8065   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8066   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8067   aescrypt_object = _gvn.transform(aescrypt_object);
8068 
8069   // we need to get the start of the aescrypt_object's expanded key array
8070   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8071   if (k_start == nullptr) return false;
8072 
8073   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8074   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8075                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8076                                      stubAddr, stubName, TypePtr::BOTTOM,
8077                                      src_start, dest_start, k_start, len);
8078 
8079   // return cipher length (int)
8080   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8081   set_result(retvalue);
8082   return true;
8083 }
8084 
8085 //------------------------------inline_counterMode_AESCrypt-----------------------
8086 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8087   assert(UseAES, "need AES instruction support");
8088   if (!UseAESCTRIntrinsics) return false;
8089 
8090   address stubAddr = nullptr;
8091   const char *stubName = nullptr;
8092   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8093     stubAddr = StubRoutines::counterMode_AESCrypt();
8094     stubName = "counterMode_AESCrypt";
8095   }
8096   if (stubAddr == nullptr) return false;
8097 
8098   Node* counterMode_object = argument(0);
8099   Node* src = argument(1);
8100   Node* src_offset = argument(2);
8101   Node* len = argument(3);
8102   Node* dest = argument(4);
8103   Node* dest_offset = argument(5);
8104 
8105   // (1) src and dest are arrays.
8106   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8107   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8108   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8109          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8110 
8111   // checks are the responsibility of the caller
8112   Node* src_start = src;
8113   Node* dest_start = dest;
8114   if (src_offset != nullptr || dest_offset != nullptr) {
8115     assert(src_offset != nullptr && dest_offset != nullptr, "");
8116     src_start = array_element_address(src, src_offset, T_BYTE);
8117     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8118   }
8119 
8120   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8121   // (because of the predicated logic executed earlier).
8122   // so we cast it here safely.
8123   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8124   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8125   if (embeddedCipherObj == nullptr) return false;
8126   // cast it to what we know it will be at runtime
8127   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8128   assert(tinst != nullptr, "CTR obj is null");
8129   assert(tinst->is_loaded(), "CTR obj is not loaded");
8130   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8131   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8132   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8133   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8134   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8135   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8136   aescrypt_object = _gvn.transform(aescrypt_object);
8137   // we need to get the start of the aescrypt_object's expanded key array
8138   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8139   if (k_start == nullptr) return false;
8140   // similarly, get the start address of the r vector
8141   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8142   if (obj_counter == nullptr) return false;
8143   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8144 
8145   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8146   if (saved_encCounter == nullptr) return false;
8147   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8148   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8149 
8150   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8151   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8152                                      OptoRuntime::counterMode_aescrypt_Type(),
8153                                      stubAddr, stubName, TypePtr::BOTTOM,
8154                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8155 
8156   // return cipher length (int)
8157   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8158   set_result(retvalue);
8159   return true;
8160 }
8161 
8162 //------------------------------get_key_start_from_aescrypt_object-----------------------
8163 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8164   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8165   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8166   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8167   // The following platform specific stubs of encryption and decryption use the same round keys.
8168 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8169   bool use_decryption_key = false;
8170 #else
8171   bool use_decryption_key = is_decrypt;
8172 #endif
8173   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8174   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8175   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8176 
8177   // now have the array, need to get the start address of the selected key array
8178   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8179   return k_start;
8180 }
8181 
8182 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8183 // Return node representing slow path of predicate check.
8184 // the pseudo code we want to emulate with this predicate is:
8185 // for encryption:
8186 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8187 // for decryption:
8188 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8189 //    note cipher==plain is more conservative than the original java code but that's OK
8190 //
8191 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8192   // The receiver was checked for null already.
8193   Node* objCBC = argument(0);
8194 
8195   Node* src = argument(1);
8196   Node* dest = argument(4);
8197 
8198   // Load embeddedCipher field of CipherBlockChaining object.
8199   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8200 
8201   // get AESCrypt klass for instanceOf check
8202   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8203   // will have same classloader as CipherBlockChaining object
8204   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8205   assert(tinst != nullptr, "CBCobj is null");
8206   assert(tinst->is_loaded(), "CBCobj is not loaded");
8207 
8208   // we want to do an instanceof comparison against the AESCrypt class
8209   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8210   if (!klass_AESCrypt->is_loaded()) {
8211     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8212     Node* ctrl = control();
8213     set_control(top()); // no regular fast path
8214     return ctrl;
8215   }
8216 
8217   src = must_be_not_null(src, true);
8218   dest = must_be_not_null(dest, true);
8219 
8220   // Resolve oops to stable for CmpP below.
8221   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8222 
8223   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8224   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8225   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8226 
8227   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8228 
8229   // for encryption, we are done
8230   if (!decrypting)
8231     return instof_false;  // even if it is null
8232 
8233   // for decryption, we need to add a further check to avoid
8234   // taking the intrinsic path when cipher and plain are the same
8235   // see the original java code for why.
8236   RegionNode* region = new RegionNode(3);
8237   region->init_req(1, instof_false);
8238 
8239   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8240   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8241   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8242   region->init_req(2, src_dest_conjoint);
8243 
8244   record_for_igvn(region);
8245   return _gvn.transform(region);
8246 }
8247 
8248 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8249 // Return node representing slow path of predicate check.
8250 // the pseudo code we want to emulate with this predicate is:
8251 // for encryption:
8252 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8253 // for decryption:
8254 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8255 //    note cipher==plain is more conservative than the original java code but that's OK
8256 //
8257 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8258   // The receiver was checked for null already.
8259   Node* objECB = argument(0);
8260 
8261   // Load embeddedCipher field of ElectronicCodeBook object.
8262   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8263 
8264   // get AESCrypt klass for instanceOf check
8265   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8266   // will have same classloader as ElectronicCodeBook object
8267   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8268   assert(tinst != nullptr, "ECBobj is null");
8269   assert(tinst->is_loaded(), "ECBobj is not loaded");
8270 
8271   // we want to do an instanceof comparison against the AESCrypt class
8272   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8273   if (!klass_AESCrypt->is_loaded()) {
8274     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8275     Node* ctrl = control();
8276     set_control(top()); // no regular fast path
8277     return ctrl;
8278   }
8279   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8280 
8281   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8282   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8283   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8284 
8285   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8286 
8287   // for encryption, we are done
8288   if (!decrypting)
8289     return instof_false;  // even if it is null
8290 
8291   // for decryption, we need to add a further check to avoid
8292   // taking the intrinsic path when cipher and plain are the same
8293   // see the original java code for why.
8294   RegionNode* region = new RegionNode(3);
8295   region->init_req(1, instof_false);
8296   Node* src = argument(1);
8297   Node* dest = argument(4);
8298   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8299   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8300   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8301   region->init_req(2, src_dest_conjoint);
8302 
8303   record_for_igvn(region);
8304   return _gvn.transform(region);
8305 }
8306 
8307 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8308 // Return node representing slow path of predicate check.
8309 // the pseudo code we want to emulate with this predicate is:
8310 // for encryption:
8311 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8312 // for decryption:
8313 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8314 //    note cipher==plain is more conservative than the original java code but that's OK
8315 //
8316 
8317 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8318   // The receiver was checked for null already.
8319   Node* objCTR = argument(0);
8320 
8321   // Load embeddedCipher field of CipherBlockChaining object.
8322   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8323 
8324   // get AESCrypt klass for instanceOf check
8325   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8326   // will have same classloader as CipherBlockChaining object
8327   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8328   assert(tinst != nullptr, "CTRobj is null");
8329   assert(tinst->is_loaded(), "CTRobj is not loaded");
8330 
8331   // we want to do an instanceof comparison against the AESCrypt class
8332   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8333   if (!klass_AESCrypt->is_loaded()) {
8334     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8335     Node* ctrl = control();
8336     set_control(top()); // no regular fast path
8337     return ctrl;
8338   }
8339 
8340   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8341   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8342   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8343   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8344   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8345 
8346   return instof_false; // even if it is null
8347 }
8348 
8349 //------------------------------inline_ghash_processBlocks
8350 bool LibraryCallKit::inline_ghash_processBlocks() {
8351   address stubAddr;
8352   const char *stubName;
8353   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8354 
8355   stubAddr = StubRoutines::ghash_processBlocks();
8356   stubName = "ghash_processBlocks";
8357 
8358   Node* data           = argument(0);
8359   Node* offset         = argument(1);
8360   Node* len            = argument(2);
8361   Node* state          = argument(3);
8362   Node* subkeyH        = argument(4);
8363 
8364   state = must_be_not_null(state, true);
8365   subkeyH = must_be_not_null(subkeyH, true);
8366   data = must_be_not_null(data, true);
8367 
8368   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8369   assert(state_start, "state is null");
8370   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8371   assert(subkeyH_start, "subkeyH is null");
8372   Node* data_start  = array_element_address(data, offset, T_BYTE);
8373   assert(data_start, "data is null");
8374 
8375   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8376                                   OptoRuntime::ghash_processBlocks_Type(),
8377                                   stubAddr, stubName, TypePtr::BOTTOM,
8378                                   state_start, subkeyH_start, data_start, len);
8379   return true;
8380 }
8381 
8382 //------------------------------inline_chacha20Block
8383 bool LibraryCallKit::inline_chacha20Block() {
8384   address stubAddr;
8385   const char *stubName;
8386   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8387 
8388   stubAddr = StubRoutines::chacha20Block();
8389   stubName = "chacha20Block";
8390 
8391   Node* state          = argument(0);
8392   Node* result         = argument(1);
8393 
8394   state = must_be_not_null(state, true);
8395   result = must_be_not_null(result, true);
8396 
8397   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8398   assert(state_start, "state is null");
8399   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8400   assert(result_start, "result is null");
8401 
8402   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8403                                   OptoRuntime::chacha20Block_Type(),
8404                                   stubAddr, stubName, TypePtr::BOTTOM,
8405                                   state_start, result_start);
8406   // return key stream length (int)
8407   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8408   set_result(retvalue);
8409   return true;
8410 }
8411 
8412 //------------------------------inline_kyberNtt
8413 bool LibraryCallKit::inline_kyberNtt() {
8414   address stubAddr;
8415   const char *stubName;
8416   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8417   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8418 
8419   stubAddr = StubRoutines::kyberNtt();
8420   stubName = "kyberNtt";
8421   if (!stubAddr) return false;
8422 
8423   Node* coeffs          = argument(0);
8424   Node* ntt_zetas        = argument(1);
8425 
8426   coeffs = must_be_not_null(coeffs, true);
8427   ntt_zetas = must_be_not_null(ntt_zetas, true);
8428 
8429   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8430   assert(coeffs_start, "coeffs is null");
8431   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8432   assert(ntt_zetas_start, "ntt_zetas is null");
8433   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8434                                   OptoRuntime::kyberNtt_Type(),
8435                                   stubAddr, stubName, TypePtr::BOTTOM,
8436                                   coeffs_start, ntt_zetas_start);
8437   // return an int
8438   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8439   set_result(retvalue);
8440   return true;
8441 }
8442 
8443 //------------------------------inline_kyberInverseNtt
8444 bool LibraryCallKit::inline_kyberInverseNtt() {
8445   address stubAddr;
8446   const char *stubName;
8447   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8448   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8449 
8450   stubAddr = StubRoutines::kyberInverseNtt();
8451   stubName = "kyberInverseNtt";
8452   if (!stubAddr) return false;
8453 
8454   Node* coeffs          = argument(0);
8455   Node* zetas           = argument(1);
8456 
8457   coeffs = must_be_not_null(coeffs, true);
8458   zetas = must_be_not_null(zetas, true);
8459 
8460   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8461   assert(coeffs_start, "coeffs is null");
8462   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8463   assert(zetas_start, "inverseNtt_zetas is null");
8464   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8465                                   OptoRuntime::kyberInverseNtt_Type(),
8466                                   stubAddr, stubName, TypePtr::BOTTOM,
8467                                   coeffs_start, zetas_start);
8468 
8469   // return an int
8470   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8471   set_result(retvalue);
8472   return true;
8473 }
8474 
8475 //------------------------------inline_kyberNttMult
8476 bool LibraryCallKit::inline_kyberNttMult() {
8477   address stubAddr;
8478   const char *stubName;
8479   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8480   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8481 
8482   stubAddr = StubRoutines::kyberNttMult();
8483   stubName = "kyberNttMult";
8484   if (!stubAddr) return false;
8485 
8486   Node* result          = argument(0);
8487   Node* ntta            = argument(1);
8488   Node* nttb            = argument(2);
8489   Node* zetas           = argument(3);
8490 
8491   result = must_be_not_null(result, true);
8492   ntta = must_be_not_null(ntta, true);
8493   nttb = must_be_not_null(nttb, true);
8494   zetas = must_be_not_null(zetas, true);
8495 
8496   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8497   assert(result_start, "result is null");
8498   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8499   assert(ntta_start, "ntta is null");
8500   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8501   assert(nttb_start, "nttb is null");
8502   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8503   assert(zetas_start, "nttMult_zetas is null");
8504   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8505                                   OptoRuntime::kyberNttMult_Type(),
8506                                   stubAddr, stubName, TypePtr::BOTTOM,
8507                                   result_start, ntta_start, nttb_start,
8508                                   zetas_start);
8509 
8510   // return an int
8511   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8512   set_result(retvalue);
8513 
8514   return true;
8515 }
8516 
8517 //------------------------------inline_kyberAddPoly_2
8518 bool LibraryCallKit::inline_kyberAddPoly_2() {
8519   address stubAddr;
8520   const char *stubName;
8521   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8522   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8523 
8524   stubAddr = StubRoutines::kyberAddPoly_2();
8525   stubName = "kyberAddPoly_2";
8526   if (!stubAddr) return false;
8527 
8528   Node* result          = argument(0);
8529   Node* a               = argument(1);
8530   Node* b               = argument(2);
8531 
8532   result = must_be_not_null(result, true);
8533   a = must_be_not_null(a, true);
8534   b = must_be_not_null(b, true);
8535 
8536   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8537   assert(result_start, "result is null");
8538   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8539   assert(a_start, "a is null");
8540   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8541   assert(b_start, "b is null");
8542   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8543                                   OptoRuntime::kyberAddPoly_2_Type(),
8544                                   stubAddr, stubName, TypePtr::BOTTOM,
8545                                   result_start, a_start, b_start);
8546   // return an int
8547   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8548   set_result(retvalue);
8549   return true;
8550 }
8551 
8552 //------------------------------inline_kyberAddPoly_3
8553 bool LibraryCallKit::inline_kyberAddPoly_3() {
8554   address stubAddr;
8555   const char *stubName;
8556   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8557   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8558 
8559   stubAddr = StubRoutines::kyberAddPoly_3();
8560   stubName = "kyberAddPoly_3";
8561   if (!stubAddr) return false;
8562 
8563   Node* result          = argument(0);
8564   Node* a               = argument(1);
8565   Node* b               = argument(2);
8566   Node* c               = argument(3);
8567 
8568   result = must_be_not_null(result, true);
8569   a = must_be_not_null(a, true);
8570   b = must_be_not_null(b, true);
8571   c = must_be_not_null(c, true);
8572 
8573   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8574   assert(result_start, "result is null");
8575   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8576   assert(a_start, "a is null");
8577   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8578   assert(b_start, "b is null");
8579   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8580   assert(c_start, "c is null");
8581   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8582                                   OptoRuntime::kyberAddPoly_3_Type(),
8583                                   stubAddr, stubName, TypePtr::BOTTOM,
8584                                   result_start, a_start, b_start, c_start);
8585   // return an int
8586   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8587   set_result(retvalue);
8588   return true;
8589 }
8590 
8591 //------------------------------inline_kyber12To16
8592 bool LibraryCallKit::inline_kyber12To16() {
8593   address stubAddr;
8594   const char *stubName;
8595   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8596   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8597 
8598   stubAddr = StubRoutines::kyber12To16();
8599   stubName = "kyber12To16";
8600   if (!stubAddr) return false;
8601 
8602   Node* condensed       = argument(0);
8603   Node* condensedOffs   = argument(1);
8604   Node* parsed          = argument(2);
8605   Node* parsedLength    = argument(3);
8606 
8607   condensed = must_be_not_null(condensed, true);
8608   parsed = must_be_not_null(parsed, true);
8609 
8610   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8611   assert(condensed_start, "condensed is null");
8612   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8613   assert(parsed_start, "parsed is null");
8614   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8615                                   OptoRuntime::kyber12To16_Type(),
8616                                   stubAddr, stubName, TypePtr::BOTTOM,
8617                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8618   // return an int
8619   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8620   set_result(retvalue);
8621   return true;
8622 
8623 }
8624 
8625 //------------------------------inline_kyberBarrettReduce
8626 bool LibraryCallKit::inline_kyberBarrettReduce() {
8627   address stubAddr;
8628   const char *stubName;
8629   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8630   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8631 
8632   stubAddr = StubRoutines::kyberBarrettReduce();
8633   stubName = "kyberBarrettReduce";
8634   if (!stubAddr) return false;
8635 
8636   Node* coeffs          = argument(0);
8637 
8638   coeffs = must_be_not_null(coeffs, true);
8639 
8640   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8641   assert(coeffs_start, "coeffs is null");
8642   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8643                                   OptoRuntime::kyberBarrettReduce_Type(),
8644                                   stubAddr, stubName, TypePtr::BOTTOM,
8645                                   coeffs_start);
8646   // return an int
8647   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8648   set_result(retvalue);
8649   return true;
8650 }
8651 
8652 //------------------------------inline_dilithiumAlmostNtt
8653 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8654   address stubAddr;
8655   const char *stubName;
8656   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8657   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8658 
8659   stubAddr = StubRoutines::dilithiumAlmostNtt();
8660   stubName = "dilithiumAlmostNtt";
8661   if (!stubAddr) return false;
8662 
8663   Node* coeffs          = argument(0);
8664   Node* ntt_zetas        = argument(1);
8665 
8666   coeffs = must_be_not_null(coeffs, true);
8667   ntt_zetas = must_be_not_null(ntt_zetas, true);
8668 
8669   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8670   assert(coeffs_start, "coeffs is null");
8671   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8672   assert(ntt_zetas_start, "ntt_zetas is null");
8673   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8674                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8675                                   stubAddr, stubName, TypePtr::BOTTOM,
8676                                   coeffs_start, ntt_zetas_start);
8677   // return an int
8678   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8679   set_result(retvalue);
8680   return true;
8681 }
8682 
8683 //------------------------------inline_dilithiumAlmostInverseNtt
8684 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8685   address stubAddr;
8686   const char *stubName;
8687   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8688   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8689 
8690   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8691   stubName = "dilithiumAlmostInverseNtt";
8692   if (!stubAddr) return false;
8693 
8694   Node* coeffs          = argument(0);
8695   Node* zetas           = argument(1);
8696 
8697   coeffs = must_be_not_null(coeffs, true);
8698   zetas = must_be_not_null(zetas, true);
8699 
8700   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8701   assert(coeffs_start, "coeffs is null");
8702   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8703   assert(zetas_start, "inverseNtt_zetas is null");
8704   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8705                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8706                                   stubAddr, stubName, TypePtr::BOTTOM,
8707                                   coeffs_start, zetas_start);
8708   // return an int
8709   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8710   set_result(retvalue);
8711   return true;
8712 }
8713 
8714 //------------------------------inline_dilithiumNttMult
8715 bool LibraryCallKit::inline_dilithiumNttMult() {
8716   address stubAddr;
8717   const char *stubName;
8718   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8719   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8720 
8721   stubAddr = StubRoutines::dilithiumNttMult();
8722   stubName = "dilithiumNttMult";
8723   if (!stubAddr) return false;
8724 
8725   Node* result          = argument(0);
8726   Node* ntta            = argument(1);
8727   Node* nttb            = argument(2);
8728   Node* zetas           = argument(3);
8729 
8730   result = must_be_not_null(result, true);
8731   ntta = must_be_not_null(ntta, true);
8732   nttb = must_be_not_null(nttb, true);
8733   zetas = must_be_not_null(zetas, true);
8734 
8735   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8736   assert(result_start, "result is null");
8737   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8738   assert(ntta_start, "ntta is null");
8739   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8740   assert(nttb_start, "nttb is null");
8741   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8742                                   OptoRuntime::dilithiumNttMult_Type(),
8743                                   stubAddr, stubName, TypePtr::BOTTOM,
8744                                   result_start, ntta_start, nttb_start);
8745 
8746   // return an int
8747   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8748   set_result(retvalue);
8749 
8750   return true;
8751 }
8752 
8753 //------------------------------inline_dilithiumMontMulByConstant
8754 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8755   address stubAddr;
8756   const char *stubName;
8757   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8758   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8759 
8760   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8761   stubName = "dilithiumMontMulByConstant";
8762   if (!stubAddr) return false;
8763 
8764   Node* coeffs          = argument(0);
8765   Node* constant        = argument(1);
8766 
8767   coeffs = must_be_not_null(coeffs, true);
8768 
8769   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8770   assert(coeffs_start, "coeffs is null");
8771   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8772                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8773                                   stubAddr, stubName, TypePtr::BOTTOM,
8774                                   coeffs_start, constant);
8775 
8776   // return an int
8777   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8778   set_result(retvalue);
8779   return true;
8780 }
8781 
8782 
8783 //------------------------------inline_dilithiumDecomposePoly
8784 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8785   address stubAddr;
8786   const char *stubName;
8787   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8788   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8789 
8790   stubAddr = StubRoutines::dilithiumDecomposePoly();
8791   stubName = "dilithiumDecomposePoly";
8792   if (!stubAddr) return false;
8793 
8794   Node* input          = argument(0);
8795   Node* lowPart        = argument(1);
8796   Node* highPart       = argument(2);
8797   Node* twoGamma2      = argument(3);
8798   Node* multiplier     = argument(4);
8799 
8800   input = must_be_not_null(input, true);
8801   lowPart = must_be_not_null(lowPart, true);
8802   highPart = must_be_not_null(highPart, true);
8803 
8804   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8805   assert(input_start, "input is null");
8806   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8807   assert(lowPart_start, "lowPart is null");
8808   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8809   assert(highPart_start, "highPart is null");
8810 
8811   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8812                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8813                                   stubAddr, stubName, TypePtr::BOTTOM,
8814                                   input_start, lowPart_start, highPart_start,
8815                                   twoGamma2, multiplier);
8816 
8817   // return an int
8818   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8819   set_result(retvalue);
8820   return true;
8821 }
8822 
8823 bool LibraryCallKit::inline_base64_encodeBlock() {
8824   address stubAddr;
8825   const char *stubName;
8826   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8827   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8828   stubAddr = StubRoutines::base64_encodeBlock();
8829   stubName = "encodeBlock";
8830 
8831   if (!stubAddr) return false;
8832   Node* base64obj = argument(0);
8833   Node* src = argument(1);
8834   Node* offset = argument(2);
8835   Node* len = argument(3);
8836   Node* dest = argument(4);
8837   Node* dp = argument(5);
8838   Node* isURL = argument(6);
8839 
8840   src = must_be_not_null(src, true);
8841   dest = must_be_not_null(dest, true);
8842 
8843   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8844   assert(src_start, "source array is null");
8845   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8846   assert(dest_start, "destination array is null");
8847 
8848   Node* base64 = make_runtime_call(RC_LEAF,
8849                                    OptoRuntime::base64_encodeBlock_Type(),
8850                                    stubAddr, stubName, TypePtr::BOTTOM,
8851                                    src_start, offset, len, dest_start, dp, isURL);
8852   return true;
8853 }
8854 
8855 bool LibraryCallKit::inline_base64_decodeBlock() {
8856   address stubAddr;
8857   const char *stubName;
8858   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8859   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8860   stubAddr = StubRoutines::base64_decodeBlock();
8861   stubName = "decodeBlock";
8862 
8863   if (!stubAddr) return false;
8864   Node* base64obj = argument(0);
8865   Node* src = argument(1);
8866   Node* src_offset = argument(2);
8867   Node* len = argument(3);
8868   Node* dest = argument(4);
8869   Node* dest_offset = argument(5);
8870   Node* isURL = argument(6);
8871   Node* isMIME = argument(7);
8872 
8873   src = must_be_not_null(src, true);
8874   dest = must_be_not_null(dest, true);
8875 
8876   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8877   assert(src_start, "source array is null");
8878   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8879   assert(dest_start, "destination array is null");
8880 
8881   Node* call = make_runtime_call(RC_LEAF,
8882                                  OptoRuntime::base64_decodeBlock_Type(),
8883                                  stubAddr, stubName, TypePtr::BOTTOM,
8884                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8885   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8886   set_result(result);
8887   return true;
8888 }
8889 
8890 bool LibraryCallKit::inline_poly1305_processBlocks() {
8891   address stubAddr;
8892   const char *stubName;
8893   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8894   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8895   stubAddr = StubRoutines::poly1305_processBlocks();
8896   stubName = "poly1305_processBlocks";
8897 
8898   if (!stubAddr) return false;
8899   null_check_receiver();  // null-check receiver
8900   if (stopped())  return true;
8901 
8902   Node* input = argument(1);
8903   Node* input_offset = argument(2);
8904   Node* len = argument(3);
8905   Node* alimbs = argument(4);
8906   Node* rlimbs = argument(5);
8907 
8908   input = must_be_not_null(input, true);
8909   alimbs = must_be_not_null(alimbs, true);
8910   rlimbs = must_be_not_null(rlimbs, true);
8911 
8912   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8913   assert(input_start, "input array is null");
8914   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8915   assert(acc_start, "acc array is null");
8916   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8917   assert(r_start, "r array is null");
8918 
8919   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8920                                  OptoRuntime::poly1305_processBlocks_Type(),
8921                                  stubAddr, stubName, TypePtr::BOTTOM,
8922                                  input_start, len, acc_start, r_start);
8923   return true;
8924 }
8925 
8926 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8927   address stubAddr;
8928   const char *stubName;
8929   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8930   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8931   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8932   stubName = "intpoly_montgomeryMult_P256";
8933 
8934   if (!stubAddr) return false;
8935   null_check_receiver();  // null-check receiver
8936   if (stopped())  return true;
8937 
8938   Node* a = argument(1);
8939   Node* b = argument(2);
8940   Node* r = argument(3);
8941 
8942   a = must_be_not_null(a, true);
8943   b = must_be_not_null(b, true);
8944   r = must_be_not_null(r, true);
8945 
8946   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8947   assert(a_start, "a array is null");
8948   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8949   assert(b_start, "b array is null");
8950   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8951   assert(r_start, "r array is null");
8952 
8953   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8954                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8955                                  stubAddr, stubName, TypePtr::BOTTOM,
8956                                  a_start, b_start, r_start);
8957   return true;
8958 }
8959 
8960 bool LibraryCallKit::inline_intpoly_assign() {
8961   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8962   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8963   const char *stubName = "intpoly_assign";
8964   address stubAddr = StubRoutines::intpoly_assign();
8965   if (!stubAddr) return false;
8966 
8967   Node* set = argument(0);
8968   Node* a = argument(1);
8969   Node* b = argument(2);
8970   Node* arr_length = load_array_length(a);
8971 
8972   a = must_be_not_null(a, true);
8973   b = must_be_not_null(b, true);
8974 
8975   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8976   assert(a_start, "a array is null");
8977   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8978   assert(b_start, "b array is null");
8979 
8980   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8981                                  OptoRuntime::intpoly_assign_Type(),
8982                                  stubAddr, stubName, TypePtr::BOTTOM,
8983                                  set, a_start, b_start, arr_length);
8984   return true;
8985 }
8986 
8987 //------------------------------inline_digestBase_implCompress-----------------------
8988 //
8989 // Calculate MD5 for single-block byte[] array.
8990 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8991 //
8992 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8993 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8994 //
8995 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8996 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8997 //
8998 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8999 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9000 //
9001 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9002 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9003 //
9004 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9005   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9006 
9007   Node* digestBase_obj = argument(0);
9008   Node* src            = argument(1); // type oop
9009   Node* ofs            = argument(2); // type int
9010 
9011   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9012   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9013     // failed array check
9014     return false;
9015   }
9016   // Figure out the size and type of the elements we will be copying.
9017   BasicType src_elem = src_type->elem()->array_element_basic_type();
9018   if (src_elem != T_BYTE) {
9019     return false;
9020   }
9021   // 'src_start' points to src array + offset
9022   src = must_be_not_null(src, true);
9023   Node* src_start = array_element_address(src, ofs, src_elem);
9024   Node* state = nullptr;
9025   Node* block_size = nullptr;
9026   address stubAddr;
9027   const char *stubName;
9028 
9029   switch(id) {
9030   case vmIntrinsics::_md5_implCompress:
9031     assert(UseMD5Intrinsics, "need MD5 instruction support");
9032     state = get_state_from_digest_object(digestBase_obj, T_INT);
9033     stubAddr = StubRoutines::md5_implCompress();
9034     stubName = "md5_implCompress";
9035     break;
9036   case vmIntrinsics::_sha_implCompress:
9037     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9038     state = get_state_from_digest_object(digestBase_obj, T_INT);
9039     stubAddr = StubRoutines::sha1_implCompress();
9040     stubName = "sha1_implCompress";
9041     break;
9042   case vmIntrinsics::_sha2_implCompress:
9043     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9044     state = get_state_from_digest_object(digestBase_obj, T_INT);
9045     stubAddr = StubRoutines::sha256_implCompress();
9046     stubName = "sha256_implCompress";
9047     break;
9048   case vmIntrinsics::_sha5_implCompress:
9049     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9050     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9051     stubAddr = StubRoutines::sha512_implCompress();
9052     stubName = "sha512_implCompress";
9053     break;
9054   case vmIntrinsics::_sha3_implCompress:
9055     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9056     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9057     stubAddr = StubRoutines::sha3_implCompress();
9058     stubName = "sha3_implCompress";
9059     block_size = get_block_size_from_digest_object(digestBase_obj);
9060     if (block_size == nullptr) return false;
9061     break;
9062   default:
9063     fatal_unexpected_iid(id);
9064     return false;
9065   }
9066   if (state == nullptr) return false;
9067 
9068   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9069   if (stubAddr == nullptr) return false;
9070 
9071   // Call the stub.
9072   Node* call;
9073   if (block_size == nullptr) {
9074     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9075                              stubAddr, stubName, TypePtr::BOTTOM,
9076                              src_start, state);
9077   } else {
9078     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9079                              stubAddr, stubName, TypePtr::BOTTOM,
9080                              src_start, state, block_size);
9081   }
9082 
9083   return true;
9084 }
9085 
9086 //------------------------------inline_double_keccak
9087 bool LibraryCallKit::inline_double_keccak() {
9088   address stubAddr;
9089   const char *stubName;
9090   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9091   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9092 
9093   stubAddr = StubRoutines::double_keccak();
9094   stubName = "double_keccak";
9095   if (!stubAddr) return false;
9096 
9097   Node* status0        = argument(0);
9098   Node* status1        = argument(1);
9099 
9100   status0 = must_be_not_null(status0, true);
9101   status1 = must_be_not_null(status1, true);
9102 
9103   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9104   assert(status0_start, "status0 is null");
9105   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9106   assert(status1_start, "status1 is null");
9107   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9108                                   OptoRuntime::double_keccak_Type(),
9109                                   stubAddr, stubName, TypePtr::BOTTOM,
9110                                   status0_start, status1_start);
9111   // return an int
9112   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9113   set_result(retvalue);
9114   return true;
9115 }
9116 
9117 
9118 //------------------------------inline_digestBase_implCompressMB-----------------------
9119 //
9120 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9121 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9122 //
9123 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9124   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9125          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9126   assert((uint)predicate < 5, "sanity");
9127   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9128 
9129   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9130   Node* src            = argument(1); // byte[] array
9131   Node* ofs            = argument(2); // type int
9132   Node* limit          = argument(3); // type int
9133 
9134   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9135   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9136     // failed array check
9137     return false;
9138   }
9139   // Figure out the size and type of the elements we will be copying.
9140   BasicType src_elem = src_type->elem()->array_element_basic_type();
9141   if (src_elem != T_BYTE) {
9142     return false;
9143   }
9144   // 'src_start' points to src array + offset
9145   src = must_be_not_null(src, false);
9146   Node* src_start = array_element_address(src, ofs, src_elem);
9147 
9148   const char* klass_digestBase_name = nullptr;
9149   const char* stub_name = nullptr;
9150   address     stub_addr = nullptr;
9151   BasicType elem_type = T_INT;
9152 
9153   switch (predicate) {
9154   case 0:
9155     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9156       klass_digestBase_name = "sun/security/provider/MD5";
9157       stub_name = "md5_implCompressMB";
9158       stub_addr = StubRoutines::md5_implCompressMB();
9159     }
9160     break;
9161   case 1:
9162     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9163       klass_digestBase_name = "sun/security/provider/SHA";
9164       stub_name = "sha1_implCompressMB";
9165       stub_addr = StubRoutines::sha1_implCompressMB();
9166     }
9167     break;
9168   case 2:
9169     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9170       klass_digestBase_name = "sun/security/provider/SHA2";
9171       stub_name = "sha256_implCompressMB";
9172       stub_addr = StubRoutines::sha256_implCompressMB();
9173     }
9174     break;
9175   case 3:
9176     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9177       klass_digestBase_name = "sun/security/provider/SHA5";
9178       stub_name = "sha512_implCompressMB";
9179       stub_addr = StubRoutines::sha512_implCompressMB();
9180       elem_type = T_LONG;
9181     }
9182     break;
9183   case 4:
9184     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9185       klass_digestBase_name = "sun/security/provider/SHA3";
9186       stub_name = "sha3_implCompressMB";
9187       stub_addr = StubRoutines::sha3_implCompressMB();
9188       elem_type = T_LONG;
9189     }
9190     break;
9191   default:
9192     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9193   }
9194   if (klass_digestBase_name != nullptr) {
9195     assert(stub_addr != nullptr, "Stub is generated");
9196     if (stub_addr == nullptr) return false;
9197 
9198     // get DigestBase klass to lookup for SHA klass
9199     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9200     assert(tinst != nullptr, "digestBase_obj is not instance???");
9201     assert(tinst->is_loaded(), "DigestBase is not loaded");
9202 
9203     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9204     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9205     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9206     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9207   }
9208   return false;
9209 }
9210 
9211 //------------------------------inline_digestBase_implCompressMB-----------------------
9212 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9213                                                       BasicType elem_type, address stubAddr, const char *stubName,
9214                                                       Node* src_start, Node* ofs, Node* limit) {
9215   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9216   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9217   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9218   digest_obj = _gvn.transform(digest_obj);
9219 
9220   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9221   if (state == nullptr) return false;
9222 
9223   Node* block_size = nullptr;
9224   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9225     block_size = get_block_size_from_digest_object(digest_obj);
9226     if (block_size == nullptr) return false;
9227   }
9228 
9229   // Call the stub.
9230   Node* call;
9231   if (block_size == nullptr) {
9232     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9233                              OptoRuntime::digestBase_implCompressMB_Type(false),
9234                              stubAddr, stubName, TypePtr::BOTTOM,
9235                              src_start, state, ofs, limit);
9236   } else {
9237      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9238                              OptoRuntime::digestBase_implCompressMB_Type(true),
9239                              stubAddr, stubName, TypePtr::BOTTOM,
9240                              src_start, state, block_size, ofs, limit);
9241   }
9242 
9243   // return ofs (int)
9244   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9245   set_result(result);
9246 
9247   return true;
9248 }
9249 
9250 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9251 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9252   assert(UseAES, "need AES instruction support");
9253   address stubAddr = nullptr;
9254   const char *stubName = nullptr;
9255   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9256   stubName = "galoisCounterMode_AESCrypt";
9257 
9258   if (stubAddr == nullptr) return false;
9259 
9260   Node* in      = argument(0);
9261   Node* inOfs   = argument(1);
9262   Node* len     = argument(2);
9263   Node* ct      = argument(3);
9264   Node* ctOfs   = argument(4);
9265   Node* out     = argument(5);
9266   Node* outOfs  = argument(6);
9267   Node* gctr_object = argument(7);
9268   Node* ghash_object = argument(8);
9269 
9270   // (1) in, ct and out are arrays.
9271   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9272   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9273   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9274   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9275           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9276          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9277 
9278   // checks are the responsibility of the caller
9279   Node* in_start = in;
9280   Node* ct_start = ct;
9281   Node* out_start = out;
9282   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9283     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9284     in_start = array_element_address(in, inOfs, T_BYTE);
9285     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9286     out_start = array_element_address(out, outOfs, T_BYTE);
9287   }
9288 
9289   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9290   // (because of the predicated logic executed earlier).
9291   // so we cast it here safely.
9292   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9293   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9294   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9295   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9296   Node* state = load_field_from_object(ghash_object, "state", "[J");
9297 
9298   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9299     return false;
9300   }
9301   // cast it to what we know it will be at runtime
9302   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9303   assert(tinst != nullptr, "GCTR obj is null");
9304   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9305   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9306   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9307   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9308   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9309   const TypeOopPtr* xtype = aklass->as_instance_type();
9310   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9311   aescrypt_object = _gvn.transform(aescrypt_object);
9312   // we need to get the start of the aescrypt_object's expanded key array
9313   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9314   if (k_start == nullptr) return false;
9315   // similarly, get the start address of the r vector
9316   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9317   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9318   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9319 
9320 
9321   // Call the stub, passing params
9322   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9323                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9324                                stubAddr, stubName, TypePtr::BOTTOM,
9325                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9326 
9327   // return cipher length (int)
9328   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9329   set_result(retvalue);
9330 
9331   return true;
9332 }
9333 
9334 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9335 // Return node representing slow path of predicate check.
9336 // the pseudo code we want to emulate with this predicate is:
9337 // for encryption:
9338 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9339 // for decryption:
9340 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9341 //    note cipher==plain is more conservative than the original java code but that's OK
9342 //
9343 
9344 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9345   // The receiver was checked for null already.
9346   Node* objGCTR = argument(7);
9347   // Load embeddedCipher field of GCTR object.
9348   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9349   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9350 
9351   // get AESCrypt klass for instanceOf check
9352   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9353   // will have same classloader as CipherBlockChaining object
9354   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9355   assert(tinst != nullptr, "GCTR obj is null");
9356   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9357 
9358   // we want to do an instanceof comparison against the AESCrypt class
9359   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9360   if (!klass_AESCrypt->is_loaded()) {
9361     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9362     Node* ctrl = control();
9363     set_control(top()); // no regular fast path
9364     return ctrl;
9365   }
9366 
9367   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9368   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9369   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9370   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9371   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9372 
9373   return instof_false; // even if it is null
9374 }
9375 
9376 //------------------------------get_state_from_digest_object-----------------------
9377 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9378   const char* state_type;
9379   switch (elem_type) {
9380     case T_BYTE: state_type = "[B"; break;
9381     case T_INT:  state_type = "[I"; break;
9382     case T_LONG: state_type = "[J"; break;
9383     default: ShouldNotReachHere();
9384   }
9385   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9386   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9387   if (digest_state == nullptr) return (Node *) nullptr;
9388 
9389   // now have the array, need to get the start address of the state array
9390   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9391   return state;
9392 }
9393 
9394 //------------------------------get_block_size_from_sha3_object----------------------------------
9395 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9396   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9397   assert (block_size != nullptr, "sanity");
9398   return block_size;
9399 }
9400 
9401 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9402 // Return node representing slow path of predicate check.
9403 // the pseudo code we want to emulate with this predicate is:
9404 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9405 //
9406 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9407   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9408          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9409   assert((uint)predicate < 5, "sanity");
9410 
9411   // The receiver was checked for null already.
9412   Node* digestBaseObj = argument(0);
9413 
9414   // get DigestBase klass for instanceOf check
9415   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9416   assert(tinst != nullptr, "digestBaseObj is null");
9417   assert(tinst->is_loaded(), "DigestBase is not loaded");
9418 
9419   const char* klass_name = nullptr;
9420   switch (predicate) {
9421   case 0:
9422     if (UseMD5Intrinsics) {
9423       // we want to do an instanceof comparison against the MD5 class
9424       klass_name = "sun/security/provider/MD5";
9425     }
9426     break;
9427   case 1:
9428     if (UseSHA1Intrinsics) {
9429       // we want to do an instanceof comparison against the SHA class
9430       klass_name = "sun/security/provider/SHA";
9431     }
9432     break;
9433   case 2:
9434     if (UseSHA256Intrinsics) {
9435       // we want to do an instanceof comparison against the SHA2 class
9436       klass_name = "sun/security/provider/SHA2";
9437     }
9438     break;
9439   case 3:
9440     if (UseSHA512Intrinsics) {
9441       // we want to do an instanceof comparison against the SHA5 class
9442       klass_name = "sun/security/provider/SHA5";
9443     }
9444     break;
9445   case 4:
9446     if (UseSHA3Intrinsics) {
9447       // we want to do an instanceof comparison against the SHA3 class
9448       klass_name = "sun/security/provider/SHA3";
9449     }
9450     break;
9451   default:
9452     fatal("unknown SHA intrinsic predicate: %d", predicate);
9453   }
9454 
9455   ciKlass* klass = nullptr;
9456   if (klass_name != nullptr) {
9457     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9458   }
9459   if ((klass == nullptr) || !klass->is_loaded()) {
9460     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9461     Node* ctrl = control();
9462     set_control(top()); // no intrinsic path
9463     return ctrl;
9464   }
9465   ciInstanceKlass* instklass = klass->as_instance_klass();
9466 
9467   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9468   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9469   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9470   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9471 
9472   return instof_false;  // even if it is null
9473 }
9474 
9475 //-------------inline_fma-----------------------------------
9476 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9477   Node *a = nullptr;
9478   Node *b = nullptr;
9479   Node *c = nullptr;
9480   Node* result = nullptr;
9481   switch (id) {
9482   case vmIntrinsics::_fmaD:
9483     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9484     // no receiver since it is static method
9485     a = argument(0);
9486     b = argument(2);
9487     c = argument(4);
9488     result = _gvn.transform(new FmaDNode(a, b, c));
9489     break;
9490   case vmIntrinsics::_fmaF:
9491     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9492     a = argument(0);
9493     b = argument(1);
9494     c = argument(2);
9495     result = _gvn.transform(new FmaFNode(a, b, c));
9496     break;
9497   default:
9498     fatal_unexpected_iid(id);  break;
9499   }
9500   set_result(result);
9501   return true;
9502 }
9503 
9504 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9505   // argument(0) is receiver
9506   Node* codePoint = argument(1);
9507   Node* n = nullptr;
9508 
9509   switch (id) {
9510     case vmIntrinsics::_isDigit :
9511       n = new DigitNode(control(), codePoint);
9512       break;
9513     case vmIntrinsics::_isLowerCase :
9514       n = new LowerCaseNode(control(), codePoint);
9515       break;
9516     case vmIntrinsics::_isUpperCase :
9517       n = new UpperCaseNode(control(), codePoint);
9518       break;
9519     case vmIntrinsics::_isWhitespace :
9520       n = new WhitespaceNode(control(), codePoint);
9521       break;
9522     default:
9523       fatal_unexpected_iid(id);
9524   }
9525 
9526   set_result(_gvn.transform(n));
9527   return true;
9528 }
9529 
9530 bool LibraryCallKit::inline_profileBoolean() {
9531   Node* counts = argument(1);
9532   const TypeAryPtr* ary = nullptr;
9533   ciArray* aobj = nullptr;
9534   if (counts->is_Con()
9535       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9536       && (aobj = ary->const_oop()->as_array()) != nullptr
9537       && (aobj->length() == 2)) {
9538     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9539     jint false_cnt = aobj->element_value(0).as_int();
9540     jint  true_cnt = aobj->element_value(1).as_int();
9541 
9542     if (C->log() != nullptr) {
9543       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9544                      false_cnt, true_cnt);
9545     }
9546 
9547     if (false_cnt + true_cnt == 0) {
9548       // According to profile, never executed.
9549       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9550                           Deoptimization::Action_reinterpret);
9551       return true;
9552     }
9553 
9554     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9555     // is a number of each value occurrences.
9556     Node* result = argument(0);
9557     if (false_cnt == 0 || true_cnt == 0) {
9558       // According to profile, one value has been never seen.
9559       int expected_val = (false_cnt == 0) ? 1 : 0;
9560 
9561       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9562       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9563 
9564       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9565       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9566       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9567 
9568       { // Slow path: uncommon trap for never seen value and then reexecute
9569         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9570         // the value has been seen at least once.
9571         PreserveJVMState pjvms(this);
9572         PreserveReexecuteState preexecs(this);
9573         jvms()->set_should_reexecute(true);
9574 
9575         set_control(slow_path);
9576         set_i_o(i_o());
9577 
9578         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9579                             Deoptimization::Action_reinterpret);
9580       }
9581       // The guard for never seen value enables sharpening of the result and
9582       // returning a constant. It allows to eliminate branches on the same value
9583       // later on.
9584       set_control(fast_path);
9585       result = intcon(expected_val);
9586     }
9587     // Stop profiling.
9588     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9589     // By replacing method body with profile data (represented as ProfileBooleanNode
9590     // on IR level) we effectively disable profiling.
9591     // It enables full speed execution once optimized code is generated.
9592     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9593     C->record_for_igvn(profile);
9594     set_result(profile);
9595     return true;
9596   } else {
9597     // Continue profiling.
9598     // Profile data isn't available at the moment. So, execute method's bytecode version.
9599     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9600     // is compiled and counters aren't available since corresponding MethodHandle
9601     // isn't a compile-time constant.
9602     return false;
9603   }
9604 }
9605 
9606 bool LibraryCallKit::inline_isCompileConstant() {
9607   Node* n = argument(0);
9608   set_result(n->is_Con() ? intcon(1) : intcon(0));
9609   return true;
9610 }
9611 
9612 //------------------------------- inline_getObjectSize --------------------------------------
9613 //
9614 // Calculate the runtime size of the object/array.
9615 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9616 //
9617 bool LibraryCallKit::inline_getObjectSize() {
9618   Node* obj = argument(3);
9619   Node* klass_node = load_object_klass(obj);
9620 
9621   jint  layout_con = Klass::_lh_neutral_value;
9622   Node* layout_val = get_layout_helper(klass_node, layout_con);
9623   int   layout_is_con = (layout_val == nullptr);
9624 
9625   if (layout_is_con) {
9626     // Layout helper is constant, can figure out things at compile time.
9627 
9628     if (Klass::layout_helper_is_instance(layout_con)) {
9629       // Instance case:  layout_con contains the size itself.
9630       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9631       set_result(size);
9632     } else {
9633       // Array case: size is round(header + element_size*arraylength).
9634       // Since arraylength is different for every array instance, we have to
9635       // compute the whole thing at runtime.
9636 
9637       Node* arr_length = load_array_length(obj);
9638 
9639       int round_mask = MinObjAlignmentInBytes - 1;
9640       int hsize  = Klass::layout_helper_header_size(layout_con);
9641       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9642 
9643       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9644         round_mask = 0;  // strength-reduce it if it goes away completely
9645       }
9646       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9647       Node* header_size = intcon(hsize + round_mask);
9648 
9649       Node* lengthx = ConvI2X(arr_length);
9650       Node* headerx = ConvI2X(header_size);
9651 
9652       Node* abody = lengthx;
9653       if (eshift != 0) {
9654         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9655       }
9656       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9657       if (round_mask != 0) {
9658         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9659       }
9660       size = ConvX2L(size);
9661       set_result(size);
9662     }
9663   } else {
9664     // Layout helper is not constant, need to test for array-ness at runtime.
9665 
9666     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9667     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9668     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9669     record_for_igvn(result_reg);
9670 
9671     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9672     if (array_ctl != nullptr) {
9673       // Array case: size is round(header + element_size*arraylength).
9674       // Since arraylength is different for every array instance, we have to
9675       // compute the whole thing at runtime.
9676 
9677       PreserveJVMState pjvms(this);
9678       set_control(array_ctl);
9679       Node* arr_length = load_array_length(obj);
9680 
9681       int round_mask = MinObjAlignmentInBytes - 1;
9682       Node* mask = intcon(round_mask);
9683 
9684       Node* hss = intcon(Klass::_lh_header_size_shift);
9685       Node* hsm = intcon(Klass::_lh_header_size_mask);
9686       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9687       header_size = _gvn.transform(new AndINode(header_size, hsm));
9688       header_size = _gvn.transform(new AddINode(header_size, mask));
9689 
9690       // There is no need to mask or shift this value.
9691       // The semantics of LShiftINode include an implicit mask to 0x1F.
9692       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9693       Node* elem_shift = layout_val;
9694 
9695       Node* lengthx = ConvI2X(arr_length);
9696       Node* headerx = ConvI2X(header_size);
9697 
9698       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9699       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9700       if (round_mask != 0) {
9701         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9702       }
9703       size = ConvX2L(size);
9704 
9705       result_reg->init_req(_array_path, control());
9706       result_val->init_req(_array_path, size);
9707     }
9708 
9709     if (!stopped()) {
9710       // Instance case: the layout helper gives us instance size almost directly,
9711       // but we need to mask out the _lh_instance_slow_path_bit.
9712       Node* size = ConvI2X(layout_val);
9713       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9714       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9715       size = _gvn.transform(new AndXNode(size, mask));
9716       size = ConvX2L(size);
9717 
9718       result_reg->init_req(_instance_path, control());
9719       result_val->init_req(_instance_path, size);
9720     }
9721 
9722     set_result(result_reg, result_val);
9723   }
9724 
9725   return true;
9726 }
9727 
9728 //------------------------------- inline_blackhole --------------------------------------
9729 //
9730 // Make sure all arguments to this node are alive.
9731 // This matches methods that were requested to be blackholed through compile commands.
9732 //
9733 bool LibraryCallKit::inline_blackhole() {
9734   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9735   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9736   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9737 
9738   // Blackhole node pinches only the control, not memory. This allows
9739   // the blackhole to be pinned in the loop that computes blackholed
9740   // values, but have no other side effects, like breaking the optimizations
9741   // across the blackhole.
9742 
9743   Node* bh = _gvn.transform(new BlackholeNode(control()));
9744   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9745 
9746   // Bind call arguments as blackhole arguments to keep them alive
9747   uint nargs = callee()->arg_size();
9748   for (uint i = 0; i < nargs; i++) {
9749     bh->add_req(argument(i));
9750   }
9751 
9752   return true;
9753 }
9754 
9755 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9756   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9757   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9758     return nullptr; // box klass is not Float16
9759   }
9760 
9761   // Null check; get notnull casted pointer
9762   Node* null_ctl = top();
9763   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9764   // If not_null_box is dead, only null-path is taken
9765   if (stopped()) {
9766     set_control(null_ctl);
9767     return nullptr;
9768   }
9769   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9770   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9771   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9772   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9773 }
9774 
9775 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9776   PreserveReexecuteState preexecs(this);
9777   jvms()->set_should_reexecute(true);
9778 
9779   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9780   Node* klass_node = makecon(klass_type);
9781   Node* box = new_instance(klass_node);
9782 
9783   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9784   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9785 
9786   Node* field_store = _gvn.transform(access_store_at(box,
9787                                                      value_field,
9788                                                      value_adr_type,
9789                                                      value,
9790                                                      TypeInt::SHORT,
9791                                                      T_SHORT,
9792                                                      IN_HEAP));
9793   set_memory(field_store, value_adr_type);
9794   return box;
9795 }
9796 
9797 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9798   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9799       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9800     return false;
9801   }
9802 
9803   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9804   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9805     return false;
9806   }
9807 
9808   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9809   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9810   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9811                                                     ciSymbols::short_signature(),
9812                                                     false);
9813   assert(field != nullptr, "");
9814 
9815   // Transformed nodes
9816   Node* fld1 = nullptr;
9817   Node* fld2 = nullptr;
9818   Node* fld3 = nullptr;
9819   switch(num_args) {
9820     case 3:
9821       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9822       if (fld3 == nullptr) {
9823         return false;
9824       }
9825       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9826     // fall-through
9827     case 2:
9828       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9829       if (fld2 == nullptr) {
9830         return false;
9831       }
9832       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9833     // fall-through
9834     case 1:
9835       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9836       if (fld1 == nullptr) {
9837         return false;
9838       }
9839       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9840       break;
9841     default: fatal("Unsupported number of arguments %d", num_args);
9842   }
9843 
9844   Node* result = nullptr;
9845   switch (id) {
9846     // Unary operations
9847     case vmIntrinsics::_sqrt_float16:
9848       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9849       break;
9850     // Ternary operations
9851     case vmIntrinsics::_fma_float16:
9852       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9853       break;
9854     default:
9855       fatal_unexpected_iid(id);
9856       break;
9857   }
9858   result = _gvn.transform(new ReinterpretHF2SNode(result));
9859   set_result(box_fp16_value(float16_box_type, field, result));
9860   return true;
9861 }
9862