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