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