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