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