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