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