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