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