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