1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/stubRoutines.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 //---------------------------make_vm_intrinsic----------------------------
  76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  77   vmIntrinsicID id = m->intrinsic_id();
  78   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  79 
  80   if (!m->is_loaded()) {
  81     // Do not attempt to inline unloaded methods.
  82     return nullptr;
  83   }
  84 
  85   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  86   bool is_available = false;
  87 
  88   {
  89     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  90     // the compiler must transition to '_thread_in_vm' state because both
  91     // methods access VM-internal data.
  92     VM_ENTRY_MARK;
  93     methodHandle mh(THREAD, m->get_Method());
  94     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  95     if (is_available && is_virtual) {
  96       is_available = vmIntrinsics::does_virtual_dispatch(id);
  97     }
  98   }
  99 
 100   if (is_available) {
 101     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 102     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 103     return new LibraryIntrinsic(m, is_virtual,
 104                                 vmIntrinsics::predicates_needed(id),
 105                                 vmIntrinsics::does_virtual_dispatch(id),
 106                                 id);
 107   } else {
 108     return nullptr;
 109   }
 110 }
 111 
 112 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 113   LibraryCallKit kit(jvms, this);
 114   Compile* C = kit.C;
 115   int nodes = C->unique();
 116 #ifndef PRODUCT
 117   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 118     char buf[1000];
 119     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 120     tty->print_cr("Intrinsic %s", str);
 121   }
 122 #endif
 123   ciMethod* callee = kit.callee();
 124   const int bci    = kit.bci();
 125 #ifdef ASSERT
 126   Node* ctrl = kit.control();
 127 #endif
 128   // Try to inline the intrinsic.
 129   if (callee->check_intrinsic_candidate() &&
 130       kit.try_to_inline(_last_predicate)) {
 131     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 132                                           : "(intrinsic)";
 133     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 134     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 135     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 136     if (C->log()) {
 137       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 138                      vmIntrinsics::name_at(intrinsic_id()),
 139                      (is_virtual() ? " virtual='1'" : ""),
 140                      C->unique() - nodes);
 141     }
 142     // Push the result from the inlined method onto the stack.
 143     kit.push_result();
 144     return kit.transfer_exceptions_into_jvms();
 145   }
 146 
 147   // The intrinsic bailed out
 148   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 149   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 150   if (jvms->has_method()) {
 151     // Not a root compile.
 152     const char* msg;
 153     if (callee->intrinsic_candidate()) {
 154       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 155     } else {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 157                          : "failed to inline (intrinsic), method not annotated";
 158     }
 159     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 160     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 161   } else {
 162     // Root compile
 163     ResourceMark rm;
 164     stringStream msg_stream;
 165     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 166                      vmIntrinsics::name_at(intrinsic_id()),
 167                      is_virtual() ? " (virtual)" : "", bci);
 168     const char *msg = msg_stream.freeze();
 169     log_debug(jit, inlining)("%s", msg);
 170     if (C->print_intrinsics() || C->print_inlining()) {
 171       tty->print("%s", msg);
 172     }
 173   }
 174   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 175 
 176   return nullptr;
 177 }
 178 
 179 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 180   LibraryCallKit kit(jvms, this);
 181   Compile* C = kit.C;
 182   int nodes = C->unique();
 183   _last_predicate = predicate;
 184 #ifndef PRODUCT
 185   assert(is_predicated() && predicate < predicates_count(), "sanity");
 186   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 187     char buf[1000];
 188     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 189     tty->print_cr("Predicate for intrinsic %s", str);
 190   }
 191 #endif
 192   ciMethod* callee = kit.callee();
 193   const int bci    = kit.bci();
 194 
 195   Node* slow_ctl = kit.try_to_predicate(predicate);
 196   if (!kit.failing()) {
 197     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 198                                           : "(intrinsic, predicate)";
 199     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 200     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 201 
 202     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 203     if (C->log()) {
 204       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 205                      vmIntrinsics::name_at(intrinsic_id()),
 206                      (is_virtual() ? " virtual='1'" : ""),
 207                      C->unique() - nodes);
 208     }
 209     return slow_ctl; // Could be null if the check folds.
 210   }
 211 
 212   // The intrinsic bailed out
 213   if (jvms->has_method()) {
 214     // Not a root compile.
 215     const char* msg = "failed to generate predicate for intrinsic";
 216     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 217     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 218   } else {
 219     // Root compile
 220     ResourceMark rm;
 221     stringStream msg_stream;
 222     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 223                      vmIntrinsics::name_at(intrinsic_id()),
 224                      is_virtual() ? " (virtual)" : "", bci);
 225     const char *msg = msg_stream.freeze();
 226     log_debug(jit, inlining)("%s", msg);
 227     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 228   }
 229   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 230   return nullptr;
 231 }
 232 
 233 bool LibraryCallKit::try_to_inline(int predicate) {
 234   // Handle symbolic names for otherwise undistinguished boolean switches:
 235   const bool is_store       = true;
 236   const bool is_compress    = true;
 237   const bool is_static      = true;
 238   const bool is_volatile    = true;
 239 
 240   if (!jvms()->has_method()) {
 241     // Root JVMState has a null method.
 242     assert(map()->memory()->Opcode() == Op_Parm, "");
 243     // Insert the memory aliasing node
 244     set_all_memory(reset_memory());
 245   }
 246   assert(merged_memory(), "");
 247 
 248   switch (intrinsic_id()) {
 249   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 250   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 251   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 252 
 253   case vmIntrinsics::_ceil:
 254   case vmIntrinsics::_floor:
 255   case vmIntrinsics::_rint:
 256   case vmIntrinsics::_dsin:
 257   case vmIntrinsics::_dcos:
 258   case vmIntrinsics::_dtan:
 259   case vmIntrinsics::_dsinh:
 260   case vmIntrinsics::_dtanh:
 261   case vmIntrinsics::_dcbrt:
 262   case vmIntrinsics::_dabs:
 263   case vmIntrinsics::_fabs:
 264   case vmIntrinsics::_iabs:
 265   case vmIntrinsics::_labs:
 266   case vmIntrinsics::_datan2:
 267   case vmIntrinsics::_dsqrt:
 268   case vmIntrinsics::_dsqrt_strict:
 269   case vmIntrinsics::_dexp:
 270   case vmIntrinsics::_dlog:
 271   case vmIntrinsics::_dlog10:
 272   case vmIntrinsics::_dpow:
 273   case vmIntrinsics::_dcopySign:
 274   case vmIntrinsics::_fcopySign:
 275   case vmIntrinsics::_dsignum:
 276   case vmIntrinsics::_roundF:
 277   case vmIntrinsics::_roundD:
 278   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 279 
 280   case vmIntrinsics::_notify:
 281   case vmIntrinsics::_notifyAll:
 282     return inline_notify(intrinsic_id());
 283 
 284   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 285   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 286   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 287   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 288   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 289   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 290   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 291   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 292   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 293   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 294   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 295   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 296   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 297   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 298 
 299   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 300 
 301   case vmIntrinsics::_arraySort:                return inline_array_sort();
 302   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 303 
 304   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 305   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 306   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 307   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 308 
 309   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 310   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 311   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 312   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 313   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 314   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 315   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 316   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 317 
 318   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 319 
 320   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 321 
 322   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 323   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 324   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 325   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 326 
 327   case vmIntrinsics::_compressStringC:
 328   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 329   case vmIntrinsics::_inflateStringC:
 330   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 331 
 332   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 333   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 344 
 345   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 346   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 347   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 348   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 349   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 350   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 351   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 352   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 353   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 354   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 355 
 356   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 357   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 358   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 359   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 360   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 361   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 362   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 363   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 364   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 365 
 366   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 367   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 368   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 369   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 370   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 371   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 372   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 373   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 374   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 375 
 376   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 377   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 378   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 379   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 380 
 381   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 382   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 383   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 384   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 385 
 386   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 387   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 388   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 389   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 390   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 391   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 392   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 393   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 394   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 395 
 396   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 397   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 398   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 399   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 400   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 401   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 402   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 403   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 404   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 405 
 406   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 407   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 408   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 409   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 410   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 411   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 412   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 413   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 414   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 415 
 416   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 417   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 418   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 419   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 420   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 421   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 422   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 423   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 424   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 425 
 426   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 427   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 428 
 429   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 432   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 433   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 434 
 435   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 439   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 440   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 441   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 442   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 443   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 444   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 445   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 446   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 447   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 448   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 449   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 450   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 451   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 452   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 453   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 454   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 455 
 456   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 457   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 458   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 459   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 460   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 461   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 462   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 463   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 464   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 465   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 466   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 467   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 468   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 469   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 470   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 471 
 472   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 474   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 475   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 476 
 477   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 480   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 481   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 482 
 483   case vmIntrinsics::_loadFence:
 484   case vmIntrinsics::_storeFence:
 485   case vmIntrinsics::_storeStoreFence:
 486   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 487 
 488   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 489   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 490   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 491 
 492   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 493 
 494   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 495   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 496   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 497 
 498   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 499   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 500 
 501   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 502   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 503 
 504 #if INCLUDE_JVMTI
 505   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 506                                                                                          "notifyJvmtiStart", true, false);
 507   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 508                                                                                          "notifyJvmtiEnd", false, true);
 509   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 510                                                                                          "notifyJvmtiMount", false, false);
 511   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
 512                                                                                          "notifyJvmtiUnmount", false, false);
 513   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 514 #endif
 515 
 516 #ifdef JFR_HAVE_INTRINSICS
 517   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 518   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 519   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 520 #endif
 521   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 522   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 523   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 524   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 525   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 526   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 527   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 528   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 529   case vmIntrinsics::_getLength:                return inline_native_getLength();
 530   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 531   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 532   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 533   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 534   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 535   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 536   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 537 
 538   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 539   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 540   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 541   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 542   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 543   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 544   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 545   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 546 
 547   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 548 
 549   case vmIntrinsics::_isInstance:
 550   case vmIntrinsics::_isHidden:
 551   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 552 
 553   case vmIntrinsics::_floatToRawIntBits:
 554   case vmIntrinsics::_floatToIntBits:
 555   case vmIntrinsics::_intBitsToFloat:
 556   case vmIntrinsics::_doubleToRawLongBits:
 557   case vmIntrinsics::_doubleToLongBits:
 558   case vmIntrinsics::_longBitsToDouble:
 559   case vmIntrinsics::_floatToFloat16:
 560   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 561   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 562   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 563   case vmIntrinsics::_floatIsFinite:
 564   case vmIntrinsics::_floatIsInfinite:
 565   case vmIntrinsics::_doubleIsFinite:
 566   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 567 
 568   case vmIntrinsics::_numberOfLeadingZeros_i:
 569   case vmIntrinsics::_numberOfLeadingZeros_l:
 570   case vmIntrinsics::_numberOfTrailingZeros_i:
 571   case vmIntrinsics::_numberOfTrailingZeros_l:
 572   case vmIntrinsics::_bitCount_i:
 573   case vmIntrinsics::_bitCount_l:
 574   case vmIntrinsics::_reverse_i:
 575   case vmIntrinsics::_reverse_l:
 576   case vmIntrinsics::_reverseBytes_i:
 577   case vmIntrinsics::_reverseBytes_l:
 578   case vmIntrinsics::_reverseBytes_s:
 579   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 580 
 581   case vmIntrinsics::_compress_i:
 582   case vmIntrinsics::_compress_l:
 583   case vmIntrinsics::_expand_i:
 584   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 585 
 586   case vmIntrinsics::_compareUnsigned_i:
 587   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 588 
 589   case vmIntrinsics::_divideUnsigned_i:
 590   case vmIntrinsics::_divideUnsigned_l:
 591   case vmIntrinsics::_remainderUnsigned_i:
 592   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 593 
 594   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 595 
 596   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 597   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 598   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 599   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 600   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 601 
 602   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 603 
 604   case vmIntrinsics::_aescrypt_encryptBlock:
 605   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 606 
 607   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 608   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 609     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 612   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 613     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 614 
 615   case vmIntrinsics::_counterMode_AESCrypt:
 616     return inline_counterMode_AESCrypt(intrinsic_id());
 617 
 618   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 619     return inline_galoisCounterMode_AESCrypt();
 620 
 621   case vmIntrinsics::_md5_implCompress:
 622   case vmIntrinsics::_sha_implCompress:
 623   case vmIntrinsics::_sha2_implCompress:
 624   case vmIntrinsics::_sha5_implCompress:
 625   case vmIntrinsics::_sha3_implCompress:
 626     return inline_digestBase_implCompress(intrinsic_id());
 627   case vmIntrinsics::_double_keccak:
 628     return inline_double_keccak();
 629 
 630   case vmIntrinsics::_digestBase_implCompressMB:
 631     return inline_digestBase_implCompressMB(predicate);
 632 
 633   case vmIntrinsics::_multiplyToLen:
 634     return inline_multiplyToLen();
 635 
 636   case vmIntrinsics::_squareToLen:
 637     return inline_squareToLen();
 638 
 639   case vmIntrinsics::_mulAdd:
 640     return inline_mulAdd();
 641 
 642   case vmIntrinsics::_montgomeryMultiply:
 643     return inline_montgomeryMultiply();
 644   case vmIntrinsics::_montgomerySquare:
 645     return inline_montgomerySquare();
 646 
 647   case vmIntrinsics::_bigIntegerRightShiftWorker:
 648     return inline_bigIntegerShift(true);
 649   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 650     return inline_bigIntegerShift(false);
 651 
 652   case vmIntrinsics::_vectorizedMismatch:
 653     return inline_vectorizedMismatch();
 654 
 655   case vmIntrinsics::_ghash_processBlocks:
 656     return inline_ghash_processBlocks();
 657   case vmIntrinsics::_chacha20Block:
 658     return inline_chacha20Block();
 659   case vmIntrinsics::_kyberNtt:
 660     return inline_kyberNtt();
 661   case vmIntrinsics::_kyberInverseNtt:
 662     return inline_kyberInverseNtt();
 663   case vmIntrinsics::_kyberNttMult:
 664     return inline_kyberNttMult();
 665   case vmIntrinsics::_kyberAddPoly_2:
 666     return inline_kyberAddPoly_2();
 667   case vmIntrinsics::_kyberAddPoly_3:
 668     return inline_kyberAddPoly_3();
 669   case vmIntrinsics::_kyber12To16:
 670     return inline_kyber12To16();
 671   case vmIntrinsics::_kyberBarrettReduce:
 672     return inline_kyberBarrettReduce();
 673   case vmIntrinsics::_dilithiumAlmostNtt:
 674     return inline_dilithiumAlmostNtt();
 675   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 676     return inline_dilithiumAlmostInverseNtt();
 677   case vmIntrinsics::_dilithiumNttMult:
 678     return inline_dilithiumNttMult();
 679   case vmIntrinsics::_dilithiumMontMulByConstant:
 680     return inline_dilithiumMontMulByConstant();
 681   case vmIntrinsics::_dilithiumDecomposePoly:
 682     return inline_dilithiumDecomposePoly();
 683   case vmIntrinsics::_base64_encodeBlock:
 684     return inline_base64_encodeBlock();
 685   case vmIntrinsics::_base64_decodeBlock:
 686     return inline_base64_decodeBlock();
 687   case vmIntrinsics::_poly1305_processBlocks:
 688     return inline_poly1305_processBlocks();
 689   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 690     return inline_intpoly_montgomeryMult_P256();
 691   case vmIntrinsics::_intpoly_assign:
 692     return inline_intpoly_assign();
 693   case vmIntrinsics::_encodeISOArray:
 694   case vmIntrinsics::_encodeByteISOArray:
 695     return inline_encodeISOArray(false);
 696   case vmIntrinsics::_encodeAsciiArray:
 697     return inline_encodeISOArray(true);
 698 
 699   case vmIntrinsics::_updateCRC32:
 700     return inline_updateCRC32();
 701   case vmIntrinsics::_updateBytesCRC32:
 702     return inline_updateBytesCRC32();
 703   case vmIntrinsics::_updateByteBufferCRC32:
 704     return inline_updateByteBufferCRC32();
 705 
 706   case vmIntrinsics::_updateBytesCRC32C:
 707     return inline_updateBytesCRC32C();
 708   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 709     return inline_updateDirectByteBufferCRC32C();
 710 
 711   case vmIntrinsics::_updateBytesAdler32:
 712     return inline_updateBytesAdler32();
 713   case vmIntrinsics::_updateByteBufferAdler32:
 714     return inline_updateByteBufferAdler32();
 715 
 716   case vmIntrinsics::_profileBoolean:
 717     return inline_profileBoolean();
 718   case vmIntrinsics::_isCompileConstant:
 719     return inline_isCompileConstant();
 720 
 721   case vmIntrinsics::_countPositives:
 722     return inline_countPositives();
 723 
 724   case vmIntrinsics::_fmaD:
 725   case vmIntrinsics::_fmaF:
 726     return inline_fma(intrinsic_id());
 727 
 728   case vmIntrinsics::_isDigit:
 729   case vmIntrinsics::_isLowerCase:
 730   case vmIntrinsics::_isUpperCase:
 731   case vmIntrinsics::_isWhitespace:
 732     return inline_character_compare(intrinsic_id());
 733 
 734   case vmIntrinsics::_min:
 735   case vmIntrinsics::_max:
 736   case vmIntrinsics::_min_strict:
 737   case vmIntrinsics::_max_strict:
 738   case vmIntrinsics::_minL:
 739   case vmIntrinsics::_maxL:
 740   case vmIntrinsics::_minF:
 741   case vmIntrinsics::_maxF:
 742   case vmIntrinsics::_minD:
 743   case vmIntrinsics::_maxD:
 744   case vmIntrinsics::_minF_strict:
 745   case vmIntrinsics::_maxF_strict:
 746   case vmIntrinsics::_minD_strict:
 747   case vmIntrinsics::_maxD_strict:
 748     return inline_min_max(intrinsic_id());
 749 
 750   case vmIntrinsics::_VectorUnaryOp:
 751     return inline_vector_nary_operation(1);
 752   case vmIntrinsics::_VectorBinaryOp:
 753     return inline_vector_nary_operation(2);
 754   case vmIntrinsics::_VectorUnaryLibOp:
 755     return inline_vector_call(1);
 756   case vmIntrinsics::_VectorBinaryLibOp:
 757     return inline_vector_call(2);
 758   case vmIntrinsics::_VectorTernaryOp:
 759     return inline_vector_nary_operation(3);
 760   case vmIntrinsics::_VectorFromBitsCoerced:
 761     return inline_vector_frombits_coerced();
 762   case vmIntrinsics::_VectorMaskOp:
 763     return inline_vector_mask_operation();
 764   case vmIntrinsics::_VectorLoadOp:
 765     return inline_vector_mem_operation(/*is_store=*/false);
 766   case vmIntrinsics::_VectorLoadMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store*/false);
 768   case vmIntrinsics::_VectorStoreOp:
 769     return inline_vector_mem_operation(/*is_store=*/true);
 770   case vmIntrinsics::_VectorStoreMaskedOp:
 771     return inline_vector_mem_masked_operation(/*is_store=*/true);
 772   case vmIntrinsics::_VectorGatherOp:
 773     return inline_vector_gather_scatter(/*is_scatter*/ false);
 774   case vmIntrinsics::_VectorScatterOp:
 775     return inline_vector_gather_scatter(/*is_scatter*/ true);
 776   case vmIntrinsics::_VectorReductionCoerced:
 777     return inline_vector_reduction();
 778   case vmIntrinsics::_VectorTest:
 779     return inline_vector_test();
 780   case vmIntrinsics::_VectorBlend:
 781     return inline_vector_blend();
 782   case vmIntrinsics::_VectorRearrange:
 783     return inline_vector_rearrange();
 784   case vmIntrinsics::_VectorSelectFrom:
 785     return inline_vector_select_from();
 786   case vmIntrinsics::_VectorCompare:
 787     return inline_vector_compare();
 788   case vmIntrinsics::_VectorBroadcastInt:
 789     return inline_vector_broadcast_int();
 790   case vmIntrinsics::_VectorConvert:
 791     return inline_vector_convert();
 792   case vmIntrinsics::_VectorInsert:
 793     return inline_vector_insert();
 794   case vmIntrinsics::_VectorExtract:
 795     return inline_vector_extract();
 796   case vmIntrinsics::_VectorCompressExpand:
 797     return inline_vector_compress_expand();
 798   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 799     return inline_vector_select_from_two_vectors();
 800   case vmIntrinsics::_IndexVector:
 801     return inline_index_vector();
 802   case vmIntrinsics::_IndexPartiallyInUpperRange:
 803     return inline_index_partially_in_upper_range();
 804 
 805   case vmIntrinsics::_getObjectSize:
 806     return inline_getObjectSize();
 807 
 808   case vmIntrinsics::_blackhole:
 809     return inline_blackhole();
 810 
 811   default:
 812     // If you get here, it may be that someone has added a new intrinsic
 813     // to the list in vmIntrinsics.hpp without implementing it here.
 814 #ifndef PRODUCT
 815     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 816       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 817                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 818     }
 819 #endif
 820     return false;
 821   }
 822 }
 823 
 824 Node* LibraryCallKit::try_to_predicate(int predicate) {
 825   if (!jvms()->has_method()) {
 826     // Root JVMState has a null method.
 827     assert(map()->memory()->Opcode() == Op_Parm, "");
 828     // Insert the memory aliasing node
 829     set_all_memory(reset_memory());
 830   }
 831   assert(merged_memory(), "");
 832 
 833   switch (intrinsic_id()) {
 834   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 835     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 836   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 837     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 839     return inline_electronicCodeBook_AESCrypt_predicate(false);
 840   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 841     return inline_electronicCodeBook_AESCrypt_predicate(true);
 842   case vmIntrinsics::_counterMode_AESCrypt:
 843     return inline_counterMode_AESCrypt_predicate();
 844   case vmIntrinsics::_digestBase_implCompressMB:
 845     return inline_digestBase_implCompressMB_predicate(predicate);
 846   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 847     return inline_galoisCounterMode_AESCrypt_predicate();
 848 
 849   default:
 850     // If you get here, it may be that someone has added a new intrinsic
 851     // to the list in vmIntrinsics.hpp without implementing it here.
 852 #ifndef PRODUCT
 853     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 854       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 855                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 856     }
 857 #endif
 858     Node* slow_ctl = control();
 859     set_control(top()); // No fast path intrinsic
 860     return slow_ctl;
 861   }
 862 }
 863 
 864 //------------------------------set_result-------------------------------
 865 // Helper function for finishing intrinsics.
 866 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 867   record_for_igvn(region);
 868   set_control(_gvn.transform(region));
 869   set_result( _gvn.transform(value));
 870   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 871 }
 872 
 873 //------------------------------generate_guard---------------------------
 874 // Helper function for generating guarded fast-slow graph structures.
 875 // The given 'test', if true, guards a slow path.  If the test fails
 876 // then a fast path can be taken.  (We generally hope it fails.)
 877 // In all cases, GraphKit::control() is updated to the fast path.
 878 // The returned value represents the control for the slow path.
 879 // The return value is never 'top'; it is either a valid control
 880 // or null if it is obvious that the slow path can never be taken.
 881 // Also, if region and the slow control are not null, the slow edge
 882 // is appended to the region.
 883 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 884   if (stopped()) {
 885     // Already short circuited.
 886     return nullptr;
 887   }
 888 
 889   // Build an if node and its projections.
 890   // If test is true we take the slow path, which we assume is uncommon.
 891   if (_gvn.type(test) == TypeInt::ZERO) {
 892     // The slow branch is never taken.  No need to build this guard.
 893     return nullptr;
 894   }
 895 
 896   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 897 
 898   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 899   if (if_slow == top()) {
 900     // The slow branch is never taken.  No need to build this guard.
 901     return nullptr;
 902   }
 903 
 904   if (region != nullptr)
 905     region->add_req(if_slow);
 906 
 907   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 908   set_control(if_fast);
 909 
 910   return if_slow;
 911 }
 912 
 913 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 914   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 915 }
 916 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 917   return generate_guard(test, region, PROB_FAIR);
 918 }
 919 
 920 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 921                                                      Node* *pos_index) {
 922   if (stopped())
 923     return nullptr;                // already stopped
 924   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 925     return nullptr;                // index is already adequately typed
 926   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 927   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 928   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 929   if (is_neg != nullptr && pos_index != nullptr) {
 930     // Emulate effect of Parse::adjust_map_after_if.
 931     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 932     (*pos_index) = _gvn.transform(ccast);
 933   }
 934   return is_neg;
 935 }
 936 
 937 // Make sure that 'position' is a valid limit index, in [0..length].
 938 // There are two equivalent plans for checking this:
 939 //   A. (offset + copyLength)  unsigned<=  arrayLength
 940 //   B. offset  <=  (arrayLength - copyLength)
 941 // We require that all of the values above, except for the sum and
 942 // difference, are already known to be non-negative.
 943 // Plan A is robust in the face of overflow, if offset and copyLength
 944 // are both hugely positive.
 945 //
 946 // Plan B is less direct and intuitive, but it does not overflow at
 947 // all, since the difference of two non-negatives is always
 948 // representable.  Whenever Java methods must perform the equivalent
 949 // check they generally use Plan B instead of Plan A.
 950 // For the moment we use Plan A.
 951 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 952                                                   Node* subseq_length,
 953                                                   Node* array_length,
 954                                                   RegionNode* region) {
 955   if (stopped())
 956     return nullptr;                // already stopped
 957   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 958   if (zero_offset && subseq_length->eqv_uncast(array_length))
 959     return nullptr;                // common case of whole-array copy
 960   Node* last = subseq_length;
 961   if (!zero_offset)             // last += offset
 962     last = _gvn.transform(new AddINode(last, offset));
 963   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 964   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 965   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 966   return is_over;
 967 }
 968 
 969 // Emit range checks for the given String.value byte array
 970 void LibraryCallKit::generate_string_range_check(Node* array,
 971                                                  Node* offset,
 972                                                  Node* count,
 973                                                  bool char_count,
 974                                                  bool halt_on_oob) {
 975   if (stopped()) {
 976     return; // already stopped
 977   }
 978   RegionNode* bailout = new RegionNode(1);
 979   record_for_igvn(bailout);
 980   if (char_count) {
 981     // Convert char count to byte count
 982     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 983   }
 984 
 985   // Offset and count must not be negative
 986   generate_negative_guard(offset, bailout);
 987   generate_negative_guard(count, bailout);
 988   // Offset + count must not exceed length of array
 989   generate_limit_guard(offset, count, load_array_length(array), bailout);
 990 
 991   if (bailout->req() > 1) {
 992     if (halt_on_oob) {
 993       bailout = _gvn.transform(bailout)->as_Region();
 994       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 995       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 996       C->root()->add_req(halt);
 997     } else {
 998       PreserveJVMState pjvms(this);
 999       set_control(_gvn.transform(bailout));
1000       uncommon_trap(Deoptimization::Reason_intrinsic,
1001                     Deoptimization::Action_maybe_recompile);
1002     }
1003   }
1004 }
1005 
1006 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1007                                             bool is_immutable) {
1008   ciKlass* thread_klass = env()->Thread_klass();
1009   const Type* thread_type
1010     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1011 
1012   Node* thread = _gvn.transform(new ThreadLocalNode());
1013   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1014   tls_output = thread;
1015 
1016   Node* thread_obj_handle
1017     = (is_immutable
1018       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1019         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1020       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1021   thread_obj_handle = _gvn.transform(thread_obj_handle);
1022 
1023   DecoratorSet decorators = IN_NATIVE;
1024   if (is_immutable) {
1025     decorators |= C2_IMMUTABLE_MEMORY;
1026   }
1027   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1028 }
1029 
1030 //--------------------------generate_current_thread--------------------
1031 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1032   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1033                                /*is_immutable*/false);
1034 }
1035 
1036 //--------------------------generate_virtual_thread--------------------
1037 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1039                                !C->method()->changes_current_thread());
1040 }
1041 
1042 //------------------------------make_string_method_node------------------------
1043 // Helper method for String intrinsic functions. This version is called with
1044 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1045 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1046 // containing the lengths of str1 and str2.
1047 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1048   Node* result = nullptr;
1049   switch (opcode) {
1050   case Op_StrIndexOf:
1051     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1052                                 str1_start, cnt1, str2_start, cnt2, ae);
1053     break;
1054   case Op_StrComp:
1055     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1056                              str1_start, cnt1, str2_start, cnt2, ae);
1057     break;
1058   case Op_StrEquals:
1059     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1060     // Use the constant length if there is one because optimized match rule may exist.
1061     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1062                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1063     break;
1064   default:
1065     ShouldNotReachHere();
1066     return nullptr;
1067   }
1068 
1069   // All these intrinsics have checks.
1070   C->set_has_split_ifs(true); // Has chance for split-if optimization
1071   clear_upper_avx();
1072 
1073   return _gvn.transform(result);
1074 }
1075 
1076 //------------------------------inline_string_compareTo------------------------
1077 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1078   Node* arg1 = argument(0);
1079   Node* arg2 = argument(1);
1080 
1081   arg1 = must_be_not_null(arg1, true);
1082   arg2 = must_be_not_null(arg2, true);
1083 
1084   // Get start addr and length of first argument
1085   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1086   Node* arg1_cnt    = load_array_length(arg1);
1087 
1088   // Get start addr and length of second argument
1089   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1090   Node* arg2_cnt    = load_array_length(arg2);
1091 
1092   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1093   set_result(result);
1094   return true;
1095 }
1096 
1097 //------------------------------inline_string_equals------------------------
1098 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1099   Node* arg1 = argument(0);
1100   Node* arg2 = argument(1);
1101 
1102   // paths (plus control) merge
1103   RegionNode* region = new RegionNode(3);
1104   Node* phi = new PhiNode(region, TypeInt::BOOL);
1105 
1106   if (!stopped()) {
1107 
1108     arg1 = must_be_not_null(arg1, true);
1109     arg2 = must_be_not_null(arg2, true);
1110 
1111     // Get start addr and length of first argument
1112     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1113     Node* arg1_cnt    = load_array_length(arg1);
1114 
1115     // Get start addr and length of second argument
1116     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1117     Node* arg2_cnt    = load_array_length(arg2);
1118 
1119     // Check for arg1_cnt != arg2_cnt
1120     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1121     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1122     Node* if_ne = generate_slow_guard(bol, nullptr);
1123     if (if_ne != nullptr) {
1124       phi->init_req(2, intcon(0));
1125       region->init_req(2, if_ne);
1126     }
1127 
1128     // Check for count == 0 is done by assembler code for StrEquals.
1129 
1130     if (!stopped()) {
1131       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1132       phi->init_req(1, equals);
1133       region->init_req(1, control());
1134     }
1135   }
1136 
1137   // post merge
1138   set_control(_gvn.transform(region));
1139   record_for_igvn(region);
1140 
1141   set_result(_gvn.transform(phi));
1142   return true;
1143 }
1144 
1145 //------------------------------inline_array_equals----------------------------
1146 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1147   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1148   Node* arg1 = argument(0);
1149   Node* arg2 = argument(1);
1150 
1151   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1152   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1153   clear_upper_avx();
1154 
1155   return true;
1156 }
1157 
1158 
1159 //------------------------------inline_countPositives------------------------------
1160 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1161 bool LibraryCallKit::inline_countPositives() {
1162   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1163     return false;
1164   }
1165 
1166   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1167   // no receiver since it is static method
1168   Node* ba         = argument(0);
1169   Node* offset     = argument(1);
1170   Node* len        = argument(2);
1171 
1172   if (VerifyIntrinsicChecks) {
1173     ba = must_be_not_null(ba, true);
1174     generate_string_range_check(ba, offset, len, false, true);
1175     if (stopped()) {
1176       return true;
1177     }
1178   }
1179 
1180   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1181   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1182   set_result(_gvn.transform(result));
1183   clear_upper_avx();
1184   return true;
1185 }
1186 
1187 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1188   Node* index = argument(0);
1189   Node* length = bt == T_INT ? argument(1) : argument(2);
1190   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1191     return false;
1192   }
1193 
1194   // check that length is positive
1195   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1196   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1197 
1198   {
1199     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1200     uncommon_trap(Deoptimization::Reason_intrinsic,
1201                   Deoptimization::Action_make_not_entrant);
1202   }
1203 
1204   if (stopped()) {
1205     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1206     return true;
1207   }
1208 
1209   // length is now known positive, add a cast node to make this explicit
1210   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1211   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1212       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1213       ConstraintCastNode::RegularDependency, bt);
1214   casted_length = _gvn.transform(casted_length);
1215   replace_in_map(length, casted_length);
1216   length = casted_length;
1217 
1218   // Use an unsigned comparison for the range check itself
1219   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1220   BoolTest::mask btest = BoolTest::lt;
1221   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1222   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1223   _gvn.set_type(rc, rc->Value(&_gvn));
1224   if (!rc_bool->is_Con()) {
1225     record_for_igvn(rc);
1226   }
1227   set_control(_gvn.transform(new IfTrueNode(rc)));
1228   {
1229     PreserveJVMState pjvms(this);
1230     set_control(_gvn.transform(new IfFalseNode(rc)));
1231     uncommon_trap(Deoptimization::Reason_range_check,
1232                   Deoptimization::Action_make_not_entrant);
1233   }
1234 
1235   if (stopped()) {
1236     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1237     return true;
1238   }
1239 
1240   // index is now known to be >= 0 and < length, cast it
1241   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1242       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1243       ConstraintCastNode::RegularDependency, bt);
1244   result = _gvn.transform(result);
1245   set_result(result);
1246   replace_in_map(index, result);
1247   return true;
1248 }
1249 
1250 //------------------------------inline_string_indexOf------------------------
1251 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1252   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1253     return false;
1254   }
1255   Node* src = argument(0);
1256   Node* tgt = argument(1);
1257 
1258   // Make the merge point
1259   RegionNode* result_rgn = new RegionNode(4);
1260   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1261 
1262   src = must_be_not_null(src, true);
1263   tgt = must_be_not_null(tgt, true);
1264 
1265   // Get start addr and length of source string
1266   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1267   Node* src_count = load_array_length(src);
1268 
1269   // Get start addr and length of substring
1270   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1271   Node* tgt_count = load_array_length(tgt);
1272 
1273   Node* result = nullptr;
1274   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1275 
1276   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1277     // Divide src size by 2 if String is UTF16 encoded
1278     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1279   }
1280   if (ae == StrIntrinsicNode::UU) {
1281     // Divide substring size by 2 if String is UTF16 encoded
1282     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1283   }
1284 
1285   if (call_opt_stub) {
1286     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1287                                    StubRoutines::_string_indexof_array[ae],
1288                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1289                                    src_count, tgt_start, tgt_count);
1290     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1291   } else {
1292     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1293                                result_rgn, result_phi, ae);
1294   }
1295   if (result != nullptr) {
1296     result_phi->init_req(3, result);
1297     result_rgn->init_req(3, control());
1298   }
1299   set_control(_gvn.transform(result_rgn));
1300   record_for_igvn(result_rgn);
1301   set_result(_gvn.transform(result_phi));
1302 
1303   return true;
1304 }
1305 
1306 //-----------------------------inline_string_indexOfI-----------------------
1307 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1308   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1309     return false;
1310   }
1311   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1312     return false;
1313   }
1314 
1315   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1316   Node* src         = argument(0); // byte[]
1317   Node* src_count   = argument(1); // char count
1318   Node* tgt         = argument(2); // byte[]
1319   Node* tgt_count   = argument(3); // char count
1320   Node* from_index  = argument(4); // char index
1321 
1322   src = must_be_not_null(src, true);
1323   tgt = must_be_not_null(tgt, true);
1324 
1325   // Multiply byte array index by 2 if String is UTF16 encoded
1326   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1327   src_count = _gvn.transform(new SubINode(src_count, from_index));
1328   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1329   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1330 
1331   // Range checks
1332   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1333   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1334   if (stopped()) {
1335     return true;
1336   }
1337 
1338   RegionNode* region = new RegionNode(5);
1339   Node* phi = new PhiNode(region, TypeInt::INT);
1340   Node* result = nullptr;
1341 
1342   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1343 
1344   if (call_opt_stub) {
1345     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1346                                    StubRoutines::_string_indexof_array[ae],
1347                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1348                                    src_count, tgt_start, tgt_count);
1349     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1350   } else {
1351     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1352                                region, phi, ae);
1353   }
1354   if (result != nullptr) {
1355     // The result is index relative to from_index if substring was found, -1 otherwise.
1356     // Generate code which will fold into cmove.
1357     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1358     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1359 
1360     Node* if_lt = generate_slow_guard(bol, nullptr);
1361     if (if_lt != nullptr) {
1362       // result == -1
1363       phi->init_req(3, result);
1364       region->init_req(3, if_lt);
1365     }
1366     if (!stopped()) {
1367       result = _gvn.transform(new AddINode(result, from_index));
1368       phi->init_req(4, result);
1369       region->init_req(4, control());
1370     }
1371   }
1372 
1373   set_control(_gvn.transform(region));
1374   record_for_igvn(region);
1375   set_result(_gvn.transform(phi));
1376   clear_upper_avx();
1377 
1378   return true;
1379 }
1380 
1381 // Create StrIndexOfNode with fast path checks
1382 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1383                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1384   // Check for substr count > string count
1385   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1386   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1387   Node* if_gt = generate_slow_guard(bol, nullptr);
1388   if (if_gt != nullptr) {
1389     phi->init_req(1, intcon(-1));
1390     region->init_req(1, if_gt);
1391   }
1392   if (!stopped()) {
1393     // Check for substr count == 0
1394     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1395     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1396     Node* if_zero = generate_slow_guard(bol, nullptr);
1397     if (if_zero != nullptr) {
1398       phi->init_req(2, intcon(0));
1399       region->init_req(2, if_zero);
1400     }
1401   }
1402   if (!stopped()) {
1403     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1404   }
1405   return nullptr;
1406 }
1407 
1408 //-----------------------------inline_string_indexOfChar-----------------------
1409 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1410   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1411     return false;
1412   }
1413   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1414     return false;
1415   }
1416   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1417   Node* src         = argument(0); // byte[]
1418   Node* int_ch      = argument(1);
1419   Node* from_index  = argument(2);
1420   Node* max         = argument(3);
1421 
1422   src = must_be_not_null(src, true);
1423 
1424   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1425   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1426   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1427 
1428   // Range checks
1429   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1430 
1431   // Check for int_ch >= 0
1432   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1433   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1434   {
1435     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1436     uncommon_trap(Deoptimization::Reason_intrinsic,
1437                   Deoptimization::Action_maybe_recompile);
1438   }
1439   if (stopped()) {
1440     return true;
1441   }
1442 
1443   RegionNode* region = new RegionNode(3);
1444   Node* phi = new PhiNode(region, TypeInt::INT);
1445 
1446   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1447   C->set_has_split_ifs(true); // Has chance for split-if optimization
1448   _gvn.transform(result);
1449 
1450   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1451   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1452 
1453   Node* if_lt = generate_slow_guard(bol, nullptr);
1454   if (if_lt != nullptr) {
1455     // result == -1
1456     phi->init_req(2, result);
1457     region->init_req(2, if_lt);
1458   }
1459   if (!stopped()) {
1460     result = _gvn.transform(new AddINode(result, from_index));
1461     phi->init_req(1, result);
1462     region->init_req(1, control());
1463   }
1464   set_control(_gvn.transform(region));
1465   record_for_igvn(region);
1466   set_result(_gvn.transform(phi));
1467   clear_upper_avx();
1468 
1469   return true;
1470 }
1471 //---------------------------inline_string_copy---------------------
1472 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1473 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1474 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1475 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1476 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1477 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 bool LibraryCallKit::inline_string_copy(bool compress) {
1479   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1480     return false;
1481   }
1482   int nargs = 5;  // 2 oops, 3 ints
1483   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1484 
1485   Node* src         = argument(0);
1486   Node* src_offset  = argument(1);
1487   Node* dst         = argument(2);
1488   Node* dst_offset  = argument(3);
1489   Node* length      = argument(4);
1490 
1491   // Check for allocation before we add nodes that would confuse
1492   // tightly_coupled_allocation()
1493   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1494 
1495   // Figure out the size and type of the elements we will be copying.
1496   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1497   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1498   if (src_type == nullptr || dst_type == nullptr) {
1499     return false;
1500   }
1501   BasicType src_elem = src_type->elem()->array_element_basic_type();
1502   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1503   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1504          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1505          "Unsupported array types for inline_string_copy");
1506 
1507   src = must_be_not_null(src, true);
1508   dst = must_be_not_null(dst, true);
1509 
1510   // Convert char[] offsets to byte[] offsets
1511   bool convert_src = (compress && src_elem == T_BYTE);
1512   bool convert_dst = (!compress && dst_elem == T_BYTE);
1513   if (convert_src) {
1514     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1515   } else if (convert_dst) {
1516     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1517   }
1518 
1519   // Range checks
1520   generate_string_range_check(src, src_offset, length, convert_src);
1521   generate_string_range_check(dst, dst_offset, length, convert_dst);
1522   if (stopped()) {
1523     return true;
1524   }
1525 
1526   Node* src_start = array_element_address(src, src_offset, src_elem);
1527   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1528   // 'src_start' points to src array + scaled offset
1529   // 'dst_start' points to dst array + scaled offset
1530   Node* count = nullptr;
1531   if (compress) {
1532     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1533   } else {
1534     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1535   }
1536 
1537   if (alloc != nullptr) {
1538     if (alloc->maybe_set_complete(&_gvn)) {
1539       // "You break it, you buy it."
1540       InitializeNode* init = alloc->initialization();
1541       assert(init->is_complete(), "we just did this");
1542       init->set_complete_with_arraycopy();
1543       assert(dst->is_CheckCastPP(), "sanity");
1544       assert(dst->in(0)->in(0) == init, "dest pinned");
1545     }
1546     // Do not let stores that initialize this object be reordered with
1547     // a subsequent store that would make this object accessible by
1548     // other threads.
1549     // Record what AllocateNode this StoreStore protects so that
1550     // escape analysis can go from the MemBarStoreStoreNode to the
1551     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1552     // based on the escape status of the AllocateNode.
1553     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1554   }
1555   if (compress) {
1556     set_result(_gvn.transform(count));
1557   }
1558   clear_upper_avx();
1559 
1560   return true;
1561 }
1562 
1563 #ifdef _LP64
1564 #define XTOP ,top() /*additional argument*/
1565 #else  //_LP64
1566 #define XTOP        /*no additional argument*/
1567 #endif //_LP64
1568 
1569 //------------------------inline_string_toBytesU--------------------------
1570 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1571 bool LibraryCallKit::inline_string_toBytesU() {
1572   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1573     return false;
1574   }
1575   // Get the arguments.
1576   Node* value     = argument(0);
1577   Node* offset    = argument(1);
1578   Node* length    = argument(2);
1579 
1580   Node* newcopy = nullptr;
1581 
1582   // Set the original stack and the reexecute bit for the interpreter to reexecute
1583   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1584   { PreserveReexecuteState preexecs(this);
1585     jvms()->set_should_reexecute(true);
1586 
1587     // Check if a null path was taken unconditionally.
1588     value = null_check(value);
1589 
1590     RegionNode* bailout = new RegionNode(1);
1591     record_for_igvn(bailout);
1592 
1593     // Range checks
1594     generate_negative_guard(offset, bailout);
1595     generate_negative_guard(length, bailout);
1596     generate_limit_guard(offset, length, load_array_length(value), bailout);
1597     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1598     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1599 
1600     if (bailout->req() > 1) {
1601       PreserveJVMState pjvms(this);
1602       set_control(_gvn.transform(bailout));
1603       uncommon_trap(Deoptimization::Reason_intrinsic,
1604                     Deoptimization::Action_maybe_recompile);
1605     }
1606     if (stopped()) {
1607       return true;
1608     }
1609 
1610     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1611     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1612     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1613     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1614     guarantee(alloc != nullptr, "created above");
1615 
1616     // Calculate starting addresses.
1617     Node* src_start = array_element_address(value, offset, T_CHAR);
1618     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1619 
1620     // Check if dst array address is aligned to HeapWordSize
1621     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1622     // If true, then check if src array address is aligned to HeapWordSize
1623     if (aligned) {
1624       const TypeInt* toffset = gvn().type(offset)->is_int();
1625       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1626                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1627     }
1628 
1629     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1630     const char* copyfunc_name = "arraycopy";
1631     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1632     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1633                       OptoRuntime::fast_arraycopy_Type(),
1634                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1635                       src_start, dst_start, ConvI2X(length) XTOP);
1636     // Do not let reads from the cloned object float above the arraycopy.
1637     if (alloc->maybe_set_complete(&_gvn)) {
1638       // "You break it, you buy it."
1639       InitializeNode* init = alloc->initialization();
1640       assert(init->is_complete(), "we just did this");
1641       init->set_complete_with_arraycopy();
1642       assert(newcopy->is_CheckCastPP(), "sanity");
1643       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1644     }
1645     // Do not let stores that initialize this object be reordered with
1646     // a subsequent store that would make this object accessible by
1647     // other threads.
1648     // Record what AllocateNode this StoreStore protects so that
1649     // escape analysis can go from the MemBarStoreStoreNode to the
1650     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1651     // based on the escape status of the AllocateNode.
1652     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1653   } // original reexecute is set back here
1654 
1655   C->set_has_split_ifs(true); // Has chance for split-if optimization
1656   if (!stopped()) {
1657     set_result(newcopy);
1658   }
1659   clear_upper_avx();
1660 
1661   return true;
1662 }
1663 
1664 //------------------------inline_string_getCharsU--------------------------
1665 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1666 bool LibraryCallKit::inline_string_getCharsU() {
1667   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1668     return false;
1669   }
1670 
1671   // Get the arguments.
1672   Node* src       = argument(0);
1673   Node* src_begin = argument(1);
1674   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1675   Node* dst       = argument(3);
1676   Node* dst_begin = argument(4);
1677 
1678   // Check for allocation before we add nodes that would confuse
1679   // tightly_coupled_allocation()
1680   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1681 
1682   // Check if a null path was taken unconditionally.
1683   src = null_check(src);
1684   dst = null_check(dst);
1685   if (stopped()) {
1686     return true;
1687   }
1688 
1689   // Get length and convert char[] offset to byte[] offset
1690   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1691   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1692 
1693   // Range checks
1694   generate_string_range_check(src, src_begin, length, true);
1695   generate_string_range_check(dst, dst_begin, length, false);
1696   if (stopped()) {
1697     return true;
1698   }
1699 
1700   if (!stopped()) {
1701     // Calculate starting addresses.
1702     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1703     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1704 
1705     // Check if array addresses are aligned to HeapWordSize
1706     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1707     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1708     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1709                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1710 
1711     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1712     const char* copyfunc_name = "arraycopy";
1713     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1714     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1715                       OptoRuntime::fast_arraycopy_Type(),
1716                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1717                       src_start, dst_start, ConvI2X(length) XTOP);
1718     // Do not let reads from the cloned object float above the arraycopy.
1719     if (alloc != nullptr) {
1720       if (alloc->maybe_set_complete(&_gvn)) {
1721         // "You break it, you buy it."
1722         InitializeNode* init = alloc->initialization();
1723         assert(init->is_complete(), "we just did this");
1724         init->set_complete_with_arraycopy();
1725         assert(dst->is_CheckCastPP(), "sanity");
1726         assert(dst->in(0)->in(0) == init, "dest pinned");
1727       }
1728       // Do not let stores that initialize this object be reordered with
1729       // a subsequent store that would make this object accessible by
1730       // other threads.
1731       // Record what AllocateNode this StoreStore protects so that
1732       // escape analysis can go from the MemBarStoreStoreNode to the
1733       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1734       // based on the escape status of the AllocateNode.
1735       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1736     } else {
1737       insert_mem_bar(Op_MemBarCPUOrder);
1738     }
1739   }
1740 
1741   C->set_has_split_ifs(true); // Has chance for split-if optimization
1742   return true;
1743 }
1744 
1745 //----------------------inline_string_char_access----------------------------
1746 // Store/Load char to/from byte[] array.
1747 // static void StringUTF16.putChar(byte[] val, int index, int c)
1748 // static char StringUTF16.getChar(byte[] val, int index)
1749 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1750   Node* value  = argument(0);
1751   Node* index  = argument(1);
1752   Node* ch = is_store ? argument(2) : nullptr;
1753 
1754   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1755   // correctly requires matched array shapes.
1756   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1757           "sanity: byte[] and char[] bases agree");
1758   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1759           "sanity: byte[] and char[] scales agree");
1760 
1761   // Bail when getChar over constants is requested: constant folding would
1762   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1763   // Java method would constant fold nicely instead.
1764   if (!is_store && value->is_Con() && index->is_Con()) {
1765     return false;
1766   }
1767 
1768   // Save state and restore on bailout
1769   SavedState old_state(this);
1770 
1771   value = must_be_not_null(value, true);
1772 
1773   Node* adr = array_element_address(value, index, T_CHAR);
1774   if (adr->is_top()) {
1775     return false;
1776   }
1777   old_state.discard();
1778   if (is_store) {
1779     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1780   } else {
1781     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);
1782     set_result(ch);
1783   }
1784   return true;
1785 }
1786 
1787 
1788 //------------------------------inline_math-----------------------------------
1789 // public static double Math.abs(double)
1790 // public static double Math.sqrt(double)
1791 // public static double Math.log(double)
1792 // public static double Math.log10(double)
1793 // public static double Math.round(double)
1794 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1795   Node* arg = argument(0);
1796   Node* n = nullptr;
1797   switch (id) {
1798   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1799   case vmIntrinsics::_dsqrt:
1800   case vmIntrinsics::_dsqrt_strict:
1801                               n = new SqrtDNode(C, control(),  arg);  break;
1802   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1803   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1804   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1805   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1806   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1807   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1808   default:  fatal_unexpected_iid(id);  break;
1809   }
1810   set_result(_gvn.transform(n));
1811   return true;
1812 }
1813 
1814 //------------------------------inline_math-----------------------------------
1815 // public static float Math.abs(float)
1816 // public static int Math.abs(int)
1817 // public static long Math.abs(long)
1818 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1819   Node* arg = argument(0);
1820   Node* n = nullptr;
1821   switch (id) {
1822   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1823   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1824   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1825   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1826   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1827   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1828   default:  fatal_unexpected_iid(id);  break;
1829   }
1830   set_result(_gvn.transform(n));
1831   return true;
1832 }
1833 
1834 //------------------------------runtime_math-----------------------------
1835 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1836   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1837          "must be (DD)D or (D)D type");
1838 
1839   // Inputs
1840   Node* a = argument(0);
1841   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1842 
1843   const TypePtr* no_memory_effects = nullptr;
1844   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1845                                  no_memory_effects,
1846                                  a, top(), b, b ? top() : nullptr);
1847   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1848 #ifdef ASSERT
1849   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1850   assert(value_top == top(), "second value must be top");
1851 #endif
1852 
1853   set_result(value);
1854   return true;
1855 }
1856 
1857 //------------------------------inline_math_pow-----------------------------
1858 bool LibraryCallKit::inline_math_pow() {
1859   Node* exp = argument(2);
1860   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1861   if (d != nullptr) {
1862     if (d->getd() == 2.0) {
1863       // Special case: pow(x, 2.0) => x * x
1864       Node* base = argument(0);
1865       set_result(_gvn.transform(new MulDNode(base, base)));
1866       return true;
1867     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1868       // Special case: pow(x, 0.5) => sqrt(x)
1869       Node* base = argument(0);
1870       Node* zero = _gvn.zerocon(T_DOUBLE);
1871 
1872       RegionNode* region = new RegionNode(3);
1873       Node* phi = new PhiNode(region, Type::DOUBLE);
1874 
1875       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1876       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1877       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1878       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1879       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1880 
1881       Node* if_pow = generate_slow_guard(test, nullptr);
1882       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1883       phi->init_req(1, value_sqrt);
1884       region->init_req(1, control());
1885 
1886       if (if_pow != nullptr) {
1887         set_control(if_pow);
1888         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1889                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1890         const TypePtr* no_memory_effects = nullptr;
1891         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1892                                        no_memory_effects, base, top(), exp, top());
1893         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1894 #ifdef ASSERT
1895         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1896         assert(value_top == top(), "second value must be top");
1897 #endif
1898         phi->init_req(2, value_pow);
1899         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1900       }
1901 
1902       C->set_has_split_ifs(true); // Has chance for split-if optimization
1903       set_control(_gvn.transform(region));
1904       record_for_igvn(region);
1905       set_result(_gvn.transform(phi));
1906 
1907       return true;
1908     }
1909   }
1910 
1911   return StubRoutines::dpow() != nullptr ?
1912     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1913     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1914 }
1915 
1916 //------------------------------inline_math_native-----------------------------
1917 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1918   switch (id) {
1919   case vmIntrinsics::_dsin:
1920     return StubRoutines::dsin() != nullptr ?
1921       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1922       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1923   case vmIntrinsics::_dcos:
1924     return StubRoutines::dcos() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1927   case vmIntrinsics::_dtan:
1928     return StubRoutines::dtan() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1930       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1931   case vmIntrinsics::_dsinh:
1932     return StubRoutines::dsinh() != nullptr ?
1933       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1934   case vmIntrinsics::_dtanh:
1935     return StubRoutines::dtanh() != nullptr ?
1936       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1937   case vmIntrinsics::_dcbrt:
1938     return StubRoutines::dcbrt() != nullptr ?
1939       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1940   case vmIntrinsics::_dexp:
1941     return StubRoutines::dexp() != nullptr ?
1942       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1943       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1944   case vmIntrinsics::_dlog:
1945     return StubRoutines::dlog() != nullptr ?
1946       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1947       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1948   case vmIntrinsics::_dlog10:
1949     return StubRoutines::dlog10() != nullptr ?
1950       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1951       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1952 
1953   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1954   case vmIntrinsics::_ceil:
1955   case vmIntrinsics::_floor:
1956   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1957 
1958   case vmIntrinsics::_dsqrt:
1959   case vmIntrinsics::_dsqrt_strict:
1960                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1961   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1962   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1963   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1964   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1965 
1966   case vmIntrinsics::_dpow:      return inline_math_pow();
1967   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1968   case vmIntrinsics::_fcopySign: return inline_math(id);
1969   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1970   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1971   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1972 
1973    // These intrinsics are not yet correctly implemented
1974   case vmIntrinsics::_datan2:
1975     return false;
1976 
1977   default:
1978     fatal_unexpected_iid(id);
1979     return false;
1980   }
1981 }
1982 
1983 //----------------------------inline_notify-----------------------------------*
1984 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1985   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1986   address func;
1987   if (id == vmIntrinsics::_notify) {
1988     func = OptoRuntime::monitor_notify_Java();
1989   } else {
1990     func = OptoRuntime::monitor_notifyAll_Java();
1991   }
1992   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1993   make_slow_call_ex(call, env()->Throwable_klass(), false);
1994   return true;
1995 }
1996 
1997 
1998 //----------------------------inline_min_max-----------------------------------
1999 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2000   Node* a = nullptr;
2001   Node* b = nullptr;
2002   Node* n = nullptr;
2003   switch (id) {
2004     case vmIntrinsics::_min:
2005     case vmIntrinsics::_max:
2006     case vmIntrinsics::_minF:
2007     case vmIntrinsics::_maxF:
2008     case vmIntrinsics::_minF_strict:
2009     case vmIntrinsics::_maxF_strict:
2010     case vmIntrinsics::_min_strict:
2011     case vmIntrinsics::_max_strict:
2012       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2013       a = argument(0);
2014       b = argument(1);
2015       break;
2016     case vmIntrinsics::_minD:
2017     case vmIntrinsics::_maxD:
2018     case vmIntrinsics::_minD_strict:
2019     case vmIntrinsics::_maxD_strict:
2020       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2021       a = argument(0);
2022       b = argument(2);
2023       break;
2024     case vmIntrinsics::_minL:
2025     case vmIntrinsics::_maxL:
2026       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2027       a = argument(0);
2028       b = argument(2);
2029       break;
2030     default:
2031       fatal_unexpected_iid(id);
2032       break;
2033   }
2034 
2035   switch (id) {
2036     case vmIntrinsics::_min:
2037     case vmIntrinsics::_min_strict:
2038       n = new MinINode(a, b);
2039       break;
2040     case vmIntrinsics::_max:
2041     case vmIntrinsics::_max_strict:
2042       n = new MaxINode(a, b);
2043       break;
2044     case vmIntrinsics::_minF:
2045     case vmIntrinsics::_minF_strict:
2046       n = new MinFNode(a, b);
2047       break;
2048     case vmIntrinsics::_maxF:
2049     case vmIntrinsics::_maxF_strict:
2050       n = new MaxFNode(a, b);
2051       break;
2052     case vmIntrinsics::_minD:
2053     case vmIntrinsics::_minD_strict:
2054       n = new MinDNode(a, b);
2055       break;
2056     case vmIntrinsics::_maxD:
2057     case vmIntrinsics::_maxD_strict:
2058       n = new MaxDNode(a, b);
2059       break;
2060     case vmIntrinsics::_minL:
2061       n = new MinLNode(_gvn.C, a, b);
2062       break;
2063     case vmIntrinsics::_maxL:
2064       n = new MaxLNode(_gvn.C, a, b);
2065       break;
2066     default:
2067       fatal_unexpected_iid(id);
2068       break;
2069   }
2070 
2071   set_result(_gvn.transform(n));
2072   return true;
2073 }
2074 
2075 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2076   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2077                                    env()->ArithmeticException_instance())) {
2078     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2079     // so let's bail out intrinsic rather than risking deopting again.
2080     return false;
2081   }
2082 
2083   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2084   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2085   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2086   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2087 
2088   {
2089     PreserveJVMState pjvms(this);
2090     PreserveReexecuteState preexecs(this);
2091     jvms()->set_should_reexecute(true);
2092 
2093     set_control(slow_path);
2094     set_i_o(i_o());
2095 
2096     builtin_throw(Deoptimization::Reason_intrinsic,
2097                   env()->ArithmeticException_instance(),
2098                   /*allow_too_many_traps*/ false);
2099   }
2100 
2101   set_control(fast_path);
2102   set_result(math);
2103   return true;
2104 }
2105 
2106 template <typename OverflowOp>
2107 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2108   typedef typename OverflowOp::MathOp MathOp;
2109 
2110   MathOp* mathOp = new MathOp(arg1, arg2);
2111   Node* operation = _gvn.transform( mathOp );
2112   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2113   return inline_math_mathExact(operation, ofcheck);
2114 }
2115 
2116 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2117   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2118 }
2119 
2120 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2121   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2125   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2129   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_negateExactI() {
2133   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_negateExactL() {
2137   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2138 }
2139 
2140 bool LibraryCallKit::inline_math_multiplyExactI() {
2141   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2142 }
2143 
2144 bool LibraryCallKit::inline_math_multiplyExactL() {
2145   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2146 }
2147 
2148 bool LibraryCallKit::inline_math_multiplyHigh() {
2149   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2150   return true;
2151 }
2152 
2153 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2154   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2155   return true;
2156 }
2157 
2158 inline int
2159 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2160   const TypePtr* base_type = TypePtr::NULL_PTR;
2161   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2162   if (base_type == nullptr) {
2163     // Unknown type.
2164     return Type::AnyPtr;
2165   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2166     // Since this is a null+long form, we have to switch to a rawptr.
2167     base   = _gvn.transform(new CastX2PNode(offset));
2168     offset = MakeConX(0);
2169     return Type::RawPtr;
2170   } else if (base_type->base() == Type::RawPtr) {
2171     return Type::RawPtr;
2172   } else if (base_type->isa_oopptr()) {
2173     // Base is never null => always a heap address.
2174     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2175       return Type::OopPtr;
2176     }
2177     // Offset is small => always a heap address.
2178     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2179     if (offset_type != nullptr &&
2180         base_type->offset() == 0 &&     // (should always be?)
2181         offset_type->_lo >= 0 &&
2182         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2183       return Type::OopPtr;
2184     } else if (type == T_OBJECT) {
2185       // off heap access to an oop doesn't make any sense. Has to be on
2186       // heap.
2187       return Type::OopPtr;
2188     }
2189     // Otherwise, it might either be oop+off or null+addr.
2190     return Type::AnyPtr;
2191   } else {
2192     // No information:
2193     return Type::AnyPtr;
2194   }
2195 }
2196 
2197 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2198   Node* uncasted_base = base;
2199   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2200   if (kind == Type::RawPtr) {
2201     return basic_plus_adr(top(), uncasted_base, offset);
2202   } else if (kind == Type::AnyPtr) {
2203     assert(base == uncasted_base, "unexpected base change");
2204     if (can_cast) {
2205       if (!_gvn.type(base)->speculative_maybe_null() &&
2206           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2207         // According to profiling, this access is always on
2208         // heap. Casting the base to not null and thus avoiding membars
2209         // around the access should allow better optimizations
2210         Node* null_ctl = top();
2211         base = null_check_oop(base, &null_ctl, true, true, true);
2212         assert(null_ctl->is_top(), "no null control here");
2213         return basic_plus_adr(base, offset);
2214       } else if (_gvn.type(base)->speculative_always_null() &&
2215                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2216         // According to profiling, this access is always off
2217         // heap.
2218         base = null_assert(base);
2219         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2220         offset = MakeConX(0);
2221         return basic_plus_adr(top(), raw_base, offset);
2222       }
2223     }
2224     // We don't know if it's an on heap or off heap access. Fall back
2225     // to raw memory access.
2226     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2227     return basic_plus_adr(top(), raw, offset);
2228   } else {
2229     assert(base == uncasted_base, "unexpected base change");
2230     // We know it's an on heap access so base can't be null
2231     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2232       base = must_be_not_null(base, true);
2233     }
2234     return basic_plus_adr(base, offset);
2235   }
2236 }
2237 
2238 //--------------------------inline_number_methods-----------------------------
2239 // inline int     Integer.numberOfLeadingZeros(int)
2240 // inline int        Long.numberOfLeadingZeros(long)
2241 //
2242 // inline int     Integer.numberOfTrailingZeros(int)
2243 // inline int        Long.numberOfTrailingZeros(long)
2244 //
2245 // inline int     Integer.bitCount(int)
2246 // inline int        Long.bitCount(long)
2247 //
2248 // inline char  Character.reverseBytes(char)
2249 // inline short     Short.reverseBytes(short)
2250 // inline int     Integer.reverseBytes(int)
2251 // inline long       Long.reverseBytes(long)
2252 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2253   Node* arg = argument(0);
2254   Node* n = nullptr;
2255   switch (id) {
2256   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2257   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2258   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2259   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2260   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2261   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2262   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2263   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2264   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2265   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2266   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2267   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2268   default:  fatal_unexpected_iid(id);  break;
2269   }
2270   set_result(_gvn.transform(n));
2271   return true;
2272 }
2273 
2274 //--------------------------inline_bitshuffle_methods-----------------------------
2275 // inline int Integer.compress(int, int)
2276 // inline int Integer.expand(int, int)
2277 // inline long Long.compress(long, long)
2278 // inline long Long.expand(long, long)
2279 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2280   Node* n = nullptr;
2281   switch (id) {
2282     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2283     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2284     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2285     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2286     default:  fatal_unexpected_iid(id);  break;
2287   }
2288   set_result(_gvn.transform(n));
2289   return true;
2290 }
2291 
2292 //--------------------------inline_number_methods-----------------------------
2293 // inline int Integer.compareUnsigned(int, int)
2294 // inline int    Long.compareUnsigned(long, long)
2295 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2296   Node* arg1 = argument(0);
2297   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2298   Node* n = nullptr;
2299   switch (id) {
2300     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2301     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2302     default:  fatal_unexpected_iid(id);  break;
2303   }
2304   set_result(_gvn.transform(n));
2305   return true;
2306 }
2307 
2308 //--------------------------inline_unsigned_divmod_methods-----------------------------
2309 // inline int Integer.divideUnsigned(int, int)
2310 // inline int Integer.remainderUnsigned(int, int)
2311 // inline long Long.divideUnsigned(long, long)
2312 // inline long Long.remainderUnsigned(long, long)
2313 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2314   Node* n = nullptr;
2315   switch (id) {
2316     case vmIntrinsics::_divideUnsigned_i: {
2317       zero_check_int(argument(1));
2318       // Compile-time detect of null-exception
2319       if (stopped()) {
2320         return true; // keep the graph constructed so far
2321       }
2322       n = new UDivINode(control(), argument(0), argument(1));
2323       break;
2324     }
2325     case vmIntrinsics::_divideUnsigned_l: {
2326       zero_check_long(argument(2));
2327       // Compile-time detect of null-exception
2328       if (stopped()) {
2329         return true; // keep the graph constructed so far
2330       }
2331       n = new UDivLNode(control(), argument(0), argument(2));
2332       break;
2333     }
2334     case vmIntrinsics::_remainderUnsigned_i: {
2335       zero_check_int(argument(1));
2336       // Compile-time detect of null-exception
2337       if (stopped()) {
2338         return true; // keep the graph constructed so far
2339       }
2340       n = new UModINode(control(), argument(0), argument(1));
2341       break;
2342     }
2343     case vmIntrinsics::_remainderUnsigned_l: {
2344       zero_check_long(argument(2));
2345       // Compile-time detect of null-exception
2346       if (stopped()) {
2347         return true; // keep the graph constructed so far
2348       }
2349       n = new UModLNode(control(), argument(0), argument(2));
2350       break;
2351     }
2352     default:  fatal_unexpected_iid(id);  break;
2353   }
2354   set_result(_gvn.transform(n));
2355   return true;
2356 }
2357 
2358 //----------------------------inline_unsafe_access----------------------------
2359 
2360 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2361   // Attempt to infer a sharper value type from the offset and base type.
2362   ciKlass* sharpened_klass = nullptr;
2363   bool null_free = false;
2364 
2365   // See if it is an instance field, with an object type.
2366   if (alias_type->field() != nullptr) {
2367     if (alias_type->field()->type()->is_klass()) {
2368       sharpened_klass = alias_type->field()->type()->as_klass();
2369       null_free = alias_type->field()->is_null_free();
2370     }
2371   }
2372 
2373   const TypeOopPtr* result = nullptr;
2374   // See if it is a narrow oop array.
2375   if (adr_type->isa_aryptr()) {
2376     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2377       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2378       null_free = adr_type->is_aryptr()->is_null_free();
2379       if (elem_type != nullptr && elem_type->is_loaded()) {
2380         // Sharpen the value type.
2381         result = elem_type;
2382       }
2383     }
2384   }
2385 
2386   // The sharpened class might be unloaded if there is no class loader
2387   // contraint in place.
2388   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2389     // Sharpen the value type.
2390     result = TypeOopPtr::make_from_klass(sharpened_klass);
2391     if (null_free) {
2392       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2393     }
2394   }
2395   if (result != nullptr) {
2396 #ifndef PRODUCT
2397     if (C->print_intrinsics() || C->print_inlining()) {
2398       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2399       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2400     }
2401 #endif
2402   }
2403   return result;
2404 }
2405 
2406 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2407   switch (kind) {
2408       case Relaxed:
2409         return MO_UNORDERED;
2410       case Opaque:
2411         return MO_RELAXED;
2412       case Acquire:
2413         return MO_ACQUIRE;
2414       case Release:
2415         return MO_RELEASE;
2416       case Volatile:
2417         return MO_SEQ_CST;
2418       default:
2419         ShouldNotReachHere();
2420         return 0;
2421   }
2422 }
2423 
2424 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2425   _kit(kit),
2426   _sp(kit->sp()),
2427   _jvms(kit->jvms()),
2428   _map(kit->clone_map()),
2429   _discarded(false)
2430 {
2431   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2432     Node* out = kit->control()->fast_out(i);
2433     if (out->is_CFG()) {
2434       _ctrl_succ.push(out);
2435     }
2436   }
2437 }
2438 
2439 LibraryCallKit::SavedState::~SavedState() {
2440   if (_discarded) {
2441     _kit->destruct_map_clone(_map);
2442     return;
2443   }
2444   _kit->jvms()->set_map(_map);
2445   _kit->jvms()->set_sp(_sp);
2446   _map->set_jvms(_kit->jvms());
2447   _kit->set_map(_map);
2448   _kit->set_sp(_sp);
2449   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2450     Node* out = _kit->control()->fast_out(i);
2451     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2452       _kit->_gvn.hash_delete(out);
2453       out->set_req(0, _kit->C->top());
2454       _kit->C->record_for_igvn(out);
2455       --i; --imax;
2456       _kit->_gvn.hash_find_insert(out);
2457     }
2458   }
2459 }
2460 
2461 void LibraryCallKit::SavedState::discard() {
2462   _discarded = true;
2463 }
2464 
2465 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2466   if (callee()->is_static())  return false;  // caller must have the capability!
2467   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2468   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2469   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2470   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2471 
2472   if (is_reference_type(type)) {
2473     decorators |= ON_UNKNOWN_OOP_REF;
2474   }
2475 
2476   if (unaligned) {
2477     decorators |= C2_UNALIGNED;
2478   }
2479 
2480 #ifndef PRODUCT
2481   {
2482     ResourceMark rm;
2483     // Check the signatures.
2484     ciSignature* sig = callee()->signature();
2485 #ifdef ASSERT
2486     if (!is_store) {
2487       // Object getReference(Object base, int/long offset), etc.
2488       BasicType rtype = sig->return_type()->basic_type();
2489       assert(rtype == type, "getter must return the expected value");
2490       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2491       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2492       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2493     } else {
2494       // void putReference(Object base, int/long offset, Object x), etc.
2495       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2496       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2497       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2498       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2499       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2500       assert(vtype == type, "putter must accept the expected value");
2501     }
2502 #endif // ASSERT
2503  }
2504 #endif //PRODUCT
2505 
2506   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2507 
2508   Node* receiver = argument(0);  // type: oop
2509 
2510   // Build address expression.
2511   Node* heap_base_oop = top();
2512 
2513   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2514   Node* base = argument(1);  // type: oop
2515   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2516   Node* offset = argument(2);  // type: long
2517   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2518   // to be plain byte offsets, which are also the same as those accepted
2519   // by oopDesc::field_addr.
2520   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2521          "fieldOffset must be byte-scaled");
2522 
2523   ciInlineKlass* inline_klass = nullptr;
2524   if (is_flat) {
2525     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2526     if (cls == nullptr || cls->const_oop() == nullptr) {
2527       return false;
2528     }
2529     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2530     if (!mirror_type->is_inlinetype()) {
2531       return false;
2532     }
2533     inline_klass = mirror_type->as_inline_klass();
2534   }
2535 
2536   if (base->is_InlineType()) {
2537     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2538     InlineTypeNode* vt = base->as_InlineType();
2539     if (offset->is_Con()) {
2540       long off = find_long_con(offset, 0);
2541       ciInlineKlass* vk = vt->type()->inline_klass();
2542       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2543         return false;
2544       }
2545 
2546       ciField* field = vk->get_non_flat_field_by_offset(off);
2547       if (field != nullptr) {
2548         BasicType bt = type2field[field->type()->basic_type()];
2549         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2550           bt = T_OBJECT;
2551         }
2552         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2553           Node* value = vt->field_value_by_offset(off, false);
2554           if (value->is_InlineType()) {
2555             value = value->as_InlineType()->adjust_scalarization_depth(this);
2556           }
2557           set_result(value);
2558           return true;
2559         }
2560       }
2561     }
2562     {
2563       // Re-execute the unsafe access if allocation triggers deoptimization.
2564       PreserveReexecuteState preexecs(this);
2565       jvms()->set_should_reexecute(true);
2566       vt = vt->buffer(this);
2567     }
2568     base = vt->get_oop();
2569   }
2570 
2571   // 32-bit machines ignore the high half!
2572   offset = ConvL2X(offset);
2573 
2574   // Save state and restore on bailout
2575   SavedState old_state(this);
2576 
2577   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2578   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2579 
2580   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2581     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2582       decorators |= IN_NATIVE; // off-heap primitive access
2583     } else {
2584       return false; // off-heap oop accesses are not supported
2585     }
2586   } else {
2587     heap_base_oop = base; // on-heap or mixed access
2588   }
2589 
2590   // Can base be null? Otherwise, always on-heap access.
2591   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2592 
2593   if (!can_access_non_heap) {
2594     decorators |= IN_HEAP;
2595   }
2596 
2597   Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2598 
2599   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2600   if (adr_type == TypePtr::NULL_PTR) {
2601     return false; // off-heap access with zero address
2602   }
2603 
2604   // Try to categorize the address.
2605   Compile::AliasType* alias_type = C->alias_type(adr_type);
2606   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2607 
2608   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2609       alias_type->adr_type() == TypeAryPtr::RANGE) {
2610     return false; // not supported
2611   }
2612 
2613   bool mismatched = false;
2614   BasicType bt = T_ILLEGAL;
2615   ciField* field = nullptr;
2616   if (adr_type->isa_instptr()) {
2617     const TypeInstPtr* instptr = adr_type->is_instptr();
2618     ciInstanceKlass* k = instptr->instance_klass();
2619     int off = instptr->offset();
2620     if (instptr->const_oop() != nullptr &&
2621         k == ciEnv::current()->Class_klass() &&
2622         instptr->offset() >= (k->size_helper() * wordSize)) {
2623       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2624       field = k->get_field_by_offset(off, true);
2625     } else {
2626       field = k->get_non_flat_field_by_offset(off);
2627     }
2628     if (field != nullptr) {
2629       bt = type2field[field->type()->basic_type()];
2630     }
2631     if (bt != alias_type->basic_type()) {
2632       // Type mismatch. Is it an access to a nested flat field?
2633       field = k->get_field_by_offset(off, false);
2634       if (field != nullptr) {
2635         bt = type2field[field->type()->basic_type()];
2636       }
2637     }
2638     assert(bt == alias_type->basic_type() || is_flat, "should match");
2639   } else {
2640     bt = alias_type->basic_type();
2641   }
2642 
2643   if (bt != T_ILLEGAL) {
2644     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2645     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2646       // Alias type doesn't differentiate between byte[] and boolean[]).
2647       // Use address type to get the element type.
2648       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2649     }
2650     if (is_reference_type(bt, true)) {
2651       // accessing an array field with getReference is not a mismatch
2652       bt = T_OBJECT;
2653     }
2654     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2655       // Don't intrinsify mismatched object accesses
2656       return false;
2657     }
2658     mismatched = (bt != type);
2659   } else if (alias_type->adr_type()->isa_oopptr()) {
2660     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2661   }
2662 
2663   if (is_flat) {
2664     if (adr_type->isa_instptr()) {
2665       if (field == nullptr || field->type() != inline_klass) {
2666         mismatched = true;
2667       }
2668     } else if (adr_type->isa_aryptr()) {
2669       const Type* elem = adr_type->is_aryptr()->elem();
2670       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2671         mismatched = true;
2672       }
2673     } else {
2674       mismatched = true;
2675     }
2676     if (is_store) {
2677       const Type* val_t = _gvn.type(val);
2678       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2679         return false;
2680       }
2681     }
2682   }
2683 
2684   old_state.discard();
2685   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2686 
2687   if (mismatched) {
2688     decorators |= C2_MISMATCHED;
2689   }
2690 
2691   // First guess at the value type.
2692   const Type *value_type = Type::get_const_basic_type(type);
2693 
2694   // Figure out the memory ordering.
2695   decorators |= mo_decorator_for_access_kind(kind);
2696 
2697   if (!is_store) {
2698     if (type == T_OBJECT && !is_flat) {
2699       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2700       if (tjp != nullptr) {
2701         value_type = tjp;
2702       }
2703     }
2704   }
2705 
2706   receiver = null_check(receiver);
2707   if (stopped()) {
2708     return true;
2709   }
2710   // Heap pointers get a null-check from the interpreter,
2711   // as a courtesy.  However, this is not guaranteed by Unsafe,
2712   // and it is not possible to fully distinguish unintended nulls
2713   // from intended ones in this API.
2714 
2715   if (!is_store) {
2716     Node* p = nullptr;
2717     // Try to constant fold a load from a constant field
2718 
2719     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2720       // final or stable field
2721       p = make_constant_from_field(field, heap_base_oop);
2722     }
2723 
2724     if (p == nullptr) { // Could not constant fold the load
2725       if (is_flat) {
2726         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2727       } else {
2728         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2729         const TypeOopPtr* ptr = value_type->make_oopptr();
2730         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2731           // Load a non-flattened inline type from memory
2732           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2733         }
2734       }
2735       // Normalize the value returned by getBoolean in the following cases
2736       if (type == T_BOOLEAN &&
2737           (mismatched ||
2738            heap_base_oop == top() ||                  // - heap_base_oop is null or
2739            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2740                                                       //   and the unsafe access is made to large offset
2741                                                       //   (i.e., larger than the maximum offset necessary for any
2742                                                       //   field access)
2743             ) {
2744           IdealKit ideal = IdealKit(this);
2745 #define __ ideal.
2746           IdealVariable normalized_result(ideal);
2747           __ declarations_done();
2748           __ set(normalized_result, p);
2749           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2750           __ set(normalized_result, ideal.ConI(1));
2751           ideal.end_if();
2752           final_sync(ideal);
2753           p = __ value(normalized_result);
2754 #undef __
2755       }
2756     }
2757     if (type == T_ADDRESS) {
2758       p = gvn().transform(new CastP2XNode(nullptr, p));
2759       p = ConvX2UL(p);
2760     }
2761     // The load node has the control of the preceding MemBarCPUOrder.  All
2762     // following nodes will have the control of the MemBarCPUOrder inserted at
2763     // the end of this method.  So, pushing the load onto the stack at a later
2764     // point is fine.
2765     set_result(p);
2766   } else {
2767     if (bt == T_ADDRESS) {
2768       // Repackage the long as a pointer.
2769       val = ConvL2X(val);
2770       val = gvn().transform(new CastX2PNode(val));
2771     }
2772     if (is_flat) {
2773       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2774     } else {
2775       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2776     }
2777   }
2778 
2779   return true;
2780 }
2781 
2782 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2783 #ifdef ASSERT
2784   {
2785     ResourceMark rm;
2786     // Check the signatures.
2787     ciSignature* sig = callee()->signature();
2788     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2789     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2790     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2791     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2792     if (is_store) {
2793       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2794       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2795       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2796     } else {
2797       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2798       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2799     }
2800  }
2801 #endif // ASSERT
2802 
2803   assert(kind == Relaxed, "Only plain accesses for now");
2804   if (callee()->is_static()) {
2805     // caller must have the capability!
2806     return false;
2807   }
2808   C->set_has_unsafe_access(true);
2809 
2810   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2811   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2812     // parameter valueType is not a constant
2813     return false;
2814   }
2815   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2816   if (!mirror_type->is_inlinetype()) {
2817     // Dead code
2818     return false;
2819   }
2820   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2821 
2822   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2823   if (layout_type == nullptr || !layout_type->is_con()) {
2824     // parameter layoutKind is not a constant
2825     return false;
2826   }
2827   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2828          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2829          "invalid layoutKind %d", layout_type->get_con());
2830   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2831   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2832          layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2833          "unexpected layoutKind %d", layout_type->get_con());
2834 
2835   null_check(argument(0));
2836   if (stopped()) {
2837     return true;
2838   }
2839 
2840   Node* base = must_be_not_null(argument(1), true);
2841   Node* offset = argument(2);
2842   const Type* base_type = _gvn.type(base);
2843 
2844   Node* ptr;
2845   bool immutable_memory = false;
2846   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2847   if (base_type->isa_instptr()) {
2848     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2849     if (offset_type == nullptr || !offset_type->is_con()) {
2850       // Offset into a non-array should be a constant
2851       decorators |= C2_MISMATCHED;
2852     } else {
2853       int offset_con = checked_cast<int>(offset_type->get_con());
2854       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2855       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2856       if (field == nullptr) {
2857         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2858         decorators |= C2_MISMATCHED;
2859       } else {
2860         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2861                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2862         immutable_memory = field->is_strict() && field->is_final();
2863 
2864         if (base->is_InlineType()) {
2865           assert(!is_store, "Cannot store into a non-larval value object");
2866           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2867           return true;
2868         }
2869       }
2870     }
2871 
2872     if (base->is_InlineType()) {
2873       assert(!is_store, "Cannot store into a non-larval value object");
2874       base = base->as_InlineType()->buffer(this, true);
2875     }
2876     ptr = basic_plus_adr(base, ConvL2X(offset));
2877   } else if (base_type->isa_aryptr()) {
2878     decorators |= IS_ARRAY;
2879     if (layout == LayoutKind::REFERENCE) {
2880       if (!base_type->is_aryptr()->is_not_flat()) {
2881         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2882         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2883         replace_in_map(base, new_base);
2884         base = new_base;
2885       }
2886       ptr = basic_plus_adr(base, ConvL2X(offset));
2887     } else {
2888       if (UseArrayFlattening) {
2889         // Flat array must have an exact type
2890         bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2891         bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2892         Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2893         replace_in_map(base, new_base);
2894         base = new_base;
2895         ptr = basic_plus_adr(base, ConvL2X(offset));
2896         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2897         if (ptr_type->field_offset().get() != 0) {
2898           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2899         }
2900       } else {
2901         uncommon_trap(Deoptimization::Reason_intrinsic,
2902                       Deoptimization::Action_none);
2903         return true;
2904       }
2905     }
2906   } else {
2907     decorators |= C2_MISMATCHED;
2908     ptr = basic_plus_adr(base, ConvL2X(offset));
2909   }
2910 
2911   if (is_store) {
2912     Node* value = argument(6);
2913     const Type* value_type = _gvn.type(value);
2914     if (!value_type->is_inlinetypeptr()) {
2915       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2916       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2917       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2918       replace_in_map(value, new_value);
2919       value = new_value;
2920     }
2921 
2922     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2923     if (layout == LayoutKind::REFERENCE) {
2924       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2925       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2926     } else {
2927       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2928       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2929       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2930     }
2931 
2932     return true;
2933   } else {
2934     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2935     InlineTypeNode* result;
2936     if (layout == LayoutKind::REFERENCE) {
2937       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2938       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2939       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2940     } else {
2941       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2942       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2943       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2944     }
2945 
2946     set_result(result);
2947     return true;
2948   }
2949 }
2950 
2951 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2952   Node* receiver = argument(0);
2953   Node* value = argument(1);
2954 
2955   const Type* type = gvn().type(value);
2956   if (!type->is_inlinetypeptr()) {
2957     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2958     return false;
2959   }
2960 
2961   null_check(receiver);
2962   if (stopped()) {
2963     return true;
2964   }
2965 
2966   value = null_check(value);
2967   if (stopped()) {
2968     return true;
2969   }
2970 
2971   ciInlineKlass* vk = type->inline_klass();
2972   Node* klass = makecon(TypeKlassPtr::make(vk));
2973   Node* obj = new_instance(klass);
2974   AllocateNode::Ideal_allocation(obj)->_larval = true;
2975 
2976   assert(value->is_InlineType(), "must be an InlineTypeNode");
2977   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2978   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2979 
2980   set_result(obj);
2981   return true;
2982 }
2983 
2984 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2985   Node* receiver = argument(0);
2986   Node* buffer = argument(1);
2987 
2988   const Type* type = gvn().type(buffer);
2989   if (!type->is_inlinetypeptr()) {
2990     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2991     return false;
2992   }
2993 
2994   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2995   if (alloc == nullptr) {
2996     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2997     return false;
2998   }
2999 
3000   null_check(receiver);
3001   if (stopped()) {
3002     return true;
3003   }
3004 
3005   // Unset the larval bit in the object header
3006   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3007   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3008   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3009 
3010   // We must ensure that the buffer is properly published
3011   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3012   assert(!type->maybe_null(), "result of an allocation should not be null");
3013   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3014   return true;
3015 }
3016 
3017 //----------------------------inline_unsafe_load_store----------------------------
3018 // This method serves a couple of different customers (depending on LoadStoreKind):
3019 //
3020 // LS_cmp_swap:
3021 //
3022 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3023 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
3024 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
3025 //
3026 // LS_cmp_swap_weak:
3027 //
3028 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
3029 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
3030 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3031 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3032 //
3033 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
3034 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
3035 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
3036 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
3037 //
3038 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
3039 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
3040 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
3041 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
3042 //
3043 // LS_cmp_exchange:
3044 //
3045 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
3046 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
3047 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
3048 //
3049 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
3050 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
3051 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
3052 //
3053 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3054 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3055 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3056 //
3057 // LS_get_add:
3058 //
3059 //   int  getAndAddInt( Object o, long offset, int  delta)
3060 //   long getAndAddLong(Object o, long offset, long delta)
3061 //
3062 // LS_get_set:
3063 //
3064 //   int    getAndSet(Object o, long offset, int    newValue)
3065 //   long   getAndSet(Object o, long offset, long   newValue)
3066 //   Object getAndSet(Object o, long offset, Object newValue)
3067 //
3068 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3069   // This basic scheme here is the same as inline_unsafe_access, but
3070   // differs in enough details that combining them would make the code
3071   // overly confusing.  (This is a true fact! I originally combined
3072   // them, but even I was confused by it!) As much code/comments as
3073   // possible are retained from inline_unsafe_access though to make
3074   // the correspondences clearer. - dl
3075 
3076   if (callee()->is_static())  return false;  // caller must have the capability!
3077 
3078   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3079   decorators |= mo_decorator_for_access_kind(access_kind);
3080 
3081 #ifndef PRODUCT
3082   BasicType rtype;
3083   {
3084     ResourceMark rm;
3085     // Check the signatures.
3086     ciSignature* sig = callee()->signature();
3087     rtype = sig->return_type()->basic_type();
3088     switch(kind) {
3089       case LS_get_add:
3090       case LS_get_set: {
3091       // Check the signatures.
3092 #ifdef ASSERT
3093       assert(rtype == type, "get and set must return the expected type");
3094       assert(sig->count() == 3, "get and set has 3 arguments");
3095       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3096       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3097       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3098       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3099 #endif // ASSERT
3100         break;
3101       }
3102       case LS_cmp_swap:
3103       case LS_cmp_swap_weak: {
3104       // Check the signatures.
3105 #ifdef ASSERT
3106       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3107       assert(sig->count() == 4, "CAS has 4 arguments");
3108       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3109       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3110 #endif // ASSERT
3111         break;
3112       }
3113       case LS_cmp_exchange: {
3114       // Check the signatures.
3115 #ifdef ASSERT
3116       assert(rtype == type, "CAS must return the expected type");
3117       assert(sig->count() == 4, "CAS has 4 arguments");
3118       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3119       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3120 #endif // ASSERT
3121         break;
3122       }
3123       default:
3124         ShouldNotReachHere();
3125     }
3126   }
3127 #endif //PRODUCT
3128 
3129   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3130 
3131   // Get arguments:
3132   Node* receiver = nullptr;
3133   Node* base     = nullptr;
3134   Node* offset   = nullptr;
3135   Node* oldval   = nullptr;
3136   Node* newval   = nullptr;
3137   switch(kind) {
3138     case LS_cmp_swap:
3139     case LS_cmp_swap_weak:
3140     case LS_cmp_exchange: {
3141       const bool two_slot_type = type2size[type] == 2;
3142       receiver = argument(0);  // type: oop
3143       base     = argument(1);  // type: oop
3144       offset   = argument(2);  // type: long
3145       oldval   = argument(4);  // type: oop, int, or long
3146       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3147       break;
3148     }
3149     case LS_get_add:
3150     case LS_get_set: {
3151       receiver = argument(0);  // type: oop
3152       base     = argument(1);  // type: oop
3153       offset   = argument(2);  // type: long
3154       oldval   = nullptr;
3155       newval   = argument(4);  // type: oop, int, or long
3156       break;
3157     }
3158     default:
3159       ShouldNotReachHere();
3160   }
3161 
3162   // Build field offset expression.
3163   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3164   // to be plain byte offsets, which are also the same as those accepted
3165   // by oopDesc::field_addr.
3166   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3167   // 32-bit machines ignore the high half of long offsets
3168   offset = ConvL2X(offset);
3169   // Save state and restore on bailout
3170   SavedState old_state(this);
3171   Node* adr = make_unsafe_address(base, offset,type, false);
3172   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3173 
3174   Compile::AliasType* alias_type = C->alias_type(adr_type);
3175   BasicType bt = alias_type->basic_type();
3176   if (bt != T_ILLEGAL &&
3177       (is_reference_type(bt) != (type == T_OBJECT))) {
3178     // Don't intrinsify mismatched object accesses.
3179     return false;
3180   }
3181 
3182   old_state.discard();
3183 
3184   // For CAS, unlike inline_unsafe_access, there seems no point in
3185   // trying to refine types. Just use the coarse types here.
3186   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3187   const Type *value_type = Type::get_const_basic_type(type);
3188 
3189   switch (kind) {
3190     case LS_get_set:
3191     case LS_cmp_exchange: {
3192       if (type == T_OBJECT) {
3193         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3194         if (tjp != nullptr) {
3195           value_type = tjp;
3196         }
3197       }
3198       break;
3199     }
3200     case LS_cmp_swap:
3201     case LS_cmp_swap_weak:
3202     case LS_get_add:
3203       break;
3204     default:
3205       ShouldNotReachHere();
3206   }
3207 
3208   // Null check receiver.
3209   receiver = null_check(receiver);
3210   if (stopped()) {
3211     return true;
3212   }
3213 
3214   int alias_idx = C->get_alias_index(adr_type);
3215 
3216   if (is_reference_type(type)) {
3217     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3218 
3219     if (oldval != nullptr && oldval->is_InlineType()) {
3220       // Re-execute the unsafe access if allocation triggers deoptimization.
3221       PreserveReexecuteState preexecs(this);
3222       jvms()->set_should_reexecute(true);
3223       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3224     }
3225     if (newval != nullptr && newval->is_InlineType()) {
3226       // Re-execute the unsafe access if allocation triggers deoptimization.
3227       PreserveReexecuteState preexecs(this);
3228       jvms()->set_should_reexecute(true);
3229       newval = newval->as_InlineType()->buffer(this)->get_oop();
3230     }
3231 
3232     // Transformation of a value which could be null pointer (CastPP #null)
3233     // could be delayed during Parse (for example, in adjust_map_after_if()).
3234     // Execute transformation here to avoid barrier generation in such case.
3235     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3236       newval = _gvn.makecon(TypePtr::NULL_PTR);
3237 
3238     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3239       // Refine the value to a null constant, when it is known to be null
3240       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3241     }
3242   }
3243 
3244   Node* result = nullptr;
3245   switch (kind) {
3246     case LS_cmp_exchange: {
3247       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3248                                             oldval, newval, value_type, type, decorators);
3249       break;
3250     }
3251     case LS_cmp_swap_weak:
3252       decorators |= C2_WEAK_CMPXCHG;
3253     case LS_cmp_swap: {
3254       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3255                                              oldval, newval, value_type, type, decorators);
3256       break;
3257     }
3258     case LS_get_set: {
3259       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3260                                      newval, value_type, type, decorators);
3261       break;
3262     }
3263     case LS_get_add: {
3264       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3265                                     newval, value_type, type, decorators);
3266       break;
3267     }
3268     default:
3269       ShouldNotReachHere();
3270   }
3271 
3272   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3273   set_result(result);
3274   return true;
3275 }
3276 
3277 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3278   // Regardless of form, don't allow previous ld/st to move down,
3279   // then issue acquire, release, or volatile mem_bar.
3280   insert_mem_bar(Op_MemBarCPUOrder);
3281   switch(id) {
3282     case vmIntrinsics::_loadFence:
3283       insert_mem_bar(Op_LoadFence);
3284       return true;
3285     case vmIntrinsics::_storeFence:
3286       insert_mem_bar(Op_StoreFence);
3287       return true;
3288     case vmIntrinsics::_storeStoreFence:
3289       insert_mem_bar(Op_StoreStoreFence);
3290       return true;
3291     case vmIntrinsics::_fullFence:
3292       insert_mem_bar(Op_MemBarVolatile);
3293       return true;
3294     default:
3295       fatal_unexpected_iid(id);
3296       return false;
3297   }
3298 }
3299 
3300 // private native int arrayInstanceBaseOffset0(Object[] array);
3301 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3302   Node* array = argument(1);
3303   Node* klass_node = load_object_klass(array);
3304 
3305   jint  layout_con = Klass::_lh_neutral_value;
3306   Node* layout_val = get_layout_helper(klass_node, layout_con);
3307   int   layout_is_con = (layout_val == nullptr);
3308 
3309   Node* header_size = nullptr;
3310   if (layout_is_con) {
3311     int hsize = Klass::layout_helper_header_size(layout_con);
3312     header_size = intcon(hsize);
3313   } else {
3314     Node* hss = intcon(Klass::_lh_header_size_shift);
3315     Node* hsm = intcon(Klass::_lh_header_size_mask);
3316     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3317     header_size = _gvn.transform(new AndINode(header_size, hsm));
3318   }
3319   set_result(header_size);
3320   return true;
3321 }
3322 
3323 // private native int arrayInstanceIndexScale0(Object[] array);
3324 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3325   Node* array = argument(1);
3326   Node* klass_node = load_object_klass(array);
3327 
3328   jint  layout_con = Klass::_lh_neutral_value;
3329   Node* layout_val = get_layout_helper(klass_node, layout_con);
3330   int   layout_is_con = (layout_val == nullptr);
3331 
3332   Node* element_size = nullptr;
3333   if (layout_is_con) {
3334     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3335     int elem_size = 1 << log_element_size;
3336     element_size = intcon(elem_size);
3337   } else {
3338     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3339     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3340     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3341     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3342     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3343   }
3344   set_result(element_size);
3345   return true;
3346 }
3347 
3348 // private native int arrayLayout0(Object[] array);
3349 bool LibraryCallKit::inline_arrayLayout() {
3350   RegionNode* region = new RegionNode(2);
3351   Node* phi = new PhiNode(region, TypeInt::POS);
3352 
3353   Node* array = argument(1);
3354   Node* klass_node = load_object_klass(array);
3355   generate_refArray_guard(klass_node, region);
3356   if (region->req() == 3) {
3357     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3358   }
3359 
3360   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3361   Node* layout_kind_addr = basic_plus_adr(klass_node, klass_node, layout_kind_offset);
3362   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3363 
3364   region->init_req(1, control());
3365   phi->init_req(1, layout_kind);
3366 
3367   set_control(_gvn.transform(region));
3368   set_result(_gvn.transform(phi));
3369   return true;
3370 }
3371 
3372 bool LibraryCallKit::inline_onspinwait() {
3373   insert_mem_bar(Op_OnSpinWait);
3374   return true;
3375 }
3376 
3377 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3378   if (!kls->is_Con()) {
3379     return true;
3380   }
3381   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3382   if (klsptr == nullptr) {
3383     return true;
3384   }
3385   ciInstanceKlass* ik = klsptr->instance_klass();
3386   // don't need a guard for a klass that is already initialized
3387   return !ik->is_initialized();
3388 }
3389 
3390 //----------------------------inline_unsafe_writeback0-------------------------
3391 // public native void Unsafe.writeback0(long address)
3392 bool LibraryCallKit::inline_unsafe_writeback0() {
3393   if (!Matcher::has_match_rule(Op_CacheWB)) {
3394     return false;
3395   }
3396 #ifndef PRODUCT
3397   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3398   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3399   ciSignature* sig = callee()->signature();
3400   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3401 #endif
3402   null_check_receiver();  // null-check, then ignore
3403   Node *addr = argument(1);
3404   addr = new CastX2PNode(addr);
3405   addr = _gvn.transform(addr);
3406   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3407   flush = _gvn.transform(flush);
3408   set_memory(flush, TypeRawPtr::BOTTOM);
3409   return true;
3410 }
3411 
3412 //----------------------------inline_unsafe_writeback0-------------------------
3413 // public native void Unsafe.writeback0(long address)
3414 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3415   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3416     return false;
3417   }
3418   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3419     return false;
3420   }
3421 #ifndef PRODUCT
3422   assert(Matcher::has_match_rule(Op_CacheWB),
3423          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3424                 : "found match rule for CacheWBPostSync but not CacheWB"));
3425 
3426 #endif
3427   null_check_receiver();  // null-check, then ignore
3428   Node *sync;
3429   if (is_pre) {
3430     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3431   } else {
3432     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3433   }
3434   sync = _gvn.transform(sync);
3435   set_memory(sync, TypeRawPtr::BOTTOM);
3436   return true;
3437 }
3438 
3439 //----------------------------inline_unsafe_allocate---------------------------
3440 // public native Object Unsafe.allocateInstance(Class<?> cls);
3441 bool LibraryCallKit::inline_unsafe_allocate() {
3442 
3443 #if INCLUDE_JVMTI
3444   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3445     return false;
3446   }
3447 #endif //INCLUDE_JVMTI
3448 
3449   if (callee()->is_static())  return false;  // caller must have the capability!
3450 
3451   null_check_receiver();  // null-check, then ignore
3452   Node* cls = null_check(argument(1));
3453   if (stopped())  return true;
3454 
3455   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3456   kls = null_check(kls);
3457   if (stopped())  return true;  // argument was like int.class
3458 
3459 #if INCLUDE_JVMTI
3460     // Don't try to access new allocated obj in the intrinsic.
3461     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3462     // Deoptimize and allocate in interpreter instead.
3463     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3464     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3465     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3466     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3467     {
3468       BuildCutout unless(this, tst, PROB_MAX);
3469       uncommon_trap(Deoptimization::Reason_intrinsic,
3470                     Deoptimization::Action_make_not_entrant);
3471     }
3472     if (stopped()) {
3473       return true;
3474     }
3475 #endif //INCLUDE_JVMTI
3476 
3477   Node* test = nullptr;
3478   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3479     // Note:  The argument might still be an illegal value like
3480     // Serializable.class or Object[].class.   The runtime will handle it.
3481     // But we must make an explicit check for initialization.
3482     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3483     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3484     // can generate code to load it as unsigned byte.
3485     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3486     Node* bits = intcon(InstanceKlass::fully_initialized);
3487     test = _gvn.transform(new SubINode(inst, bits));
3488     // The 'test' is non-zero if we need to take a slow path.
3489   }
3490   Node* obj = nullptr;
3491   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3492   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3493     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3494   } else {
3495     obj = new_instance(kls, test);
3496   }
3497   set_result(obj);
3498   return true;
3499 }
3500 
3501 //------------------------inline_native_time_funcs--------------
3502 // inline code for System.currentTimeMillis() and System.nanoTime()
3503 // these have the same type and signature
3504 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3505   const TypeFunc* tf = OptoRuntime::void_long_Type();
3506   const TypePtr* no_memory_effects = nullptr;
3507   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3508   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3509 #ifdef ASSERT
3510   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3511   assert(value_top == top(), "second value must be top");
3512 #endif
3513   set_result(value);
3514   return true;
3515 }
3516 
3517 
3518 #if INCLUDE_JVMTI
3519 
3520 // When notifications are disabled then just update the VTMS transition bit and return.
3521 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3522 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3523   if (!DoJVMTIVirtualThreadTransitions) {
3524     return true;
3525   }
3526   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3527   IdealKit ideal(this);
3528 
3529   Node* ONE = ideal.ConI(1);
3530   Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3531   Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3532   Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3533 
3534   ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3535     sync_kit(ideal);
3536     // if notifyJvmti enabled then make a call to the given SharedRuntime function
3537     const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3538     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3539     ideal.sync_kit(this);
3540   } ideal.else_(); {
3541     // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3542     Node* thread = ideal.thread();
3543     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3544     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3545 
3546     sync_kit(ideal);
3547     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3548     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3549 
3550     ideal.sync_kit(this);
3551   } ideal.end_if();
3552   final_sync(ideal);
3553 
3554   return true;
3555 }
3556 
3557 // Always update the is_disable_suspend bit.
3558 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3559   if (!DoJVMTIVirtualThreadTransitions) {
3560     return true;
3561   }
3562   IdealKit ideal(this);
3563 
3564   {
3565     // unconditionally update the is_disable_suspend bit in current JavaThread
3566     Node* thread = ideal.thread();
3567     Node* arg = _gvn.transform(argument(0)); // argument for notification
3568     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3569     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3570 
3571     sync_kit(ideal);
3572     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3573     ideal.sync_kit(this);
3574   }
3575   final_sync(ideal);
3576 
3577   return true;
3578 }
3579 
3580 #endif // INCLUDE_JVMTI
3581 
3582 #ifdef JFR_HAVE_INTRINSICS
3583 
3584 /**
3585  * if oop->klass != null
3586  *   // normal class
3587  *   epoch = _epoch_state ? 2 : 1
3588  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3589  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3590  *   }
3591  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3592  * else
3593  *   // primitive class
3594  *   if oop->array_klass != null
3595  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3596  *   else
3597  *     id = LAST_TYPE_ID + 1 // void class path
3598  *   if (!signaled)
3599  *     signaled = true
3600  */
3601 bool LibraryCallKit::inline_native_classID() {
3602   Node* cls = argument(0);
3603 
3604   IdealKit ideal(this);
3605 #define __ ideal.
3606   IdealVariable result(ideal); __ declarations_done();
3607   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3608                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3609                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3610 
3611 
3612   __ if_then(kls, BoolTest::ne, null()); {
3613     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3614     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3615 
3616     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3617     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3618     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3619     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3620     mask = _gvn.transform(new OrLNode(mask, epoch));
3621     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3622 
3623     float unlikely  = PROB_UNLIKELY(0.999);
3624     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3625       sync_kit(ideal);
3626       make_runtime_call(RC_LEAF,
3627                         OptoRuntime::class_id_load_barrier_Type(),
3628                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3629                         "class id load barrier",
3630                         TypePtr::BOTTOM,
3631                         kls);
3632       ideal.sync_kit(this);
3633     } __ end_if();
3634 
3635     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3636   } __ else_(); {
3637     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3638                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3639                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3640     __ if_then(array_kls, BoolTest::ne, null()); {
3641       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3642       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3643       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3644       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3645     } __ else_(); {
3646       // void class case
3647       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3648     } __ end_if();
3649 
3650     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3651     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3652     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3653       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3654     } __ end_if();
3655   } __ end_if();
3656 
3657   final_sync(ideal);
3658   set_result(ideal.value(result));
3659 #undef __
3660   return true;
3661 }
3662 
3663 //------------------------inline_native_jvm_commit------------------
3664 bool LibraryCallKit::inline_native_jvm_commit() {
3665   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3666 
3667   // Save input memory and i_o state.
3668   Node* input_memory_state = reset_memory();
3669   set_all_memory(input_memory_state);
3670   Node* input_io_state = i_o();
3671 
3672   // TLS.
3673   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3674   // Jfr java buffer.
3675   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3676   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3677   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3678 
3679   // Load the current value of the notified field in the JfrThreadLocal.
3680   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3681   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3682 
3683   // Test for notification.
3684   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3685   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3686   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3687 
3688   // True branch, is notified.
3689   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3690   set_control(is_notified);
3691 
3692   // Reset notified state.
3693   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3694   Node* notified_reset_memory = reset_memory();
3695 
3696   // 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.
3697   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3698   // Convert the machine-word to a long.
3699   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3700 
3701   // False branch, not notified.
3702   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3703   set_control(not_notified);
3704   set_all_memory(input_memory_state);
3705 
3706   // Arg is the next position as a long.
3707   Node* arg = argument(0);
3708   // Convert long to machine-word.
3709   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3710 
3711   // Store the next_position to the underlying jfr java buffer.
3712   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3713 
3714   Node* commit_memory = reset_memory();
3715   set_all_memory(commit_memory);
3716 
3717   // 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.
3718   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3719   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3720   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3721 
3722   // And flags with lease constant.
3723   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3724 
3725   // Branch on lease to conditionalize returning the leased java buffer.
3726   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3727   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3728   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3729 
3730   // False branch, not a lease.
3731   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3732 
3733   // True branch, is lease.
3734   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3735   set_control(is_lease);
3736 
3737   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3738   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3739                                               OptoRuntime::void_void_Type(),
3740                                               SharedRuntime::jfr_return_lease(),
3741                                               "return_lease", TypePtr::BOTTOM);
3742   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3743 
3744   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3745   record_for_igvn(lease_compare_rgn);
3746   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3747   record_for_igvn(lease_compare_mem);
3748   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3749   record_for_igvn(lease_compare_io);
3750   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3751   record_for_igvn(lease_result_value);
3752 
3753   // Update control and phi nodes.
3754   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3755   lease_compare_rgn->init_req(_false_path, not_lease);
3756 
3757   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3758   lease_compare_mem->init_req(_false_path, commit_memory);
3759 
3760   lease_compare_io->init_req(_true_path, i_o());
3761   lease_compare_io->init_req(_false_path, input_io_state);
3762 
3763   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3764   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3765 
3766   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3767   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3768   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3769   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3770 
3771   // Update control and phi nodes.
3772   result_rgn->init_req(_true_path, is_notified);
3773   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3774 
3775   result_mem->init_req(_true_path, notified_reset_memory);
3776   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3777 
3778   result_io->init_req(_true_path, input_io_state);
3779   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3780 
3781   result_value->init_req(_true_path, current_pos);
3782   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3783 
3784   // Set output state.
3785   set_control(_gvn.transform(result_rgn));
3786   set_all_memory(_gvn.transform(result_mem));
3787   set_i_o(_gvn.transform(result_io));
3788   set_result(result_rgn, result_value);
3789   return true;
3790 }
3791 
3792 /*
3793  * The intrinsic is a model of this pseudo-code:
3794  *
3795  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3796  * jobject h_event_writer = tl->java_event_writer();
3797  * if (h_event_writer == nullptr) {
3798  *   return nullptr;
3799  * }
3800  * oop threadObj = Thread::threadObj();
3801  * oop vthread = java_lang_Thread::vthread(threadObj);
3802  * traceid tid;
3803  * bool pinVirtualThread;
3804  * bool excluded;
3805  * if (vthread != threadObj) {  // i.e. current thread is virtual
3806  *   tid = java_lang_Thread::tid(vthread);
3807  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3808  *   pinVirtualThread = VMContinuations;
3809  *   excluded = vthread_epoch_raw & excluded_mask;
3810  *   if (!excluded) {
3811  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3812  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3813  *     if (vthread_epoch != current_epoch) {
3814  *       write_checkpoint();
3815  *     }
3816  *   }
3817  * } else {
3818  *   tid = java_lang_Thread::tid(threadObj);
3819  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3820  *   pinVirtualThread = false;
3821  *   excluded = thread_epoch_raw & excluded_mask;
3822  * }
3823  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3824  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3825  * if (tid_in_event_writer != tid) {
3826  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3827  *   setField(event_writer, "excluded", excluded);
3828  *   setField(event_writer, "threadID", tid);
3829  * }
3830  * return event_writer
3831  */
3832 bool LibraryCallKit::inline_native_getEventWriter() {
3833   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3834 
3835   // Save input memory and i_o state.
3836   Node* input_memory_state = reset_memory();
3837   set_all_memory(input_memory_state);
3838   Node* input_io_state = i_o();
3839 
3840   // The most significant bit of the u2 is used to denote thread exclusion
3841   Node* excluded_shift = _gvn.intcon(15);
3842   Node* excluded_mask = _gvn.intcon(1 << 15);
3843   // The epoch generation is the range [1-32767]
3844   Node* epoch_mask = _gvn.intcon(32767);
3845 
3846   // TLS
3847   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3848 
3849   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3850   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3851 
3852   // Load the eventwriter jobject handle.
3853   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3854 
3855   // Null check the jobject handle.
3856   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3857   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3858   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3859 
3860   // False path, jobj is null.
3861   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3862 
3863   // True path, jobj is not null.
3864   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3865 
3866   set_control(jobj_is_not_null);
3867 
3868   // Load the threadObj for the CarrierThread.
3869   Node* threadObj = generate_current_thread(tls_ptr);
3870 
3871   // Load the vthread.
3872   Node* vthread = generate_virtual_thread(tls_ptr);
3873 
3874   // If vthread != threadObj, this is a virtual thread.
3875   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3876   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3877   IfNode* iff_vthread_not_equal_threadObj =
3878     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3879 
3880   // False branch, fallback to threadObj.
3881   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3882   set_control(vthread_equal_threadObj);
3883 
3884   // Load the tid field from the vthread object.
3885   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3886 
3887   // Load the raw epoch value from the threadObj.
3888   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3889   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3890                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3891                                              TypeInt::CHAR, T_CHAR,
3892                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3893 
3894   // Mask off the excluded information from the epoch.
3895   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3896 
3897   // True branch, this is a virtual thread.
3898   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3899   set_control(vthread_not_equal_threadObj);
3900 
3901   // Load the tid field from the vthread object.
3902   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3903 
3904   // Continuation support determines if a virtual thread should be pinned.
3905   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3906   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3907 
3908   // Load the raw epoch value from the vthread.
3909   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3910   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3911                                            TypeInt::CHAR, T_CHAR,
3912                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3913 
3914   // Mask off the excluded information from the epoch.
3915   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3916 
3917   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3918   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3919   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3920   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3921 
3922   // False branch, vthread is excluded, no need to write epoch info.
3923   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3924 
3925   // True branch, vthread is included, update epoch info.
3926   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3927   set_control(included);
3928 
3929   // Get epoch value.
3930   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3931 
3932   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3933   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3934   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3935 
3936   // Compare the epoch in the vthread to the current epoch generation.
3937   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3938   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3939   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3940 
3941   // False path, epoch is equal, checkpoint information is valid.
3942   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3943 
3944   // True path, epoch is not equal, write a checkpoint for the vthread.
3945   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3946 
3947   set_control(epoch_is_not_equal);
3948 
3949   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3950   // The call also updates the native thread local thread id and the vthread with the current epoch.
3951   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3952                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3953                                                   SharedRuntime::jfr_write_checkpoint(),
3954                                                   "write_checkpoint", TypePtr::BOTTOM);
3955   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3956 
3957   // vthread epoch != current epoch
3958   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3959   record_for_igvn(epoch_compare_rgn);
3960   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3961   record_for_igvn(epoch_compare_mem);
3962   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3963   record_for_igvn(epoch_compare_io);
3964 
3965   // Update control and phi nodes.
3966   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3967   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3968   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3969   epoch_compare_mem->init_req(_false_path, input_memory_state);
3970   epoch_compare_io->init_req(_true_path, i_o());
3971   epoch_compare_io->init_req(_false_path, input_io_state);
3972 
3973   // excluded != true
3974   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3975   record_for_igvn(exclude_compare_rgn);
3976   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3977   record_for_igvn(exclude_compare_mem);
3978   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3979   record_for_igvn(exclude_compare_io);
3980 
3981   // Update control and phi nodes.
3982   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3983   exclude_compare_rgn->init_req(_false_path, excluded);
3984   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3985   exclude_compare_mem->init_req(_false_path, input_memory_state);
3986   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3987   exclude_compare_io->init_req(_false_path, input_io_state);
3988 
3989   // vthread != threadObj
3990   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3991   record_for_igvn(vthread_compare_rgn);
3992   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3993   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3994   record_for_igvn(vthread_compare_io);
3995   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3996   record_for_igvn(tid);
3997   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3998   record_for_igvn(exclusion);
3999   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
4000   record_for_igvn(pinVirtualThread);
4001 
4002   // Update control and phi nodes.
4003   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
4004   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
4005   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
4006   vthread_compare_mem->init_req(_false_path, input_memory_state);
4007   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
4008   vthread_compare_io->init_req(_false_path, input_io_state);
4009   tid->init_req(_true_path, _gvn.transform(vthread_tid));
4010   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
4011   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4012   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
4013   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
4014   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
4015 
4016   // Update branch state.
4017   set_control(_gvn.transform(vthread_compare_rgn));
4018   set_all_memory(_gvn.transform(vthread_compare_mem));
4019   set_i_o(_gvn.transform(vthread_compare_io));
4020 
4021   // Load the event writer oop by dereferencing the jobject handle.
4022   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
4023   assert(klass_EventWriter->is_loaded(), "invariant");
4024   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
4025   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
4026   const TypeOopPtr* const xtype = aklass->as_instance_type();
4027   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
4028   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
4029 
4030   // Load the current thread id from the event writer object.
4031   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
4032   // Get the field offset to, conditionally, store an updated tid value later.
4033   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
4034   // Get the field offset to, conditionally, store an updated exclusion value later.
4035   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
4036   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
4037   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
4038 
4039   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
4040   record_for_igvn(event_writer_tid_compare_rgn);
4041   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4042   record_for_igvn(event_writer_tid_compare_mem);
4043   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
4044   record_for_igvn(event_writer_tid_compare_io);
4045 
4046   // Compare the current tid from the thread object to what is currently stored in the event writer object.
4047   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
4048   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
4049   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
4050 
4051   // False path, tids are the same.
4052   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4053 
4054   // True path, tid is not equal, need to update the tid in the event writer.
4055   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4056   record_for_igvn(tid_is_not_equal);
4057 
4058   // Store the pin state to the event writer.
4059   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4060 
4061   // Store the exclusion state to the event writer.
4062   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4063   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4064 
4065   // Store the tid to the event writer.
4066   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4067 
4068   // Update control and phi nodes.
4069   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4070   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4071   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4072   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4073   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4074   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4075 
4076   // Result of top level CFG, Memory, IO and Value.
4077   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4078   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4079   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4080   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4081 
4082   // Result control.
4083   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4084   result_rgn->init_req(_false_path, jobj_is_null);
4085 
4086   // Result memory.
4087   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4088   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4089 
4090   // Result IO.
4091   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4092   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4093 
4094   // Result value.
4095   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4096   result_value->init_req(_false_path, null()); // return null
4097 
4098   // Set output state.
4099   set_control(_gvn.transform(result_rgn));
4100   set_all_memory(_gvn.transform(result_mem));
4101   set_i_o(_gvn.transform(result_io));
4102   set_result(result_rgn, result_value);
4103   return true;
4104 }
4105 
4106 /*
4107  * The intrinsic is a model of this pseudo-code:
4108  *
4109  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4110  * if (carrierThread != thread) { // is virtual thread
4111  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4112  *   bool excluded = vthread_epoch_raw & excluded_mask;
4113  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4114  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4115  *   if (!excluded) {
4116  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4117  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4118  *   }
4119  *   AtomicAccess::release_store(&tl->_vthread, true);
4120  *   return;
4121  * }
4122  * AtomicAccess::release_store(&tl->_vthread, false);
4123  */
4124 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4125   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4126 
4127   Node* input_memory_state = reset_memory();
4128   set_all_memory(input_memory_state);
4129 
4130   // The most significant bit of the u2 is used to denote thread exclusion
4131   Node* excluded_mask = _gvn.intcon(1 << 15);
4132   // The epoch generation is the range [1-32767]
4133   Node* epoch_mask = _gvn.intcon(32767);
4134 
4135   Node* const carrierThread = generate_current_thread(jt);
4136   // If thread != carrierThread, this is a virtual thread.
4137   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4138   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4139   IfNode* iff_thread_not_equal_carrierThread =
4140     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4141 
4142   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4143 
4144   // False branch, is carrierThread.
4145   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4146   // Store release
4147   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4148 
4149   set_all_memory(input_memory_state);
4150 
4151   // True branch, is virtual thread.
4152   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4153   set_control(thread_not_equal_carrierThread);
4154 
4155   // Load the raw epoch value from the vthread.
4156   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4157   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4158                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4159 
4160   // Mask off the excluded information from the epoch.
4161   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4162 
4163   // Load the tid field from the thread.
4164   Node* tid = load_field_from_object(thread, "tid", "J");
4165 
4166   // Store the vthread tid to the jfr thread local.
4167   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4168   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4169 
4170   // Branch is_excluded to conditionalize updating the epoch .
4171   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4172   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4173   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4174 
4175   // True branch, vthread is excluded, no need to write epoch info.
4176   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4177   set_control(excluded);
4178   Node* vthread_is_excluded = _gvn.intcon(1);
4179 
4180   // False branch, vthread is included, update epoch info.
4181   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4182   set_control(included);
4183   Node* vthread_is_included = _gvn.intcon(0);
4184 
4185   // Get epoch value.
4186   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4187 
4188   // Store the vthread epoch to the jfr thread local.
4189   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4190   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4191 
4192   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4193   record_for_igvn(excluded_rgn);
4194   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4195   record_for_igvn(excluded_mem);
4196   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4197   record_for_igvn(exclusion);
4198 
4199   // Merge the excluded control and memory.
4200   excluded_rgn->init_req(_true_path, excluded);
4201   excluded_rgn->init_req(_false_path, included);
4202   excluded_mem->init_req(_true_path, tid_memory);
4203   excluded_mem->init_req(_false_path, included_memory);
4204   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4205   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4206 
4207   // Set intermediate state.
4208   set_control(_gvn.transform(excluded_rgn));
4209   set_all_memory(excluded_mem);
4210 
4211   // Store the vthread exclusion state to the jfr thread local.
4212   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4213   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4214 
4215   // Store release
4216   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4217 
4218   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4219   record_for_igvn(thread_compare_rgn);
4220   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4221   record_for_igvn(thread_compare_mem);
4222   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4223   record_for_igvn(vthread);
4224 
4225   // Merge the thread_compare control and memory.
4226   thread_compare_rgn->init_req(_true_path, control());
4227   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4228   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4229   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4230 
4231   // Set output state.
4232   set_control(_gvn.transform(thread_compare_rgn));
4233   set_all_memory(_gvn.transform(thread_compare_mem));
4234 }
4235 
4236 #endif // JFR_HAVE_INTRINSICS
4237 
4238 //------------------------inline_native_currentCarrierThread------------------
4239 bool LibraryCallKit::inline_native_currentCarrierThread() {
4240   Node* junk = nullptr;
4241   set_result(generate_current_thread(junk));
4242   return true;
4243 }
4244 
4245 //------------------------inline_native_currentThread------------------
4246 bool LibraryCallKit::inline_native_currentThread() {
4247   Node* junk = nullptr;
4248   set_result(generate_virtual_thread(junk));
4249   return true;
4250 }
4251 
4252 //------------------------inline_native_setVthread------------------
4253 bool LibraryCallKit::inline_native_setCurrentThread() {
4254   assert(C->method()->changes_current_thread(),
4255          "method changes current Thread but is not annotated ChangesCurrentThread");
4256   Node* arr = argument(1);
4257   Node* thread = _gvn.transform(new ThreadLocalNode());
4258   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4259   Node* thread_obj_handle
4260     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4261   thread_obj_handle = _gvn.transform(thread_obj_handle);
4262   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4263   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4264 
4265   // Change the _monitor_owner_id of the JavaThread
4266   Node* tid = load_field_from_object(arr, "tid", "J");
4267   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4268   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4269 
4270   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4271   return true;
4272 }
4273 
4274 const Type* LibraryCallKit::scopedValueCache_type() {
4275   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4276   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4277   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4278 
4279   // Because we create the scopedValue cache lazily we have to make the
4280   // type of the result BotPTR.
4281   bool xk = etype->klass_is_exact();
4282   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4283   return objects_type;
4284 }
4285 
4286 Node* LibraryCallKit::scopedValueCache_helper() {
4287   Node* thread = _gvn.transform(new ThreadLocalNode());
4288   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4289   // We cannot use immutable_memory() because we might flip onto a
4290   // different carrier thread, at which point we'll need to use that
4291   // carrier thread's cache.
4292   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4293   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4294   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4295 }
4296 
4297 //------------------------inline_native_scopedValueCache------------------
4298 bool LibraryCallKit::inline_native_scopedValueCache() {
4299   Node* cache_obj_handle = scopedValueCache_helper();
4300   const Type* objects_type = scopedValueCache_type();
4301   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4302 
4303   return true;
4304 }
4305 
4306 //------------------------inline_native_setScopedValueCache------------------
4307 bool LibraryCallKit::inline_native_setScopedValueCache() {
4308   Node* arr = argument(0);
4309   Node* cache_obj_handle = scopedValueCache_helper();
4310   const Type* objects_type = scopedValueCache_type();
4311 
4312   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4313   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4314 
4315   return true;
4316 }
4317 
4318 //------------------------inline_native_Continuation_pin and unpin-----------
4319 
4320 // Shared implementation routine for both pin and unpin.
4321 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4322   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4323 
4324   // Save input memory.
4325   Node* input_memory_state = reset_memory();
4326   set_all_memory(input_memory_state);
4327 
4328   // TLS
4329   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4330   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4331   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4332 
4333   // Null check the last continuation object.
4334   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4335   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4336   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4337 
4338   // False path, last continuation is null.
4339   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4340 
4341   // True path, last continuation is not null.
4342   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4343 
4344   set_control(continuation_is_not_null);
4345 
4346   // Load the pin count from the last continuation.
4347   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4348   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4349 
4350   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4351   Node* pin_count_rhs;
4352   if (unpin) {
4353     pin_count_rhs = _gvn.intcon(0);
4354   } else {
4355     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4356   }
4357   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4358   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4359   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4360 
4361   // True branch, pin count over/underflow.
4362   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4363   {
4364     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4365     // which will throw IllegalStateException for pin count over/underflow.
4366     // No memory changed so far - we can use memory create by reset_memory()
4367     // at the beginning of this intrinsic. No need to call reset_memory() again.
4368     PreserveJVMState pjvms(this);
4369     set_control(pin_count_over_underflow);
4370     uncommon_trap(Deoptimization::Reason_intrinsic,
4371                   Deoptimization::Action_none);
4372     assert(stopped(), "invariant");
4373   }
4374 
4375   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4376   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4377   set_control(valid_pin_count);
4378 
4379   Node* next_pin_count;
4380   if (unpin) {
4381     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4382   } else {
4383     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4384   }
4385 
4386   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4387 
4388   // Result of top level CFG and Memory.
4389   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4390   record_for_igvn(result_rgn);
4391   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4392   record_for_igvn(result_mem);
4393 
4394   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4395   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4396   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4397   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4398 
4399   // Set output state.
4400   set_control(_gvn.transform(result_rgn));
4401   set_all_memory(_gvn.transform(result_mem));
4402 
4403   return true;
4404 }
4405 
4406 //-----------------------load_klass_from_mirror_common-------------------------
4407 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4408 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4409 // and branch to the given path on the region.
4410 // If never_see_null, take an uncommon trap on null, so we can optimistically
4411 // compile for the non-null case.
4412 // If the region is null, force never_see_null = true.
4413 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4414                                                     bool never_see_null,
4415                                                     RegionNode* region,
4416                                                     int null_path,
4417                                                     int offset) {
4418   if (region == nullptr)  never_see_null = true;
4419   Node* p = basic_plus_adr(mirror, offset);
4420   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4421   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4422   Node* null_ctl = top();
4423   kls = null_check_oop(kls, &null_ctl, never_see_null);
4424   if (region != nullptr) {
4425     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4426     region->init_req(null_path, null_ctl);
4427   } else {
4428     assert(null_ctl == top(), "no loose ends");
4429   }
4430   return kls;
4431 }
4432 
4433 //--------------------(inline_native_Class_query helpers)---------------------
4434 // Use this for JVM_ACC_INTERFACE.
4435 // Fall through if (mods & mask) == bits, take the guard otherwise.
4436 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4437                                                  ByteSize offset, const Type* type, BasicType bt) {
4438   // Branch around if the given klass has the given modifier bit set.
4439   // Like generate_guard, adds a new path onto the region.
4440   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4441   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4442   Node* mask = intcon(modifier_mask);
4443   Node* bits = intcon(modifier_bits);
4444   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4445   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4446   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4447   return generate_fair_guard(bol, region);
4448 }
4449 
4450 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4451   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4452                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4453 }
4454 
4455 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4456 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4457   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4458                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4459 }
4460 
4461 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4462   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4463 }
4464 
4465 //-------------------------inline_native_Class_query-------------------
4466 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4467   const Type* return_type = TypeInt::BOOL;
4468   Node* prim_return_value = top();  // what happens if it's a primitive class?
4469   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4470   bool expect_prim = false;     // most of these guys expect to work on refs
4471 
4472   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4473 
4474   Node* mirror = argument(0);
4475   Node* obj    = top();
4476 
4477   switch (id) {
4478   case vmIntrinsics::_isInstance:
4479     // nothing is an instance of a primitive type
4480     prim_return_value = intcon(0);
4481     obj = argument(1);
4482     break;
4483   case vmIntrinsics::_isHidden:
4484     prim_return_value = intcon(0);
4485     break;
4486   case vmIntrinsics::_getSuperclass:
4487     prim_return_value = null();
4488     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4489     break;
4490   default:
4491     fatal_unexpected_iid(id);
4492     break;
4493   }
4494 
4495   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4496   if (mirror_con == nullptr)  return false;  // cannot happen?
4497 
4498 #ifndef PRODUCT
4499   if (C->print_intrinsics() || C->print_inlining()) {
4500     ciType* k = mirror_con->java_mirror_type();
4501     if (k) {
4502       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4503       k->print_name();
4504       tty->cr();
4505     }
4506   }
4507 #endif
4508 
4509   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4510   RegionNode* region = new RegionNode(PATH_LIMIT);
4511   record_for_igvn(region);
4512   PhiNode* phi = new PhiNode(region, return_type);
4513 
4514   // The mirror will never be null of Reflection.getClassAccessFlags, however
4515   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4516   // if it is. See bug 4774291.
4517 
4518   // For Reflection.getClassAccessFlags(), the null check occurs in
4519   // the wrong place; see inline_unsafe_access(), above, for a similar
4520   // situation.
4521   mirror = null_check(mirror);
4522   // If mirror or obj is dead, only null-path is taken.
4523   if (stopped())  return true;
4524 
4525   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4526 
4527   // Now load the mirror's klass metaobject, and null-check it.
4528   // Side-effects region with the control path if the klass is null.
4529   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4530   // If kls is null, we have a primitive mirror.
4531   phi->init_req(_prim_path, prim_return_value);
4532   if (stopped()) { set_result(region, phi); return true; }
4533   bool safe_for_replace = (region->in(_prim_path) == top());
4534 
4535   Node* p;  // handy temp
4536   Node* null_ctl;
4537 
4538   // Now that we have the non-null klass, we can perform the real query.
4539   // For constant classes, the query will constant-fold in LoadNode::Value.
4540   Node* query_value = top();
4541   switch (id) {
4542   case vmIntrinsics::_isInstance:
4543     // nothing is an instance of a primitive type
4544     query_value = gen_instanceof(obj, kls, safe_for_replace);
4545     break;
4546 
4547   case vmIntrinsics::_isHidden:
4548     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4549     if (generate_hidden_class_guard(kls, region) != nullptr)
4550       // A guard was added.  If the guard is taken, it was an hidden class.
4551       phi->add_req(intcon(1));
4552     // If we fall through, it's a plain class.
4553     query_value = intcon(0);
4554     break;
4555 
4556 
4557   case vmIntrinsics::_getSuperclass:
4558     // The rules here are somewhat unfortunate, but we can still do better
4559     // with random logic than with a JNI call.
4560     // Interfaces store null or Object as _super, but must report null.
4561     // Arrays store an intermediate super as _super, but must report Object.
4562     // Other types can report the actual _super.
4563     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4564     if (generate_interface_guard(kls, region) != nullptr)
4565       // A guard was added.  If the guard is taken, it was an interface.
4566       phi->add_req(null());
4567     if (generate_array_guard(kls, region) != nullptr)
4568       // A guard was added.  If the guard is taken, it was an array.
4569       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4570     // If we fall through, it's a plain class.  Get its _super.
4571     if (!stopped()) {
4572       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4573       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4574       null_ctl = top();
4575       kls = null_check_oop(kls, &null_ctl);
4576       if (null_ctl != top()) {
4577         // If the guard is taken, Object.superClass is null (both klass and mirror).
4578         region->add_req(null_ctl);
4579         phi   ->add_req(null());
4580       }
4581       if (!stopped()) {
4582         query_value = load_mirror_from_klass(kls);
4583       }
4584     }
4585     break;
4586 
4587   default:
4588     fatal_unexpected_iid(id);
4589     break;
4590   }
4591 
4592   // Fall-through is the normal case of a query to a real class.
4593   phi->init_req(1, query_value);
4594   region->init_req(1, control());
4595 
4596   C->set_has_split_ifs(true); // Has chance for split-if optimization
4597   set_result(region, phi);
4598   return true;
4599 }
4600 
4601 
4602 //-------------------------inline_Class_cast-------------------
4603 bool LibraryCallKit::inline_Class_cast() {
4604   Node* mirror = argument(0); // Class
4605   Node* obj    = argument(1);
4606   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4607   if (mirror_con == nullptr) {
4608     return false;  // dead path (mirror->is_top()).
4609   }
4610   if (obj == nullptr || obj->is_top()) {
4611     return false;  // dead path
4612   }
4613   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4614 
4615   // First, see if Class.cast() can be folded statically.
4616   // java_mirror_type() returns non-null for compile-time Class constants.
4617   ciType* tm = mirror_con->java_mirror_type();
4618   if (tm != nullptr && tm->is_klass() &&
4619       tp != nullptr) {
4620     if (!tp->is_loaded()) {
4621       // Don't use intrinsic when class is not loaded.
4622       return false;
4623     } else {
4624       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4625       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4626       if (static_res == Compile::SSC_always_true) {
4627         // isInstance() is true - fold the code.
4628         set_result(obj);
4629         return true;
4630       } else if (static_res == Compile::SSC_always_false) {
4631         // Don't use intrinsic, have to throw ClassCastException.
4632         // If the reference is null, the non-intrinsic bytecode will
4633         // be optimized appropriately.
4634         return false;
4635       }
4636     }
4637   }
4638 
4639   // Bailout intrinsic and do normal inlining if exception path is frequent.
4640   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4641     return false;
4642   }
4643 
4644   // Generate dynamic checks.
4645   // Class.cast() is java implementation of _checkcast bytecode.
4646   // Do checkcast (Parse::do_checkcast()) optimizations here.
4647 
4648   mirror = null_check(mirror);
4649   // If mirror is dead, only null-path is taken.
4650   if (stopped()) {
4651     return true;
4652   }
4653 
4654   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4655   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4656   RegionNode* region = new RegionNode(PATH_LIMIT);
4657   record_for_igvn(region);
4658 
4659   // Now load the mirror's klass metaobject, and null-check it.
4660   // If kls is null, we have a primitive mirror and
4661   // nothing is an instance of a primitive type.
4662   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4663 
4664   Node* res = top();
4665   Node* io = i_o();
4666   Node* mem = merged_memory();
4667   if (!stopped()) {
4668 
4669     Node* bad_type_ctrl = top();
4670     // Do checkcast optimizations.
4671     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4672     region->init_req(_bad_type_path, bad_type_ctrl);
4673   }
4674   if (region->in(_prim_path) != top() ||
4675       region->in(_bad_type_path) != top() ||
4676       region->in(_npe_path) != top()) {
4677     // Let Interpreter throw ClassCastException.
4678     PreserveJVMState pjvms(this);
4679     set_control(_gvn.transform(region));
4680     // Set IO and memory because gen_checkcast may override them when buffering inline types
4681     set_i_o(io);
4682     set_all_memory(mem);
4683     uncommon_trap(Deoptimization::Reason_intrinsic,
4684                   Deoptimization::Action_maybe_recompile);
4685   }
4686   if (!stopped()) {
4687     set_result(res);
4688   }
4689   return true;
4690 }
4691 
4692 
4693 //--------------------------inline_native_subtype_check------------------------
4694 // This intrinsic takes the JNI calls out of the heart of
4695 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4696 bool LibraryCallKit::inline_native_subtype_check() {
4697   // Pull both arguments off the stack.
4698   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4699   args[0] = argument(0);
4700   args[1] = argument(1);
4701   Node* klasses[2];             // corresponding Klasses: superk, subk
4702   klasses[0] = klasses[1] = top();
4703 
4704   enum {
4705     // A full decision tree on {superc is prim, subc is prim}:
4706     _prim_0_path = 1,           // {P,N} => false
4707                                 // {P,P} & superc!=subc => false
4708     _prim_same_path,            // {P,P} & superc==subc => true
4709     _prim_1_path,               // {N,P} => false
4710     _ref_subtype_path,          // {N,N} & subtype check wins => true
4711     _both_ref_path,             // {N,N} & subtype check loses => false
4712     PATH_LIMIT
4713   };
4714 
4715   RegionNode* region = new RegionNode(PATH_LIMIT);
4716   RegionNode* prim_region = new RegionNode(2);
4717   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4718   record_for_igvn(region);
4719   record_for_igvn(prim_region);
4720 
4721   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4722   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4723   int class_klass_offset = java_lang_Class::klass_offset();
4724 
4725   // First null-check both mirrors and load each mirror's klass metaobject.
4726   int which_arg;
4727   for (which_arg = 0; which_arg <= 1; which_arg++) {
4728     Node* arg = args[which_arg];
4729     arg = null_check(arg);
4730     if (stopped())  break;
4731     args[which_arg] = arg;
4732 
4733     Node* p = basic_plus_adr(arg, class_klass_offset);
4734     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4735     klasses[which_arg] = _gvn.transform(kls);
4736   }
4737 
4738   // Having loaded both klasses, test each for null.
4739   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4740   for (which_arg = 0; which_arg <= 1; which_arg++) {
4741     Node* kls = klasses[which_arg];
4742     Node* null_ctl = top();
4743     kls = null_check_oop(kls, &null_ctl, never_see_null);
4744     if (which_arg == 0) {
4745       prim_region->init_req(1, null_ctl);
4746     } else {
4747       region->init_req(_prim_1_path, null_ctl);
4748     }
4749     if (stopped())  break;
4750     klasses[which_arg] = kls;
4751   }
4752 
4753   if (!stopped()) {
4754     // now we have two reference types, in klasses[0..1]
4755     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4756     Node* superk = klasses[0];  // the receiver
4757     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4758     region->set_req(_ref_subtype_path, control());
4759   }
4760 
4761   // If both operands are primitive (both klasses null), then
4762   // we must return true when they are identical primitives.
4763   // It is convenient to test this after the first null klass check.
4764   // This path is also used if superc is a value mirror.
4765   set_control(_gvn.transform(prim_region));
4766   if (!stopped()) {
4767     // Since superc is primitive, make a guard for the superc==subc case.
4768     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4769     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4770     generate_fair_guard(bol_eq, region);
4771     if (region->req() == PATH_LIMIT+1) {
4772       // A guard was added.  If the added guard is taken, superc==subc.
4773       region->swap_edges(PATH_LIMIT, _prim_same_path);
4774       region->del_req(PATH_LIMIT);
4775     }
4776     region->set_req(_prim_0_path, control()); // Not equal after all.
4777   }
4778 
4779   // these are the only paths that produce 'true':
4780   phi->set_req(_prim_same_path,   intcon(1));
4781   phi->set_req(_ref_subtype_path, intcon(1));
4782 
4783   // pull together the cases:
4784   assert(region->req() == PATH_LIMIT, "sane region");
4785   for (uint i = 1; i < region->req(); i++) {
4786     Node* ctl = region->in(i);
4787     if (ctl == nullptr || ctl == top()) {
4788       region->set_req(i, top());
4789       phi   ->set_req(i, top());
4790     } else if (phi->in(i) == nullptr) {
4791       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4792     }
4793   }
4794 
4795   set_control(_gvn.transform(region));
4796   set_result(_gvn.transform(phi));
4797   return true;
4798 }
4799 
4800 //---------------------generate_array_guard_common------------------------
4801 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4802 
4803   if (stopped()) {
4804     return nullptr;
4805   }
4806 
4807   // Like generate_guard, adds a new path onto the region.
4808   jint  layout_con = 0;
4809   Node* layout_val = get_layout_helper(kls, layout_con);
4810   if (layout_val == nullptr) {
4811     bool query = 0;
4812     switch(kind) {
4813       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4814       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4815       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4816       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4817       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4818       default:
4819         ShouldNotReachHere();
4820     }
4821     if (!query) {
4822       return nullptr;                       // never a branch
4823     } else {                             // always a branch
4824       Node* always_branch = control();
4825       if (region != nullptr)
4826         region->add_req(always_branch);
4827       set_control(top());
4828       return always_branch;
4829     }
4830   }
4831   unsigned int value = 0;
4832   BoolTest::mask btest = BoolTest::illegal;
4833   switch(kind) {
4834     case RefArray:
4835     case NonRefArray: {
4836       value = Klass::_lh_array_tag_ref_value;
4837       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4838       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4839       break;
4840     }
4841     case TypeArray: {
4842       value = Klass::_lh_array_tag_type_value;
4843       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4844       btest = BoolTest::eq;
4845       break;
4846     }
4847     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4848     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4849     default:
4850       ShouldNotReachHere();
4851   }
4852   // Now test the correct condition.
4853   jint nval = (jint)value;
4854   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4855   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4856   Node* ctrl = generate_fair_guard(bol, region);
4857   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4858   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4859     // Keep track of the fact that 'obj' is an array to prevent
4860     // array specific accesses from floating above the guard.
4861     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4862   }
4863   return ctrl;
4864 }
4865 
4866 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4867 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4868 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4869 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4870   assert(null_free || atomic, "nullable implies atomic");
4871   Node* componentType = argument(0);
4872   Node* length = argument(1);
4873   Node* init_val = null_free ? argument(2) : nullptr;
4874 
4875   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4876   if (tp != nullptr) {
4877     ciInstanceKlass* ik = tp->instance_klass();
4878     if (ik == C->env()->Class_klass()) {
4879       ciType* t = tp->java_mirror_type();
4880       if (t != nullptr && t->is_inlinetype()) {
4881 
4882         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4883         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4884         assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4885 
4886         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4887         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4888           return false;
4889         }
4890 
4891         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4892           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4893           if (null_free) {
4894             if (init_val->is_InlineType()) {
4895               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4896                 // Zeroing is enough because the init value is the all-zero value
4897                 init_val = nullptr;
4898               } else {
4899                 init_val = init_val->as_InlineType()->buffer(this);
4900               }
4901             }
4902             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4903           }
4904           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4905           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4906           assert(arytype->is_null_free() == null_free, "inconsistency");
4907           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4908           assert(arytype->is_atomic() == atomic, "inconsistency");
4909           set_result(obj);
4910           return true;
4911         }
4912       }
4913     }
4914   }
4915   return false;
4916 }
4917 
4918 // public static native boolean ValueClass::isFlatArray(Object array);
4919 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4920 // public static native boolean ValueClass::isAtomicArray(Object array);
4921 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4922   Node* array = argument(0);
4923 
4924   Node* bol;
4925   switch(check) {
4926     case IsFlat:
4927       // TODO 8350865 Use the object version here instead of loading the klass
4928       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4929       bol = flat_array_test(load_object_klass(array));
4930       break;
4931     case IsNullRestricted:
4932       bol = null_free_array_test(array);
4933       break;
4934     case IsAtomic:
4935       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4936       // Enable TestIntrinsics::test87/88 once this is implemented
4937       // bol = null_free_atomic_array_test
4938       return false;
4939     default:
4940       ShouldNotReachHere();
4941   }
4942 
4943   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4944   set_result(res);
4945   return true;
4946 }
4947 
4948 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4949 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4950 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4951   RegionNode* region = new RegionNode(2);
4952   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4953 
4954   if (type_array_guard) {
4955     generate_typeArray_guard(klass_node, region);
4956     if (region->req() == 3) {
4957       phi->add_req(klass_node);
4958     }
4959   }
4960   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4961   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4962 
4963   // Can be null if not initialized yet, just deopt
4964   Node* null_ctl = top();
4965   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4966 
4967   region->init_req(1, control());
4968   phi->init_req(1, refined_klass);
4969 
4970   set_control(_gvn.transform(region));
4971   return _gvn.transform(phi);
4972 }
4973 
4974 // Load the non-refined array klass from an ObjArrayKlass.
4975 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4976   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4977   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4978     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4979   }
4980 
4981   RegionNode* region = new RegionNode(2);
4982   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4983 
4984   generate_typeArray_guard(klass_node, region);
4985   if (region->req() == 3) {
4986     phi->add_req(klass_node);
4987   }
4988   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4989   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4990 
4991   region->init_req(1, control());
4992   phi->init_req(1, super_klass);
4993 
4994   set_control(_gvn.transform(region));
4995   return _gvn.transform(phi);
4996 }
4997 
4998 //-----------------------inline_native_newArray--------------------------
4999 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5000 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5001 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5002   Node* mirror;
5003   Node* count_val;
5004   if (uninitialized) {
5005     null_check_receiver();
5006     mirror    = argument(1);
5007     count_val = argument(2);
5008   } else {
5009     mirror    = argument(0);
5010     count_val = argument(1);
5011   }
5012 
5013   mirror = null_check(mirror);
5014   // If mirror or obj is dead, only null-path is taken.
5015   if (stopped())  return true;
5016 
5017   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5018   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5019   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5020   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5021   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5022 
5023   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5024   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5025                                                   result_reg, _slow_path);
5026   Node* normal_ctl   = control();
5027   Node* no_array_ctl = result_reg->in(_slow_path);
5028 
5029   // Generate code for the slow case.  We make a call to newArray().
5030   set_control(no_array_ctl);
5031   if (!stopped()) {
5032     // Either the input type is void.class, or else the
5033     // array klass has not yet been cached.  Either the
5034     // ensuing call will throw an exception, or else it
5035     // will cache the array klass for next time.
5036     PreserveJVMState pjvms(this);
5037     CallJavaNode* slow_call = nullptr;
5038     if (uninitialized) {
5039       // Generate optimized virtual call (holder class 'Unsafe' is final)
5040       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5041     } else {
5042       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5043     }
5044     Node* slow_result = set_results_for_java_call(slow_call);
5045     // this->control() comes from set_results_for_java_call
5046     result_reg->set_req(_slow_path, control());
5047     result_val->set_req(_slow_path, slow_result);
5048     result_io ->set_req(_slow_path, i_o());
5049     result_mem->set_req(_slow_path, reset_memory());
5050   }
5051 
5052   set_control(normal_ctl);
5053   if (!stopped()) {
5054     // Normal case:  The array type has been cached in the java.lang.Class.
5055     // The following call works fine even if the array type is polymorphic.
5056     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5057 
5058     klass_node = load_default_refined_array_klass(klass_node);
5059 
5060     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5061     result_reg->init_req(_normal_path, control());
5062     result_val->init_req(_normal_path, obj);
5063     result_io ->init_req(_normal_path, i_o());
5064     result_mem->init_req(_normal_path, reset_memory());
5065 
5066     if (uninitialized) {
5067       // Mark the allocation so that zeroing is skipped
5068       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5069       alloc->maybe_set_complete(&_gvn);
5070     }
5071   }
5072 
5073   // Return the combined state.
5074   set_i_o(        _gvn.transform(result_io)  );
5075   set_all_memory( _gvn.transform(result_mem));
5076 
5077   C->set_has_split_ifs(true); // Has chance for split-if optimization
5078   set_result(result_reg, result_val);
5079   return true;
5080 }
5081 
5082 //----------------------inline_native_getLength--------------------------
5083 // public static native int java.lang.reflect.Array.getLength(Object array);
5084 bool LibraryCallKit::inline_native_getLength() {
5085   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5086 
5087   Node* array = null_check(argument(0));
5088   // If array is dead, only null-path is taken.
5089   if (stopped())  return true;
5090 
5091   // Deoptimize if it is a non-array.
5092   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5093 
5094   if (non_array != nullptr) {
5095     PreserveJVMState pjvms(this);
5096     set_control(non_array);
5097     uncommon_trap(Deoptimization::Reason_intrinsic,
5098                   Deoptimization::Action_maybe_recompile);
5099   }
5100 
5101   // If control is dead, only non-array-path is taken.
5102   if (stopped())  return true;
5103 
5104   // The works fine even if the array type is polymorphic.
5105   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5106   Node* result = load_array_length(array);
5107 
5108   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5109   set_result(result);
5110   return true;
5111 }
5112 
5113 //------------------------inline_array_copyOf----------------------------
5114 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5115 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5116 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5117   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5118 
5119   // Get the arguments.
5120   Node* original          = argument(0);
5121   Node* start             = is_copyOfRange? argument(1): intcon(0);
5122   Node* end               = is_copyOfRange? argument(2): argument(1);
5123   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5124 
5125   Node* newcopy = nullptr;
5126 
5127   // Set the original stack and the reexecute bit for the interpreter to reexecute
5128   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5129   { PreserveReexecuteState preexecs(this);
5130     jvms()->set_should_reexecute(true);
5131 
5132     array_type_mirror = null_check(array_type_mirror);
5133     original          = null_check(original);
5134 
5135     // Check if a null path was taken unconditionally.
5136     if (stopped())  return true;
5137 
5138     Node* orig_length = load_array_length(original);
5139 
5140     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5141     klass_node = null_check(klass_node);
5142 
5143     RegionNode* bailout = new RegionNode(1);
5144     record_for_igvn(bailout);
5145 
5146     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5147     // Bail out if that is so.
5148     // Inline type array may have object field that would require a
5149     // write barrier. Conservatively, go to slow path.
5150     // TODO 8251971: Optimize for the case when flat src/dst are later found
5151     // to not contain oops (i.e., move this check to the macro expansion phase).
5152     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5153     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5154     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5155     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5156                         // Can src array be flat and contain oops?
5157                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5158                         // Can dest array be flat and contain oops?
5159                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5160     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5161 
5162     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5163 
5164     if (not_objArray != nullptr) {
5165       // Improve the klass node's type from the new optimistic assumption:
5166       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5167       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5168       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5169       refined_klass_node = _gvn.transform(cast);
5170     }
5171 
5172     // Bail out if either start or end is negative.
5173     generate_negative_guard(start, bailout, &start);
5174     generate_negative_guard(end,   bailout, &end);
5175 
5176     Node* length = end;
5177     if (_gvn.type(start) != TypeInt::ZERO) {
5178       length = _gvn.transform(new SubINode(end, start));
5179     }
5180 
5181     // Bail out if length is negative (i.e., if start > end).
5182     // Without this the new_array would throw
5183     // NegativeArraySizeException but IllegalArgumentException is what
5184     // should be thrown
5185     generate_negative_guard(length, bailout, &length);
5186 
5187     // Handle inline type arrays
5188     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5189     if (!stopped()) {
5190       // TODO JDK-8329224
5191       if (!orig_t->is_null_free()) {
5192         // Not statically known to be null free, add a check
5193         generate_fair_guard(null_free_array_test(original), bailout);
5194       }
5195       orig_t = _gvn.type(original)->isa_aryptr();
5196       if (orig_t != nullptr && orig_t->is_flat()) {
5197         // Src is flat, check that dest is flat as well
5198         if (exclude_flat) {
5199           // Dest can't be flat, bail out
5200           bailout->add_req(control());
5201           set_control(top());
5202         } else {
5203           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5204         }
5205         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5206       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5207                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5208                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5209         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5210         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5211         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5212         if (orig_t != nullptr) {
5213           orig_t = orig_t->cast_to_not_flat();
5214           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5215         }
5216       }
5217       if (!can_validate) {
5218         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5219         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5220         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5221         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5222         generate_fair_guard(null_free_array_test(original), bailout);
5223       }
5224     }
5225 
5226     // Bail out if start is larger than the original length
5227     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5228     generate_negative_guard(orig_tail, bailout, &orig_tail);
5229 
5230     if (bailout->req() > 1) {
5231       PreserveJVMState pjvms(this);
5232       set_control(_gvn.transform(bailout));
5233       uncommon_trap(Deoptimization::Reason_intrinsic,
5234                     Deoptimization::Action_maybe_recompile);
5235     }
5236 
5237     if (!stopped()) {
5238       // How many elements will we copy from the original?
5239       // The answer is MinI(orig_tail, length).
5240       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5241 
5242       // Generate a direct call to the right arraycopy function(s).
5243       // We know the copy is disjoint but we might not know if the
5244       // oop stores need checking.
5245       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5246       // This will fail a store-check if x contains any non-nulls.
5247 
5248       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5249       // loads/stores but it is legal only if we're sure the
5250       // Arrays.copyOf would succeed. So we need all input arguments
5251       // to the copyOf to be validated, including that the copy to the
5252       // new array won't trigger an ArrayStoreException. That subtype
5253       // check can be optimized if we know something on the type of
5254       // the input array from type speculation.
5255       if (_gvn.type(klass_node)->singleton()) {
5256         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5257         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5258 
5259         int test = C->static_subtype_check(superk, subk);
5260         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5261           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5262           if (t_original->speculative_type() != nullptr) {
5263             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5264           }
5265         }
5266       }
5267 
5268       bool validated = false;
5269       // Reason_class_check rather than Reason_intrinsic because we
5270       // want to intrinsify even if this traps.
5271       if (can_validate) {
5272         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5273 
5274         if (not_subtype_ctrl != top()) {
5275           PreserveJVMState pjvms(this);
5276           set_control(not_subtype_ctrl);
5277           uncommon_trap(Deoptimization::Reason_class_check,
5278                         Deoptimization::Action_make_not_entrant);
5279           assert(stopped(), "Should be stopped");
5280         }
5281         validated = true;
5282       }
5283 
5284       if (!stopped()) {
5285         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5286 
5287         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5288                                                 load_object_klass(original), klass_node);
5289         if (!is_copyOfRange) {
5290           ac->set_copyof(validated);
5291         } else {
5292           ac->set_copyofrange(validated);
5293         }
5294         Node* n = _gvn.transform(ac);
5295         if (n == ac) {
5296           ac->connect_outputs(this);
5297         } else {
5298           assert(validated, "shouldn't transform if all arguments not validated");
5299           set_all_memory(n);
5300         }
5301       }
5302     }
5303   } // original reexecute is set back here
5304 
5305   C->set_has_split_ifs(true); // Has chance for split-if optimization
5306   if (!stopped()) {
5307     set_result(newcopy);
5308   }
5309   return true;
5310 }
5311 
5312 
5313 //----------------------generate_virtual_guard---------------------------
5314 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5315 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5316                                              RegionNode* slow_region) {
5317   ciMethod* method = callee();
5318   int vtable_index = method->vtable_index();
5319   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5320          "bad index %d", vtable_index);
5321   // Get the Method* out of the appropriate vtable entry.
5322   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5323                      vtable_index*vtableEntry::size_in_bytes() +
5324                      in_bytes(vtableEntry::method_offset());
5325   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5326   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5327 
5328   // Compare the target method with the expected method (e.g., Object.hashCode).
5329   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5330 
5331   Node* native_call = makecon(native_call_addr);
5332   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5333   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5334 
5335   return generate_slow_guard(test_native, slow_region);
5336 }
5337 
5338 //-----------------------generate_method_call----------------------------
5339 // Use generate_method_call to make a slow-call to the real
5340 // method if the fast path fails.  An alternative would be to
5341 // use a stub like OptoRuntime::slow_arraycopy_Java.
5342 // This only works for expanding the current library call,
5343 // not another intrinsic.  (E.g., don't use this for making an
5344 // arraycopy call inside of the copyOf intrinsic.)
5345 CallJavaNode*
5346 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5347   // When compiling the intrinsic method itself, do not use this technique.
5348   guarantee(callee() != C->method(), "cannot make slow-call to self");
5349 
5350   ciMethod* method = callee();
5351   // ensure the JVMS we have will be correct for this call
5352   guarantee(method_id == method->intrinsic_id(), "must match");
5353 
5354   const TypeFunc* tf = TypeFunc::make(method);
5355   if (res_not_null) {
5356     assert(tf->return_type() == T_OBJECT, "");
5357     const TypeTuple* range = tf->range_cc();
5358     const Type** fields = TypeTuple::fields(range->cnt());
5359     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5360     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5361     tf = TypeFunc::make(tf->domain_cc(), new_range);
5362   }
5363   CallJavaNode* slow_call;
5364   if (is_static) {
5365     assert(!is_virtual, "");
5366     slow_call = new CallStaticJavaNode(C, tf,
5367                            SharedRuntime::get_resolve_static_call_stub(), method);
5368   } else if (is_virtual) {
5369     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5370     int vtable_index = Method::invalid_vtable_index;
5371     if (UseInlineCaches) {
5372       // Suppress the vtable call
5373     } else {
5374       // hashCode and clone are not a miranda methods,
5375       // so the vtable index is fixed.
5376       // No need to use the linkResolver to get it.
5377        vtable_index = method->vtable_index();
5378        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5379               "bad index %d", vtable_index);
5380     }
5381     slow_call = new CallDynamicJavaNode(tf,
5382                           SharedRuntime::get_resolve_virtual_call_stub(),
5383                           method, vtable_index);
5384   } else {  // neither virtual nor static:  opt_virtual
5385     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5386     slow_call = new CallStaticJavaNode(C, tf,
5387                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5388     slow_call->set_optimized_virtual(true);
5389   }
5390   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5391     // To be able to issue a direct call (optimized virtual or virtual)
5392     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5393     // about the method being invoked should be attached to the call site to
5394     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5395     slow_call->set_override_symbolic_info(true);
5396   }
5397   set_arguments_for_java_call(slow_call);
5398   set_edges_for_java_call(slow_call);
5399   return slow_call;
5400 }
5401 
5402 
5403 /**
5404  * Build special case code for calls to hashCode on an object. This call may
5405  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5406  * slightly different code.
5407  */
5408 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5409   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5410   assert(!(is_virtual && is_static), "either virtual, special, or static");
5411 
5412   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5413 
5414   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5415   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5416   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5417   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5418   Node* obj = argument(0);
5419 
5420   // Don't intrinsify hashcode on inline types for now.
5421   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5422   if (gvn().type(obj)->is_inlinetypeptr()) {
5423     return false;
5424   }
5425 
5426   if (!is_static) {
5427     // Check for hashing null object
5428     obj = null_check_receiver();
5429     if (stopped())  return true;        // unconditionally null
5430     result_reg->init_req(_null_path, top());
5431     result_val->init_req(_null_path, top());
5432   } else {
5433     // Do a null check, and return zero if null.
5434     // System.identityHashCode(null) == 0
5435     Node* null_ctl = top();
5436     obj = null_check_oop(obj, &null_ctl);
5437     result_reg->init_req(_null_path, null_ctl);
5438     result_val->init_req(_null_path, _gvn.intcon(0));
5439   }
5440 
5441   // Unconditionally null?  Then return right away.
5442   if (stopped()) {
5443     set_control( result_reg->in(_null_path));
5444     if (!stopped())
5445       set_result(result_val->in(_null_path));
5446     return true;
5447   }
5448 
5449   // We only go to the fast case code if we pass a number of guards.  The
5450   // paths which do not pass are accumulated in the slow_region.
5451   RegionNode* slow_region = new RegionNode(1);
5452   record_for_igvn(slow_region);
5453 
5454   // If this is a virtual call, we generate a funny guard.  We pull out
5455   // the vtable entry corresponding to hashCode() from the target object.
5456   // If the target method which we are calling happens to be the native
5457   // Object hashCode() method, we pass the guard.  We do not need this
5458   // guard for non-virtual calls -- the caller is known to be the native
5459   // Object hashCode().
5460   if (is_virtual) {
5461     // After null check, get the object's klass.
5462     Node* obj_klass = load_object_klass(obj);
5463     generate_virtual_guard(obj_klass, slow_region);
5464   }
5465 
5466   // Get the header out of the object, use LoadMarkNode when available
5467   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5468   // The control of the load must be null. Otherwise, the load can move before
5469   // the null check after castPP removal.
5470   Node* no_ctrl = nullptr;
5471   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5472 
5473   if (!UseObjectMonitorTable) {
5474     // Test the header to see if it is safe to read w.r.t. locking.
5475     // We cannot use the inline type mask as this may check bits that are overriden
5476     // by an object monitor's pointer when inflating locking.
5477     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5478     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5479     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5480     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5481     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5482 
5483     generate_slow_guard(test_monitor, slow_region);
5484   }
5485 
5486   // Get the hash value and check to see that it has been properly assigned.
5487   // We depend on hash_mask being at most 32 bits and avoid the use of
5488   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5489   // vm: see markWord.hpp.
5490   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5491   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5492   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5493   // This hack lets the hash bits live anywhere in the mark object now, as long
5494   // as the shift drops the relevant bits into the low 32 bits.  Note that
5495   // Java spec says that HashCode is an int so there's no point in capturing
5496   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5497   hshifted_header      = ConvX2I(hshifted_header);
5498   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5499 
5500   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5501   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5502   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5503 
5504   generate_slow_guard(test_assigned, slow_region);
5505 
5506   Node* init_mem = reset_memory();
5507   // fill in the rest of the null path:
5508   result_io ->init_req(_null_path, i_o());
5509   result_mem->init_req(_null_path, init_mem);
5510 
5511   result_val->init_req(_fast_path, hash_val);
5512   result_reg->init_req(_fast_path, control());
5513   result_io ->init_req(_fast_path, i_o());
5514   result_mem->init_req(_fast_path, init_mem);
5515 
5516   // Generate code for the slow case.  We make a call to hashCode().
5517   set_control(_gvn.transform(slow_region));
5518   if (!stopped()) {
5519     // No need for PreserveJVMState, because we're using up the present state.
5520     set_all_memory(init_mem);
5521     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5522     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5523     Node* slow_result = set_results_for_java_call(slow_call);
5524     // this->control() comes from set_results_for_java_call
5525     result_reg->init_req(_slow_path, control());
5526     result_val->init_req(_slow_path, slow_result);
5527     result_io  ->set_req(_slow_path, i_o());
5528     result_mem ->set_req(_slow_path, reset_memory());
5529   }
5530 
5531   // Return the combined state.
5532   set_i_o(        _gvn.transform(result_io)  );
5533   set_all_memory( _gvn.transform(result_mem));
5534 
5535   set_result(result_reg, result_val);
5536   return true;
5537 }
5538 
5539 //---------------------------inline_native_getClass----------------------------
5540 // public final native Class<?> java.lang.Object.getClass();
5541 //
5542 // Build special case code for calls to getClass on an object.
5543 bool LibraryCallKit::inline_native_getClass() {
5544   Node* obj = argument(0);
5545   if (obj->is_InlineType()) {
5546     const Type* t = _gvn.type(obj);
5547     if (t->maybe_null()) {
5548       null_check(obj);
5549     }
5550     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5551     return true;
5552   }
5553   obj = null_check_receiver();
5554   if (stopped())  return true;
5555   set_result(load_mirror_from_klass(load_object_klass(obj)));
5556   return true;
5557 }
5558 
5559 //-----------------inline_native_Reflection_getCallerClass---------------------
5560 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5561 //
5562 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5563 //
5564 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5565 // in that it must skip particular security frames and checks for
5566 // caller sensitive methods.
5567 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5568 #ifndef PRODUCT
5569   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5570     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5571   }
5572 #endif
5573 
5574   if (!jvms()->has_method()) {
5575 #ifndef PRODUCT
5576     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5577       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5578     }
5579 #endif
5580     return false;
5581   }
5582 
5583   // Walk back up the JVM state to find the caller at the required
5584   // depth.
5585   JVMState* caller_jvms = jvms();
5586 
5587   // Cf. JVM_GetCallerClass
5588   // NOTE: Start the loop at depth 1 because the current JVM state does
5589   // not include the Reflection.getCallerClass() frame.
5590   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5591     ciMethod* m = caller_jvms->method();
5592     switch (n) {
5593     case 0:
5594       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5595       break;
5596     case 1:
5597       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5598       if (!m->caller_sensitive()) {
5599 #ifndef PRODUCT
5600         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5601           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5602         }
5603 #endif
5604         return false;  // bail-out; let JVM_GetCallerClass do the work
5605       }
5606       break;
5607     default:
5608       if (!m->is_ignored_by_security_stack_walk()) {
5609         // We have reached the desired frame; return the holder class.
5610         // Acquire method holder as java.lang.Class and push as constant.
5611         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5612         ciInstance* caller_mirror = caller_klass->java_mirror();
5613         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5614 
5615 #ifndef PRODUCT
5616         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5617           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());
5618           tty->print_cr("  JVM state at this point:");
5619           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5620             ciMethod* m = jvms()->of_depth(i)->method();
5621             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5622           }
5623         }
5624 #endif
5625         return true;
5626       }
5627       break;
5628     }
5629   }
5630 
5631 #ifndef PRODUCT
5632   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5633     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5634     tty->print_cr("  JVM state at this point:");
5635     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5636       ciMethod* m = jvms()->of_depth(i)->method();
5637       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5638     }
5639   }
5640 #endif
5641 
5642   return false;  // bail-out; let JVM_GetCallerClass do the work
5643 }
5644 
5645 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5646   Node* arg = argument(0);
5647   Node* result = nullptr;
5648 
5649   switch (id) {
5650   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5651   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5652   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5653   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5654   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5655   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5656 
5657   case vmIntrinsics::_doubleToLongBits: {
5658     // two paths (plus control) merge in a wood
5659     RegionNode *r = new RegionNode(3);
5660     Node *phi = new PhiNode(r, TypeLong::LONG);
5661 
5662     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5663     // Build the boolean node
5664     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5665 
5666     // Branch either way.
5667     // NaN case is less traveled, which makes all the difference.
5668     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5669     Node *opt_isnan = _gvn.transform(ifisnan);
5670     assert( opt_isnan->is_If(), "Expect an IfNode");
5671     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5672     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5673 
5674     set_control(iftrue);
5675 
5676     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5677     Node *slow_result = longcon(nan_bits); // return NaN
5678     phi->init_req(1, _gvn.transform( slow_result ));
5679     r->init_req(1, iftrue);
5680 
5681     // Else fall through
5682     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5683     set_control(iffalse);
5684 
5685     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5686     r->init_req(2, iffalse);
5687 
5688     // Post merge
5689     set_control(_gvn.transform(r));
5690     record_for_igvn(r);
5691 
5692     C->set_has_split_ifs(true); // Has chance for split-if optimization
5693     result = phi;
5694     assert(result->bottom_type()->isa_long(), "must be");
5695     break;
5696   }
5697 
5698   case vmIntrinsics::_floatToIntBits: {
5699     // two paths (plus control) merge in a wood
5700     RegionNode *r = new RegionNode(3);
5701     Node *phi = new PhiNode(r, TypeInt::INT);
5702 
5703     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5704     // Build the boolean node
5705     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5706 
5707     // Branch either way.
5708     // NaN case is less traveled, which makes all the difference.
5709     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5710     Node *opt_isnan = _gvn.transform(ifisnan);
5711     assert( opt_isnan->is_If(), "Expect an IfNode");
5712     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5713     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5714 
5715     set_control(iftrue);
5716 
5717     static const jint nan_bits = 0x7fc00000;
5718     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5719     phi->init_req(1, _gvn.transform( slow_result ));
5720     r->init_req(1, iftrue);
5721 
5722     // Else fall through
5723     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5724     set_control(iffalse);
5725 
5726     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5727     r->init_req(2, iffalse);
5728 
5729     // Post merge
5730     set_control(_gvn.transform(r));
5731     record_for_igvn(r);
5732 
5733     C->set_has_split_ifs(true); // Has chance for split-if optimization
5734     result = phi;
5735     assert(result->bottom_type()->isa_int(), "must be");
5736     break;
5737   }
5738 
5739   default:
5740     fatal_unexpected_iid(id);
5741     break;
5742   }
5743   set_result(_gvn.transform(result));
5744   return true;
5745 }
5746 
5747 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5748   Node* arg = argument(0);
5749   Node* result = nullptr;
5750 
5751   switch (id) {
5752   case vmIntrinsics::_floatIsInfinite:
5753     result = new IsInfiniteFNode(arg);
5754     break;
5755   case vmIntrinsics::_floatIsFinite:
5756     result = new IsFiniteFNode(arg);
5757     break;
5758   case vmIntrinsics::_doubleIsInfinite:
5759     result = new IsInfiniteDNode(arg);
5760     break;
5761   case vmIntrinsics::_doubleIsFinite:
5762     result = new IsFiniteDNode(arg);
5763     break;
5764   default:
5765     fatal_unexpected_iid(id);
5766     break;
5767   }
5768   set_result(_gvn.transform(result));
5769   return true;
5770 }
5771 
5772 //----------------------inline_unsafe_copyMemory-------------------------
5773 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5774 
5775 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5776   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5777   const Type*       base_t = gvn.type(base);
5778 
5779   bool in_native = (base_t == TypePtr::NULL_PTR);
5780   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5781   bool is_mixed  = !in_heap && !in_native;
5782 
5783   if (is_mixed) {
5784     return true; // mixed accesses can touch both on-heap and off-heap memory
5785   }
5786   if (in_heap) {
5787     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5788     if (!is_prim_array) {
5789       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5790       // there's not enough type information available to determine proper memory slice for it.
5791       return true;
5792     }
5793   }
5794   return false;
5795 }
5796 
5797 bool LibraryCallKit::inline_unsafe_copyMemory() {
5798   if (callee()->is_static())  return false;  // caller must have the capability!
5799   null_check_receiver();  // null-check receiver
5800   if (stopped())  return true;
5801 
5802   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5803 
5804   Node* src_base =         argument(1);  // type: oop
5805   Node* src_off  = ConvL2X(argument(2)); // type: long
5806   Node* dst_base =         argument(4);  // type: oop
5807   Node* dst_off  = ConvL2X(argument(5)); // type: long
5808   Node* size     = ConvL2X(argument(7)); // type: long
5809 
5810   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5811          "fieldOffset must be byte-scaled");
5812 
5813   Node* src_addr = make_unsafe_address(src_base, src_off);
5814   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5815 
5816   Node* thread = _gvn.transform(new ThreadLocalNode());
5817   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5818   BasicType doing_unsafe_access_bt = T_BYTE;
5819   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5820 
5821   // update volatile field
5822   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5823 
5824   int flags = RC_LEAF | RC_NO_FP;
5825 
5826   const TypePtr* dst_type = TypePtr::BOTTOM;
5827 
5828   // Adjust memory effects of the runtime call based on input values.
5829   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5830       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5831     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5832 
5833     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5834     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5835       flags |= RC_NARROW_MEM; // narrow in memory
5836     }
5837   }
5838 
5839   // Call it.  Note that the length argument is not scaled.
5840   make_runtime_call(flags,
5841                     OptoRuntime::fast_arraycopy_Type(),
5842                     StubRoutines::unsafe_arraycopy(),
5843                     "unsafe_arraycopy",
5844                     dst_type,
5845                     src_addr, dst_addr, size XTOP);
5846 
5847   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5848 
5849   return true;
5850 }
5851 
5852 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5853 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5854 bool LibraryCallKit::inline_unsafe_setMemory() {
5855   if (callee()->is_static())  return false;  // caller must have the capability!
5856   null_check_receiver();  // null-check receiver
5857   if (stopped())  return true;
5858 
5859   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5860 
5861   Node* dst_base =         argument(1);  // type: oop
5862   Node* dst_off  = ConvL2X(argument(2)); // type: long
5863   Node* size     = ConvL2X(argument(4)); // type: long
5864   Node* byte     =         argument(6);  // type: byte
5865 
5866   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5867          "fieldOffset must be byte-scaled");
5868 
5869   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5870 
5871   Node* thread = _gvn.transform(new ThreadLocalNode());
5872   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5873   BasicType doing_unsafe_access_bt = T_BYTE;
5874   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5875 
5876   // update volatile field
5877   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5878 
5879   int flags = RC_LEAF | RC_NO_FP;
5880 
5881   const TypePtr* dst_type = TypePtr::BOTTOM;
5882 
5883   // Adjust memory effects of the runtime call based on input values.
5884   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5885     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5886 
5887     flags |= RC_NARROW_MEM; // narrow in memory
5888   }
5889 
5890   // Call it.  Note that the length argument is not scaled.
5891   make_runtime_call(flags,
5892                     OptoRuntime::unsafe_setmemory_Type(),
5893                     StubRoutines::unsafe_setmemory(),
5894                     "unsafe_setmemory",
5895                     dst_type,
5896                     dst_addr, size XTOP, byte);
5897 
5898   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5899 
5900   return true;
5901 }
5902 
5903 #undef XTOP
5904 
5905 //------------------------clone_coping-----------------------------------
5906 // Helper function for inline_native_clone.
5907 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5908   assert(obj_size != nullptr, "");
5909   Node* raw_obj = alloc_obj->in(1);
5910   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5911 
5912   AllocateNode* alloc = nullptr;
5913   if (ReduceBulkZeroing &&
5914       // If we are implementing an array clone without knowing its source type
5915       // (can happen when compiling the array-guarded branch of a reflective
5916       // Object.clone() invocation), initialize the array within the allocation.
5917       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5918       // to a runtime clone call that assumes fully initialized source arrays.
5919       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5920     // We will be completely responsible for initializing this object -
5921     // mark Initialize node as complete.
5922     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5923     // The object was just allocated - there should be no any stores!
5924     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5925     // Mark as complete_with_arraycopy so that on AllocateNode
5926     // expansion, we know this AllocateNode is initialized by an array
5927     // copy and a StoreStore barrier exists after the array copy.
5928     alloc->initialization()->set_complete_with_arraycopy();
5929   }
5930 
5931   Node* size = _gvn.transform(obj_size);
5932   access_clone(obj, alloc_obj, size, is_array);
5933 
5934   // Do not let reads from the cloned object float above the arraycopy.
5935   if (alloc != nullptr) {
5936     // Do not let stores that initialize this object be reordered with
5937     // a subsequent store that would make this object accessible by
5938     // other threads.
5939     // Record what AllocateNode this StoreStore protects so that
5940     // escape analysis can go from the MemBarStoreStoreNode to the
5941     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5942     // based on the escape status of the AllocateNode.
5943     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5944   } else {
5945     insert_mem_bar(Op_MemBarCPUOrder);
5946   }
5947 }
5948 
5949 //------------------------inline_native_clone----------------------------
5950 // protected native Object java.lang.Object.clone();
5951 //
5952 // Here are the simple edge cases:
5953 //  null receiver => normal trap
5954 //  virtual and clone was overridden => slow path to out-of-line clone
5955 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5956 //
5957 // The general case has two steps, allocation and copying.
5958 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5959 //
5960 // Copying also has two cases, oop arrays and everything else.
5961 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5962 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5963 //
5964 // These steps fold up nicely if and when the cloned object's klass
5965 // can be sharply typed as an object array, a type array, or an instance.
5966 //
5967 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5968   PhiNode* result_val;
5969 
5970   // Set the reexecute bit for the interpreter to reexecute
5971   // the bytecode that invokes Object.clone if deoptimization happens.
5972   { PreserveReexecuteState preexecs(this);
5973     jvms()->set_should_reexecute(true);
5974 
5975     Node* obj = argument(0);
5976     obj = null_check_receiver();
5977     if (stopped())  return true;
5978 
5979     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5980     if (obj_type->is_inlinetypeptr()) {
5981       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5982       // no identity.
5983       set_result(obj);
5984       return true;
5985     }
5986 
5987     // If we are going to clone an instance, we need its exact type to
5988     // know the number and types of fields to convert the clone to
5989     // loads/stores. Maybe a speculative type can help us.
5990     if (!obj_type->klass_is_exact() &&
5991         obj_type->speculative_type() != nullptr &&
5992         obj_type->speculative_type()->is_instance_klass() &&
5993         !obj_type->speculative_type()->is_inlinetype()) {
5994       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5995       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5996           !spec_ik->has_injected_fields()) {
5997         if (!obj_type->isa_instptr() ||
5998             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5999           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6000         }
6001       }
6002     }
6003 
6004     // Conservatively insert a memory barrier on all memory slices.
6005     // Do not let writes into the original float below the clone.
6006     insert_mem_bar(Op_MemBarCPUOrder);
6007 
6008     // paths into result_reg:
6009     enum {
6010       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6011       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6012       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6013       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6014       PATH_LIMIT
6015     };
6016     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6017     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6018     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6019     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6020     record_for_igvn(result_reg);
6021 
6022     Node* obj_klass = load_object_klass(obj);
6023     // We only go to the fast case code if we pass a number of guards.
6024     // The paths which do not pass are accumulated in the slow_region.
6025     RegionNode* slow_region = new RegionNode(1);
6026     record_for_igvn(slow_region);
6027 
6028     Node* array_obj = obj;
6029     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6030     if (array_ctl != nullptr) {
6031       // It's an array.
6032       PreserveJVMState pjvms(this);
6033       set_control(array_ctl);
6034 
6035       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6036       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6037       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6038           obj_type->can_be_inline_array() &&
6039           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6040         // Flat inline type array may have object field that would require a
6041         // write barrier. Conservatively, go to slow path.
6042         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6043       }
6044 
6045       if (!stopped()) {
6046         Node* obj_length = load_array_length(array_obj);
6047         Node* array_size = nullptr; // Size of the array without object alignment padding.
6048         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6049 
6050         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6051         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6052           // If it is an oop array, it requires very special treatment,
6053           // because gc barriers are required when accessing the array.
6054           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6055           if (is_obja != nullptr) {
6056             PreserveJVMState pjvms2(this);
6057             set_control(is_obja);
6058             // Generate a direct call to the right arraycopy function(s).
6059             // Clones are always tightly coupled.
6060             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6061             ac->set_clone_oop_array();
6062             Node* n = _gvn.transform(ac);
6063             assert(n == ac, "cannot disappear");
6064             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6065 
6066             result_reg->init_req(_objArray_path, control());
6067             result_val->init_req(_objArray_path, alloc_obj);
6068             result_i_o ->set_req(_objArray_path, i_o());
6069             result_mem ->set_req(_objArray_path, reset_memory());
6070           }
6071         }
6072         // Otherwise, there are no barriers to worry about.
6073         // (We can dispense with card marks if we know the allocation
6074         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6075         //  causes the non-eden paths to take compensating steps to
6076         //  simulate a fresh allocation, so that no further
6077         //  card marks are required in compiled code to initialize
6078         //  the object.)
6079 
6080         if (!stopped()) {
6081           copy_to_clone(obj, alloc_obj, array_size, true);
6082 
6083           // Present the results of the copy.
6084           result_reg->init_req(_array_path, control());
6085           result_val->init_req(_array_path, alloc_obj);
6086           result_i_o ->set_req(_array_path, i_o());
6087           result_mem ->set_req(_array_path, reset_memory());
6088         }
6089       }
6090     }
6091 
6092     if (!stopped()) {
6093       // It's an instance (we did array above).  Make the slow-path tests.
6094       // If this is a virtual call, we generate a funny guard.  We grab
6095       // the vtable entry corresponding to clone() from the target object.
6096       // If the target method which we are calling happens to be the
6097       // Object clone() method, we pass the guard.  We do not need this
6098       // guard for non-virtual calls; the caller is known to be the native
6099       // Object clone().
6100       if (is_virtual) {
6101         generate_virtual_guard(obj_klass, slow_region);
6102       }
6103 
6104       // The object must be easily cloneable and must not have a finalizer.
6105       // Both of these conditions may be checked in a single test.
6106       // We could optimize the test further, but we don't care.
6107       generate_misc_flags_guard(obj_klass,
6108                                 // Test both conditions:
6109                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6110                                 // Must be cloneable but not finalizer:
6111                                 KlassFlags::_misc_is_cloneable_fast,
6112                                 slow_region);
6113     }
6114 
6115     if (!stopped()) {
6116       // It's an instance, and it passed the slow-path tests.
6117       PreserveJVMState pjvms(this);
6118       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6119       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6120       // is reexecuted if deoptimization occurs and there could be problems when merging
6121       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6122       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6123 
6124       copy_to_clone(obj, alloc_obj, obj_size, false);
6125 
6126       // Present the results of the slow call.
6127       result_reg->init_req(_instance_path, control());
6128       result_val->init_req(_instance_path, alloc_obj);
6129       result_i_o ->set_req(_instance_path, i_o());
6130       result_mem ->set_req(_instance_path, reset_memory());
6131     }
6132 
6133     // Generate code for the slow case.  We make a call to clone().
6134     set_control(_gvn.transform(slow_region));
6135     if (!stopped()) {
6136       PreserveJVMState pjvms(this);
6137       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6138       // We need to deoptimize on exception (see comment above)
6139       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6140       // this->control() comes from set_results_for_java_call
6141       result_reg->init_req(_slow_path, control());
6142       result_val->init_req(_slow_path, slow_result);
6143       result_i_o ->set_req(_slow_path, i_o());
6144       result_mem ->set_req(_slow_path, reset_memory());
6145     }
6146 
6147     // Return the combined state.
6148     set_control(    _gvn.transform(result_reg));
6149     set_i_o(        _gvn.transform(result_i_o));
6150     set_all_memory( _gvn.transform(result_mem));
6151   } // original reexecute is set back here
6152 
6153   set_result(_gvn.transform(result_val));
6154   return true;
6155 }
6156 
6157 // If we have a tightly coupled allocation, the arraycopy may take care
6158 // of the array initialization. If one of the guards we insert between
6159 // the allocation and the arraycopy causes a deoptimization, an
6160 // uninitialized array will escape the compiled method. To prevent that
6161 // we set the JVM state for uncommon traps between the allocation and
6162 // the arraycopy to the state before the allocation so, in case of
6163 // deoptimization, we'll reexecute the allocation and the
6164 // initialization.
6165 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6166   if (alloc != nullptr) {
6167     ciMethod* trap_method = alloc->jvms()->method();
6168     int trap_bci = alloc->jvms()->bci();
6169 
6170     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6171         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6172       // Make sure there's no store between the allocation and the
6173       // arraycopy otherwise visible side effects could be rexecuted
6174       // in case of deoptimization and cause incorrect execution.
6175       bool no_interfering_store = true;
6176       Node* mem = alloc->in(TypeFunc::Memory);
6177       if (mem->is_MergeMem()) {
6178         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6179           Node* n = mms.memory();
6180           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6181             assert(n->is_Store(), "what else?");
6182             no_interfering_store = false;
6183             break;
6184           }
6185         }
6186       } else {
6187         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6188           Node* n = mms.memory();
6189           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6190             assert(n->is_Store(), "what else?");
6191             no_interfering_store = false;
6192             break;
6193           }
6194         }
6195       }
6196 
6197       if (no_interfering_store) {
6198         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6199 
6200         JVMState* saved_jvms = jvms();
6201         saved_reexecute_sp = _reexecute_sp;
6202 
6203         set_jvms(sfpt->jvms());
6204         _reexecute_sp = jvms()->sp();
6205 
6206         return saved_jvms;
6207       }
6208     }
6209   }
6210   return nullptr;
6211 }
6212 
6213 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6214 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6215 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6216   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6217   uint size = alloc->req();
6218   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6219   old_jvms->set_map(sfpt);
6220   for (uint i = 0; i < size; i++) {
6221     sfpt->init_req(i, alloc->in(i));
6222   }
6223   int adjustment = 1;
6224   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6225   if (ary_klass_ptr->is_null_free()) {
6226     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6227     // also requires the componentType and initVal on stack for re-execution.
6228     // Re-create and push the componentType.
6229     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6230     ciInstance* instance = klass->component_mirror_instance();
6231     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6232     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6233     adjustment++;
6234   }
6235   // re-push array length for deoptimization
6236   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6237   if (ary_klass_ptr->is_null_free()) {
6238     // Re-create and push the initVal.
6239     Node* init_val = alloc->in(AllocateNode::InitValue);
6240     if (init_val == nullptr) {
6241       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6242     } else if (UseCompressedOops) {
6243       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6244     }
6245     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6246     adjustment++;
6247   }
6248   old_jvms->set_sp(old_jvms->sp() + adjustment);
6249   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6250   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6251   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6252   old_jvms->set_should_reexecute(true);
6253 
6254   sfpt->set_i_o(map()->i_o());
6255   sfpt->set_memory(map()->memory());
6256   sfpt->set_control(map()->control());
6257   return sfpt;
6258 }
6259 
6260 // In case of a deoptimization, we restart execution at the
6261 // allocation, allocating a new array. We would leave an uninitialized
6262 // array in the heap that GCs wouldn't expect. Move the allocation
6263 // after the traps so we don't allocate the array if we
6264 // deoptimize. This is possible because tightly_coupled_allocation()
6265 // guarantees there's no observer of the allocated array at this point
6266 // and the control flow is simple enough.
6267 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6268                                                     int saved_reexecute_sp, uint new_idx) {
6269   if (saved_jvms_before_guards != nullptr && !stopped()) {
6270     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6271 
6272     assert(alloc != nullptr, "only with a tightly coupled allocation");
6273     // restore JVM state to the state at the arraycopy
6274     saved_jvms_before_guards->map()->set_control(map()->control());
6275     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6276     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6277     // If we've improved the types of some nodes (null check) while
6278     // emitting the guards, propagate them to the current state
6279     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6280     set_jvms(saved_jvms_before_guards);
6281     _reexecute_sp = saved_reexecute_sp;
6282 
6283     // Remove the allocation from above the guards
6284     CallProjections* callprojs = alloc->extract_projections(true);
6285     InitializeNode* init = alloc->initialization();
6286     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6287     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6288     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6289 
6290     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6291     // the allocation (i.e. is only valid if the allocation succeeds):
6292     // 1) replace CastIINode with AllocateArrayNode's length here
6293     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6294     //
6295     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6296     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6297     Node* init_control = init->proj_out(TypeFunc::Control);
6298     Node* alloc_length = alloc->Ideal_length();
6299 #ifdef ASSERT
6300     Node* prev_cast = nullptr;
6301 #endif
6302     for (uint i = 0; i < init_control->outcnt(); i++) {
6303       Node* init_out = init_control->raw_out(i);
6304       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6305 #ifdef ASSERT
6306         if (prev_cast == nullptr) {
6307           prev_cast = init_out;
6308         } else {
6309           if (prev_cast->cmp(*init_out) == false) {
6310             prev_cast->dump();
6311             init_out->dump();
6312             assert(false, "not equal CastIINode");
6313           }
6314         }
6315 #endif
6316         C->gvn_replace_by(init_out, alloc_length);
6317       }
6318     }
6319     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6320 
6321     // move the allocation here (after the guards)
6322     _gvn.hash_delete(alloc);
6323     alloc->set_req(TypeFunc::Control, control());
6324     alloc->set_req(TypeFunc::I_O, i_o());
6325     Node *mem = reset_memory();
6326     set_all_memory(mem);
6327     alloc->set_req(TypeFunc::Memory, mem);
6328     set_control(init->proj_out_or_null(TypeFunc::Control));
6329     set_i_o(callprojs->fallthrough_ioproj);
6330 
6331     // Update memory as done in GraphKit::set_output_for_allocation()
6332     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6333     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6334     if (ary_type->isa_aryptr() && length_type != nullptr) {
6335       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6336     }
6337     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6338     int            elemidx  = C->get_alias_index(telemref);
6339     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6340     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6341 
6342     Node* allocx = _gvn.transform(alloc);
6343     assert(allocx == alloc, "where has the allocation gone?");
6344     assert(dest->is_CheckCastPP(), "not an allocation result?");
6345 
6346     _gvn.hash_delete(dest);
6347     dest->set_req(0, control());
6348     Node* destx = _gvn.transform(dest);
6349     assert(destx == dest, "where has the allocation result gone?");
6350 
6351     array_ideal_length(alloc, ary_type, true);
6352   }
6353 }
6354 
6355 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6356 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6357 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6358 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6359 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6360 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6361 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6362                                                                        JVMState* saved_jvms_before_guards) {
6363   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6364     // There is at least one unrelated uncommon trap which needs to be replaced.
6365     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6366 
6367     JVMState* saved_jvms = jvms();
6368     const int saved_reexecute_sp = _reexecute_sp;
6369     set_jvms(sfpt->jvms());
6370     _reexecute_sp = jvms()->sp();
6371 
6372     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6373 
6374     // Restore state
6375     set_jvms(saved_jvms);
6376     _reexecute_sp = saved_reexecute_sp;
6377   }
6378 }
6379 
6380 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6381 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6382 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6383   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6384   while (if_proj->is_IfProj()) {
6385     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6386     if (uncommon_trap != nullptr) {
6387       create_new_uncommon_trap(uncommon_trap);
6388     }
6389     assert(if_proj->in(0)->is_If(), "must be If");
6390     if_proj = if_proj->in(0)->in(0);
6391   }
6392   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6393          "must have reached control projection of init node");
6394 }
6395 
6396 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6397   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6398   assert(trap_request != 0, "no valid UCT trap request");
6399   PreserveJVMState pjvms(this);
6400   set_control(uncommon_trap_call->in(0));
6401   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6402                 Deoptimization::trap_request_action(trap_request));
6403   assert(stopped(), "Should be stopped");
6404   _gvn.hash_delete(uncommon_trap_call);
6405   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6406 }
6407 
6408 // Common checks for array sorting intrinsics arguments.
6409 // Returns `true` if checks passed.
6410 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6411   // check address of the class
6412   if (elementType == nullptr || elementType->is_top()) {
6413     return false;  // dead path
6414   }
6415   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6416   if (elem_klass == nullptr) {
6417     return false;  // dead path
6418   }
6419   // java_mirror_type() returns non-null for compile-time Class constants only
6420   ciType* elem_type = elem_klass->java_mirror_type();
6421   if (elem_type == nullptr) {
6422     return false;
6423   }
6424   bt = elem_type->basic_type();
6425   // Disable the intrinsic if the CPU does not support SIMD sort
6426   if (!Matcher::supports_simd_sort(bt)) {
6427     return false;
6428   }
6429   // check address of the array
6430   if (obj == nullptr || obj->is_top()) {
6431     return false;  // dead path
6432   }
6433   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6434   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6435     return false; // failed input validation
6436   }
6437   return true;
6438 }
6439 
6440 //------------------------------inline_array_partition-----------------------
6441 bool LibraryCallKit::inline_array_partition() {
6442   address stubAddr = StubRoutines::select_array_partition_function();
6443   if (stubAddr == nullptr) {
6444     return false; // Intrinsic's stub is not implemented on this platform
6445   }
6446   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6447 
6448   // no receiver because it is a static method
6449   Node* elementType     = argument(0);
6450   Node* obj             = argument(1);
6451   Node* offset          = argument(2); // long
6452   Node* fromIndex       = argument(4);
6453   Node* toIndex         = argument(5);
6454   Node* indexPivot1     = argument(6);
6455   Node* indexPivot2     = argument(7);
6456   // PartitionOperation:  argument(8) is ignored
6457 
6458   Node* pivotIndices = nullptr;
6459   BasicType bt = T_ILLEGAL;
6460 
6461   if (!check_array_sort_arguments(elementType, obj, bt)) {
6462     return false;
6463   }
6464   null_check(obj);
6465   // If obj is dead, only null-path is taken.
6466   if (stopped()) {
6467     return true;
6468   }
6469   // Set the original stack and the reexecute bit for the interpreter to reexecute
6470   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6471   { PreserveReexecuteState preexecs(this);
6472     jvms()->set_should_reexecute(true);
6473 
6474     Node* obj_adr = make_unsafe_address(obj, offset);
6475 
6476     // create the pivotIndices array of type int and size = 2
6477     Node* size = intcon(2);
6478     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6479     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6480     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6481     guarantee(alloc != nullptr, "created above");
6482     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6483 
6484     // pass the basic type enum to the stub
6485     Node* elemType = intcon(bt);
6486 
6487     // Call the stub
6488     const char *stubName = "array_partition_stub";
6489     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6490                       stubAddr, stubName, TypePtr::BOTTOM,
6491                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6492                       indexPivot1, indexPivot2);
6493 
6494   } // original reexecute is set back here
6495 
6496   if (!stopped()) {
6497     set_result(pivotIndices);
6498   }
6499 
6500   return true;
6501 }
6502 
6503 
6504 //------------------------------inline_array_sort-----------------------
6505 bool LibraryCallKit::inline_array_sort() {
6506   address stubAddr = StubRoutines::select_arraysort_function();
6507   if (stubAddr == nullptr) {
6508     return false; // Intrinsic's stub is not implemented on this platform
6509   }
6510   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6511 
6512   // no receiver because it is a static method
6513   Node* elementType     = argument(0);
6514   Node* obj             = argument(1);
6515   Node* offset          = argument(2); // long
6516   Node* fromIndex       = argument(4);
6517   Node* toIndex         = argument(5);
6518   // SortOperation:       argument(6) is ignored
6519 
6520   BasicType bt = T_ILLEGAL;
6521 
6522   if (!check_array_sort_arguments(elementType, obj, bt)) {
6523     return false;
6524   }
6525   null_check(obj);
6526   // If obj is dead, only null-path is taken.
6527   if (stopped()) {
6528     return true;
6529   }
6530   Node* obj_adr = make_unsafe_address(obj, offset);
6531 
6532   // pass the basic type enum to the stub
6533   Node* elemType = intcon(bt);
6534 
6535   // Call the stub.
6536   const char *stubName = "arraysort_stub";
6537   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6538                     stubAddr, stubName, TypePtr::BOTTOM,
6539                     obj_adr, elemType, fromIndex, toIndex);
6540 
6541   return true;
6542 }
6543 
6544 
6545 //------------------------------inline_arraycopy-----------------------
6546 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6547 //                                                      Object dest, int destPos,
6548 //                                                      int length);
6549 bool LibraryCallKit::inline_arraycopy() {
6550   // Get the arguments.
6551   Node* src         = argument(0);  // type: oop
6552   Node* src_offset  = argument(1);  // type: int
6553   Node* dest        = argument(2);  // type: oop
6554   Node* dest_offset = argument(3);  // type: int
6555   Node* length      = argument(4);  // type: int
6556 
6557   uint new_idx = C->unique();
6558 
6559   // Check for allocation before we add nodes that would confuse
6560   // tightly_coupled_allocation()
6561   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6562 
6563   int saved_reexecute_sp = -1;
6564   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6565   // See arraycopy_restore_alloc_state() comment
6566   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6567   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6568   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6569   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6570 
6571   // The following tests must be performed
6572   // (1) src and dest are arrays.
6573   // (2) src and dest arrays must have elements of the same BasicType
6574   // (3) src and dest must not be null.
6575   // (4) src_offset must not be negative.
6576   // (5) dest_offset must not be negative.
6577   // (6) length must not be negative.
6578   // (7) src_offset + length must not exceed length of src.
6579   // (8) dest_offset + length must not exceed length of dest.
6580   // (9) each element of an oop array must be assignable
6581 
6582   // (3) src and dest must not be null.
6583   // always do this here because we need the JVM state for uncommon traps
6584   Node* null_ctl = top();
6585   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6586   assert(null_ctl->is_top(), "no null control here");
6587   dest = null_check(dest, T_ARRAY);
6588 
6589   if (!can_emit_guards) {
6590     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6591     // guards but the arraycopy node could still take advantage of a
6592     // tightly allocated allocation. tightly_coupled_allocation() is
6593     // called again to make sure it takes the null check above into
6594     // account: the null check is mandatory and if it caused an
6595     // uncommon trap to be emitted then the allocation can't be
6596     // considered tightly coupled in this context.
6597     alloc = tightly_coupled_allocation(dest);
6598   }
6599 
6600   bool validated = false;
6601 
6602   const Type* src_type  = _gvn.type(src);
6603   const Type* dest_type = _gvn.type(dest);
6604   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6605   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6606 
6607   // Do we have the type of src?
6608   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6609   // Do we have the type of dest?
6610   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6611   // Is the type for src from speculation?
6612   bool src_spec = false;
6613   // Is the type for dest from speculation?
6614   bool dest_spec = false;
6615 
6616   if ((!has_src || !has_dest) && can_emit_guards) {
6617     // We don't have sufficient type information, let's see if
6618     // speculative types can help. We need to have types for both src
6619     // and dest so that it pays off.
6620 
6621     // Do we already have or could we have type information for src
6622     bool could_have_src = has_src;
6623     // Do we already have or could we have type information for dest
6624     bool could_have_dest = has_dest;
6625 
6626     ciKlass* src_k = nullptr;
6627     if (!has_src) {
6628       src_k = src_type->speculative_type_not_null();
6629       if (src_k != nullptr && src_k->is_array_klass()) {
6630         could_have_src = true;
6631       }
6632     }
6633 
6634     ciKlass* dest_k = nullptr;
6635     if (!has_dest) {
6636       dest_k = dest_type->speculative_type_not_null();
6637       if (dest_k != nullptr && dest_k->is_array_klass()) {
6638         could_have_dest = true;
6639       }
6640     }
6641 
6642     if (could_have_src && could_have_dest) {
6643       // This is going to pay off so emit the required guards
6644       if (!has_src) {
6645         src = maybe_cast_profiled_obj(src, src_k, true);
6646         src_type  = _gvn.type(src);
6647         top_src  = src_type->isa_aryptr();
6648         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6649         src_spec = true;
6650       }
6651       if (!has_dest) {
6652         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6653         dest_type  = _gvn.type(dest);
6654         top_dest  = dest_type->isa_aryptr();
6655         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6656         dest_spec = true;
6657       }
6658     }
6659   }
6660 
6661   if (has_src && has_dest && can_emit_guards) {
6662     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6663     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6664     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6665     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6666 
6667     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6668       // If both arrays are object arrays then having the exact types
6669       // for both will remove the need for a subtype check at runtime
6670       // before the call and may make it possible to pick a faster copy
6671       // routine (without a subtype check on every element)
6672       // Do we have the exact type of src?
6673       bool could_have_src = src_spec;
6674       // Do we have the exact type of dest?
6675       bool could_have_dest = dest_spec;
6676       ciKlass* src_k = nullptr;
6677       ciKlass* dest_k = nullptr;
6678       if (!src_spec) {
6679         src_k = src_type->speculative_type_not_null();
6680         if (src_k != nullptr && src_k->is_array_klass()) {
6681           could_have_src = true;
6682         }
6683       }
6684       if (!dest_spec) {
6685         dest_k = dest_type->speculative_type_not_null();
6686         if (dest_k != nullptr && dest_k->is_array_klass()) {
6687           could_have_dest = true;
6688         }
6689       }
6690       if (could_have_src && could_have_dest) {
6691         // If we can have both exact types, emit the missing guards
6692         if (could_have_src && !src_spec) {
6693           src = maybe_cast_profiled_obj(src, src_k, true);
6694           src_type = _gvn.type(src);
6695           top_src = src_type->isa_aryptr();
6696         }
6697         if (could_have_dest && !dest_spec) {
6698           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6699           dest_type = _gvn.type(dest);
6700           top_dest = dest_type->isa_aryptr();
6701         }
6702       }
6703     }
6704   }
6705 
6706   ciMethod* trap_method = method();
6707   int trap_bci = bci();
6708   if (saved_jvms_before_guards != nullptr) {
6709     trap_method = alloc->jvms()->method();
6710     trap_bci = alloc->jvms()->bci();
6711   }
6712 
6713   bool negative_length_guard_generated = false;
6714 
6715   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6716       can_emit_guards && !src->is_top() && !dest->is_top()) {
6717     // validate arguments: enables transformation the ArrayCopyNode
6718     validated = true;
6719 
6720     RegionNode* slow_region = new RegionNode(1);
6721     record_for_igvn(slow_region);
6722 
6723     // (1) src and dest are arrays.
6724     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6725     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6726 
6727     // (2) src and dest arrays must have elements of the same BasicType
6728     // done at macro expansion or at Ideal transformation time
6729 
6730     // (4) src_offset must not be negative.
6731     generate_negative_guard(src_offset, slow_region);
6732 
6733     // (5) dest_offset must not be negative.
6734     generate_negative_guard(dest_offset, slow_region);
6735 
6736     // (7) src_offset + length must not exceed length of src.
6737     generate_limit_guard(src_offset, length,
6738                          load_array_length(src),
6739                          slow_region);
6740 
6741     // (8) dest_offset + length must not exceed length of dest.
6742     generate_limit_guard(dest_offset, length,
6743                          load_array_length(dest),
6744                          slow_region);
6745 
6746     // (6) length must not be negative.
6747     // This is also checked in generate_arraycopy() during macro expansion, but
6748     // we also have to check it here for the case where the ArrayCopyNode will
6749     // be eliminated by Escape Analysis.
6750     if (EliminateAllocations) {
6751       generate_negative_guard(length, slow_region);
6752       negative_length_guard_generated = true;
6753     }
6754 
6755     // (9) each element of an oop array must be assignable
6756     Node* dest_klass = load_object_klass(dest);
6757     Node* refined_dest_klass = dest_klass;
6758     if (src != dest) {
6759       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6760       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6761       slow_region->add_req(not_subtype_ctrl);
6762     }
6763 
6764     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6765     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6766     Node* src_klass = load_object_klass(src);
6767     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6768     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6769     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6770     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6771 
6772     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6773     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6774     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6775 
6776     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6777     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6778     generate_fair_guard(tst, slow_region);
6779 
6780     // TODO 8350865 This is too strong
6781     generate_fair_guard(flat_array_test(src), slow_region);
6782     generate_fair_guard(flat_array_test(dest), slow_region);
6783 
6784     {
6785       PreserveJVMState pjvms(this);
6786       set_control(_gvn.transform(slow_region));
6787       uncommon_trap(Deoptimization::Reason_intrinsic,
6788                     Deoptimization::Action_make_not_entrant);
6789       assert(stopped(), "Should be stopped");
6790     }
6791 
6792     const TypeKlassPtr* dest_klass_t = _gvn.type(refined_dest_klass)->is_klassptr();
6793     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6794     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6795     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6796   }
6797 
6798   if (stopped()) {
6799     return true;
6800   }
6801 
6802   Node* dest_klass = load_object_klass(dest);
6803   dest_klass = load_non_refined_array_klass(dest_klass);
6804 
6805   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6806                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6807                                           // so the compiler has a chance to eliminate them: during macro expansion,
6808                                           // we have to set their control (CastPP nodes are eliminated).
6809                                           load_object_klass(src), dest_klass,
6810                                           load_array_length(src), load_array_length(dest));
6811 
6812   ac->set_arraycopy(validated);
6813 
6814   Node* n = _gvn.transform(ac);
6815   if (n == ac) {
6816     ac->connect_outputs(this);
6817   } else {
6818     assert(validated, "shouldn't transform if all arguments not validated");
6819     set_all_memory(n);
6820   }
6821   clear_upper_avx();
6822 
6823 
6824   return true;
6825 }
6826 
6827 
6828 // Helper function which determines if an arraycopy immediately follows
6829 // an allocation, with no intervening tests or other escapes for the object.
6830 AllocateArrayNode*
6831 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6832   if (stopped())             return nullptr;  // no fast path
6833   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6834 
6835   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6836   if (alloc == nullptr)  return nullptr;
6837 
6838   Node* rawmem = memory(Compile::AliasIdxRaw);
6839   // Is the allocation's memory state untouched?
6840   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6841     // Bail out if there have been raw-memory effects since the allocation.
6842     // (Example:  There might have been a call or safepoint.)
6843     return nullptr;
6844   }
6845   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6846   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6847     return nullptr;
6848   }
6849 
6850   // There must be no unexpected observers of this allocation.
6851   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6852     Node* obs = ptr->fast_out(i);
6853     if (obs != this->map()) {
6854       return nullptr;
6855     }
6856   }
6857 
6858   // This arraycopy must unconditionally follow the allocation of the ptr.
6859   Node* alloc_ctl = ptr->in(0);
6860   Node* ctl = control();
6861   while (ctl != alloc_ctl) {
6862     // There may be guards which feed into the slow_region.
6863     // Any other control flow means that we might not get a chance
6864     // to finish initializing the allocated object.
6865     // Various low-level checks bottom out in uncommon traps. These
6866     // are considered safe since we've already checked above that
6867     // there is no unexpected observer of this allocation.
6868     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6869       assert(ctl->in(0)->is_If(), "must be If");
6870       ctl = ctl->in(0)->in(0);
6871     } else {
6872       return nullptr;
6873     }
6874   }
6875 
6876   // If we get this far, we have an allocation which immediately
6877   // precedes the arraycopy, and we can take over zeroing the new object.
6878   // The arraycopy will finish the initialization, and provide
6879   // a new control state to which we will anchor the destination pointer.
6880 
6881   return alloc;
6882 }
6883 
6884 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6885   if (node->is_IfProj()) {
6886     Node* other_proj = node->as_IfProj()->other_if_proj();
6887     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6888       Node* obs = other_proj->fast_out(j);
6889       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6890           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6891         return obs->as_CallStaticJava();
6892       }
6893     }
6894   }
6895   return nullptr;
6896 }
6897 
6898 //-------------inline_encodeISOArray-----------------------------------
6899 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6900 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6901 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6902 // encode char[] to byte[] in ISO_8859_1 or ASCII
6903 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6904   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6905   // no receiver since it is static method
6906   Node *src         = argument(0);
6907   Node *src_offset  = argument(1);
6908   Node *dst         = argument(2);
6909   Node *dst_offset  = argument(3);
6910   Node *length      = argument(4);
6911 
6912   // Cast source & target arrays to not-null
6913   if (VerifyIntrinsicChecks) {
6914     src = must_be_not_null(src, true);
6915     dst = must_be_not_null(dst, true);
6916     if (stopped()) {
6917       return true;
6918     }
6919   }
6920 
6921   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6922   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6923   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6924       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6925     // failed array check
6926     return false;
6927   }
6928 
6929   // Figure out the size and type of the elements we will be copying.
6930   BasicType src_elem = src_type->elem()->array_element_basic_type();
6931   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6932   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6933     return false;
6934   }
6935 
6936   // Check source & target bounds
6937   if (VerifyIntrinsicChecks) {
6938     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6939     generate_string_range_check(dst, dst_offset, length, false, true);
6940     if (stopped()) {
6941       return true;
6942     }
6943   }
6944 
6945   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6946   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6947   // 'src_start' points to src array + scaled offset
6948   // 'dst_start' points to dst array + scaled offset
6949 
6950   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6951   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6952   enc = _gvn.transform(enc);
6953   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6954   set_memory(res_mem, mtype);
6955   set_result(enc);
6956   clear_upper_avx();
6957 
6958   return true;
6959 }
6960 
6961 //-------------inline_multiplyToLen-----------------------------------
6962 bool LibraryCallKit::inline_multiplyToLen() {
6963   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6964 
6965   address stubAddr = StubRoutines::multiplyToLen();
6966   if (stubAddr == nullptr) {
6967     return false; // Intrinsic's stub is not implemented on this platform
6968   }
6969   const char* stubName = "multiplyToLen";
6970 
6971   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6972 
6973   // no receiver because it is a static method
6974   Node* x    = argument(0);
6975   Node* xlen = argument(1);
6976   Node* y    = argument(2);
6977   Node* ylen = argument(3);
6978   Node* z    = argument(4);
6979 
6980   x = must_be_not_null(x, true);
6981   y = must_be_not_null(y, true);
6982 
6983   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6984   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6985   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6986       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6987     // failed array check
6988     return false;
6989   }
6990 
6991   BasicType x_elem = x_type->elem()->array_element_basic_type();
6992   BasicType y_elem = y_type->elem()->array_element_basic_type();
6993   if (x_elem != T_INT || y_elem != T_INT) {
6994     return false;
6995   }
6996 
6997   Node* x_start = array_element_address(x, intcon(0), x_elem);
6998   Node* y_start = array_element_address(y, intcon(0), y_elem);
6999   // 'x_start' points to x array + scaled xlen
7000   // 'y_start' points to y array + scaled ylen
7001 
7002   Node* z_start = array_element_address(z, intcon(0), T_INT);
7003 
7004   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7005                                  OptoRuntime::multiplyToLen_Type(),
7006                                  stubAddr, stubName, TypePtr::BOTTOM,
7007                                  x_start, xlen, y_start, ylen, z_start);
7008 
7009   C->set_has_split_ifs(true); // Has chance for split-if optimization
7010   set_result(z);
7011   return true;
7012 }
7013 
7014 //-------------inline_squareToLen------------------------------------
7015 bool LibraryCallKit::inline_squareToLen() {
7016   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7017 
7018   address stubAddr = StubRoutines::squareToLen();
7019   if (stubAddr == nullptr) {
7020     return false; // Intrinsic's stub is not implemented on this platform
7021   }
7022   const char* stubName = "squareToLen";
7023 
7024   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7025 
7026   Node* x    = argument(0);
7027   Node* len  = argument(1);
7028   Node* z    = argument(2);
7029   Node* zlen = argument(3);
7030 
7031   x = must_be_not_null(x, true);
7032   z = must_be_not_null(z, true);
7033 
7034   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7035   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7036   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7037       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7038     // failed array check
7039     return false;
7040   }
7041 
7042   BasicType x_elem = x_type->elem()->array_element_basic_type();
7043   BasicType z_elem = z_type->elem()->array_element_basic_type();
7044   if (x_elem != T_INT || z_elem != T_INT) {
7045     return false;
7046   }
7047 
7048 
7049   Node* x_start = array_element_address(x, intcon(0), x_elem);
7050   Node* z_start = array_element_address(z, intcon(0), z_elem);
7051 
7052   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7053                                   OptoRuntime::squareToLen_Type(),
7054                                   stubAddr, stubName, TypePtr::BOTTOM,
7055                                   x_start, len, z_start, zlen);
7056 
7057   set_result(z);
7058   return true;
7059 }
7060 
7061 //-------------inline_mulAdd------------------------------------------
7062 bool LibraryCallKit::inline_mulAdd() {
7063   assert(UseMulAddIntrinsic, "not implemented on this platform");
7064 
7065   address stubAddr = StubRoutines::mulAdd();
7066   if (stubAddr == nullptr) {
7067     return false; // Intrinsic's stub is not implemented on this platform
7068   }
7069   const char* stubName = "mulAdd";
7070 
7071   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7072 
7073   Node* out      = argument(0);
7074   Node* in       = argument(1);
7075   Node* offset   = argument(2);
7076   Node* len      = argument(3);
7077   Node* k        = argument(4);
7078 
7079   in = must_be_not_null(in, true);
7080   out = must_be_not_null(out, true);
7081 
7082   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7083   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7084   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7085        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7086     // failed array check
7087     return false;
7088   }
7089 
7090   BasicType out_elem = out_type->elem()->array_element_basic_type();
7091   BasicType in_elem = in_type->elem()->array_element_basic_type();
7092   if (out_elem != T_INT || in_elem != T_INT) {
7093     return false;
7094   }
7095 
7096   Node* outlen = load_array_length(out);
7097   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7098   Node* out_start = array_element_address(out, intcon(0), out_elem);
7099   Node* in_start = array_element_address(in, intcon(0), in_elem);
7100 
7101   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7102                                   OptoRuntime::mulAdd_Type(),
7103                                   stubAddr, stubName, TypePtr::BOTTOM,
7104                                   out_start,in_start, new_offset, len, k);
7105   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7106   set_result(result);
7107   return true;
7108 }
7109 
7110 //-------------inline_montgomeryMultiply-----------------------------------
7111 bool LibraryCallKit::inline_montgomeryMultiply() {
7112   address stubAddr = StubRoutines::montgomeryMultiply();
7113   if (stubAddr == nullptr) {
7114     return false; // Intrinsic's stub is not implemented on this platform
7115   }
7116 
7117   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7118   const char* stubName = "montgomery_multiply";
7119 
7120   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7121 
7122   Node* a    = argument(0);
7123   Node* b    = argument(1);
7124   Node* n    = argument(2);
7125   Node* len  = argument(3);
7126   Node* inv  = argument(4);
7127   Node* m    = argument(6);
7128 
7129   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7130   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7131   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7132   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7133   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7134       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7135       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7136       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7137     // failed array check
7138     return false;
7139   }
7140 
7141   BasicType a_elem = a_type->elem()->array_element_basic_type();
7142   BasicType b_elem = b_type->elem()->array_element_basic_type();
7143   BasicType n_elem = n_type->elem()->array_element_basic_type();
7144   BasicType m_elem = m_type->elem()->array_element_basic_type();
7145   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7146     return false;
7147   }
7148 
7149   // Make the call
7150   {
7151     Node* a_start = array_element_address(a, intcon(0), a_elem);
7152     Node* b_start = array_element_address(b, intcon(0), b_elem);
7153     Node* n_start = array_element_address(n, intcon(0), n_elem);
7154     Node* m_start = array_element_address(m, intcon(0), m_elem);
7155 
7156     Node* call = make_runtime_call(RC_LEAF,
7157                                    OptoRuntime::montgomeryMultiply_Type(),
7158                                    stubAddr, stubName, TypePtr::BOTTOM,
7159                                    a_start, b_start, n_start, len, inv, top(),
7160                                    m_start);
7161     set_result(m);
7162   }
7163 
7164   return true;
7165 }
7166 
7167 bool LibraryCallKit::inline_montgomerySquare() {
7168   address stubAddr = StubRoutines::montgomerySquare();
7169   if (stubAddr == nullptr) {
7170     return false; // Intrinsic's stub is not implemented on this platform
7171   }
7172 
7173   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7174   const char* stubName = "montgomery_square";
7175 
7176   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7177 
7178   Node* a    = argument(0);
7179   Node* n    = argument(1);
7180   Node* len  = argument(2);
7181   Node* inv  = argument(3);
7182   Node* m    = argument(5);
7183 
7184   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7185   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7186   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7187   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7188       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7189       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7190     // failed array check
7191     return false;
7192   }
7193 
7194   BasicType a_elem = a_type->elem()->array_element_basic_type();
7195   BasicType n_elem = n_type->elem()->array_element_basic_type();
7196   BasicType m_elem = m_type->elem()->array_element_basic_type();
7197   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7198     return false;
7199   }
7200 
7201   // Make the call
7202   {
7203     Node* a_start = array_element_address(a, intcon(0), a_elem);
7204     Node* n_start = array_element_address(n, intcon(0), n_elem);
7205     Node* m_start = array_element_address(m, intcon(0), m_elem);
7206 
7207     Node* call = make_runtime_call(RC_LEAF,
7208                                    OptoRuntime::montgomerySquare_Type(),
7209                                    stubAddr, stubName, TypePtr::BOTTOM,
7210                                    a_start, n_start, len, inv, top(),
7211                                    m_start);
7212     set_result(m);
7213   }
7214 
7215   return true;
7216 }
7217 
7218 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7219   address stubAddr = nullptr;
7220   const char* stubName = nullptr;
7221 
7222   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7223   if (stubAddr == nullptr) {
7224     return false; // Intrinsic's stub is not implemented on this platform
7225   }
7226 
7227   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7228 
7229   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7230 
7231   Node* newArr = argument(0);
7232   Node* oldArr = argument(1);
7233   Node* newIdx = argument(2);
7234   Node* shiftCount = argument(3);
7235   Node* numIter = argument(4);
7236 
7237   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7238   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7239   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7240       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7241     return false;
7242   }
7243 
7244   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7245   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7246   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7247     return false;
7248   }
7249 
7250   // Make the call
7251   {
7252     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7253     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7254 
7255     Node* call = make_runtime_call(RC_LEAF,
7256                                    OptoRuntime::bigIntegerShift_Type(),
7257                                    stubAddr,
7258                                    stubName,
7259                                    TypePtr::BOTTOM,
7260                                    newArr_start,
7261                                    oldArr_start,
7262                                    newIdx,
7263                                    shiftCount,
7264                                    numIter);
7265   }
7266 
7267   return true;
7268 }
7269 
7270 //-------------inline_vectorizedMismatch------------------------------
7271 bool LibraryCallKit::inline_vectorizedMismatch() {
7272   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7273 
7274   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7275   Node* obja    = argument(0); // Object
7276   Node* aoffset = argument(1); // long
7277   Node* objb    = argument(3); // Object
7278   Node* boffset = argument(4); // long
7279   Node* length  = argument(6); // int
7280   Node* scale   = argument(7); // int
7281 
7282   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7283   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7284   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7285       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7286       scale == top()) {
7287     return false; // failed input validation
7288   }
7289 
7290   Node* obja_adr = make_unsafe_address(obja, aoffset);
7291   Node* objb_adr = make_unsafe_address(objb, boffset);
7292 
7293   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7294   //
7295   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7296   //    if (length <= inline_limit) {
7297   //      inline_path:
7298   //        vmask   = VectorMaskGen length
7299   //        vload1  = LoadVectorMasked obja, vmask
7300   //        vload2  = LoadVectorMasked objb, vmask
7301   //        result1 = VectorCmpMasked vload1, vload2, vmask
7302   //    } else {
7303   //      call_stub_path:
7304   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7305   //    }
7306   //    exit_block:
7307   //      return Phi(result1, result2);
7308   //
7309   enum { inline_path = 1,  // input is small enough to process it all at once
7310          stub_path   = 2,  // input is too large; call into the VM
7311          PATH_LIMIT  = 3
7312   };
7313 
7314   Node* exit_block = new RegionNode(PATH_LIMIT);
7315   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7316   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7317 
7318   Node* call_stub_path = control();
7319 
7320   BasicType elem_bt = T_ILLEGAL;
7321 
7322   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7323   if (scale_t->is_con()) {
7324     switch (scale_t->get_con()) {
7325       case 0: elem_bt = T_BYTE;  break;
7326       case 1: elem_bt = T_SHORT; break;
7327       case 2: elem_bt = T_INT;   break;
7328       case 3: elem_bt = T_LONG;  break;
7329 
7330       default: elem_bt = T_ILLEGAL; break; // not supported
7331     }
7332   }
7333 
7334   int inline_limit = 0;
7335   bool do_partial_inline = false;
7336 
7337   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7338     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7339     do_partial_inline = inline_limit >= 16;
7340   }
7341 
7342   if (do_partial_inline) {
7343     assert(elem_bt != T_ILLEGAL, "sanity");
7344 
7345     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7346         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7347         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7348 
7349       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7350       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7351       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7352 
7353       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7354 
7355       if (!stopped()) {
7356         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7357 
7358         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7359         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7360         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7361         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7362 
7363         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7364         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7365         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7366         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7367 
7368         exit_block->init_req(inline_path, control());
7369         memory_phi->init_req(inline_path, map()->memory());
7370         result_phi->init_req(inline_path, result);
7371 
7372         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7373         clear_upper_avx();
7374       }
7375     }
7376   }
7377 
7378   if (call_stub_path != nullptr) {
7379     set_control(call_stub_path);
7380 
7381     Node* call = make_runtime_call(RC_LEAF,
7382                                    OptoRuntime::vectorizedMismatch_Type(),
7383                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7384                                    obja_adr, objb_adr, length, scale);
7385 
7386     exit_block->init_req(stub_path, control());
7387     memory_phi->init_req(stub_path, map()->memory());
7388     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7389   }
7390 
7391   exit_block = _gvn.transform(exit_block);
7392   memory_phi = _gvn.transform(memory_phi);
7393   result_phi = _gvn.transform(result_phi);
7394 
7395   record_for_igvn(exit_block);
7396   record_for_igvn(memory_phi);
7397   record_for_igvn(result_phi);
7398 
7399   set_control(exit_block);
7400   set_all_memory(memory_phi);
7401   set_result(result_phi);
7402 
7403   return true;
7404 }
7405 
7406 //------------------------------inline_vectorizedHashcode----------------------------
7407 bool LibraryCallKit::inline_vectorizedHashCode() {
7408   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7409 
7410   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7411   Node* array          = argument(0);
7412   Node* offset         = argument(1);
7413   Node* length         = argument(2);
7414   Node* initialValue   = argument(3);
7415   Node* basic_type     = argument(4);
7416 
7417   if (basic_type == top()) {
7418     return false; // failed input validation
7419   }
7420 
7421   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7422   if (!basic_type_t->is_con()) {
7423     return false; // Only intrinsify if mode argument is constant
7424   }
7425 
7426   array = must_be_not_null(array, true);
7427 
7428   BasicType bt = (BasicType)basic_type_t->get_con();
7429 
7430   // Resolve address of first element
7431   Node* array_start = array_element_address(array, offset, bt);
7432 
7433   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7434     array_start, length, initialValue, basic_type)));
7435   clear_upper_avx();
7436 
7437   return true;
7438 }
7439 
7440 /**
7441  * Calculate CRC32 for byte.
7442  * int java.util.zip.CRC32.update(int crc, int b)
7443  */
7444 bool LibraryCallKit::inline_updateCRC32() {
7445   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7446   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7447   // no receiver since it is static method
7448   Node* crc  = argument(0); // type: int
7449   Node* b    = argument(1); // type: int
7450 
7451   /*
7452    *    int c = ~ crc;
7453    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7454    *    b = b ^ (c >>> 8);
7455    *    crc = ~b;
7456    */
7457 
7458   Node* M1 = intcon(-1);
7459   crc = _gvn.transform(new XorINode(crc, M1));
7460   Node* result = _gvn.transform(new XorINode(crc, b));
7461   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7462 
7463   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7464   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7465   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7466   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7467 
7468   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7469   result = _gvn.transform(new XorINode(crc, result));
7470   result = _gvn.transform(new XorINode(result, M1));
7471   set_result(result);
7472   return true;
7473 }
7474 
7475 /**
7476  * Calculate CRC32 for byte[] array.
7477  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7478  */
7479 bool LibraryCallKit::inline_updateBytesCRC32() {
7480   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7481   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7482   // no receiver since it is static method
7483   Node* crc     = argument(0); // type: int
7484   Node* src     = argument(1); // type: oop
7485   Node* offset  = argument(2); // type: int
7486   Node* length  = argument(3); // type: int
7487 
7488   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7489   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7490     // failed array check
7491     return false;
7492   }
7493 
7494   // Figure out the size and type of the elements we will be copying.
7495   BasicType src_elem = src_type->elem()->array_element_basic_type();
7496   if (src_elem != T_BYTE) {
7497     return false;
7498   }
7499 
7500   // 'src_start' points to src array + scaled offset
7501   src = must_be_not_null(src, true);
7502   Node* src_start = array_element_address(src, offset, src_elem);
7503 
7504   // We assume that range check is done by caller.
7505   // TODO: generate range check (offset+length < src.length) in debug VM.
7506 
7507   // Call the stub.
7508   address stubAddr = StubRoutines::updateBytesCRC32();
7509   const char *stubName = "updateBytesCRC32";
7510 
7511   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7512                                  stubAddr, stubName, TypePtr::BOTTOM,
7513                                  crc, src_start, length);
7514   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7515   set_result(result);
7516   return true;
7517 }
7518 
7519 /**
7520  * Calculate CRC32 for ByteBuffer.
7521  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7522  */
7523 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7524   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7525   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7526   // no receiver since it is static method
7527   Node* crc     = argument(0); // type: int
7528   Node* src     = argument(1); // type: long
7529   Node* offset  = argument(3); // type: int
7530   Node* length  = argument(4); // type: int
7531 
7532   src = ConvL2X(src);  // adjust Java long to machine word
7533   Node* base = _gvn.transform(new CastX2PNode(src));
7534   offset = ConvI2X(offset);
7535 
7536   // 'src_start' points to src array + scaled offset
7537   Node* src_start = basic_plus_adr(top(), base, offset);
7538 
7539   // Call the stub.
7540   address stubAddr = StubRoutines::updateBytesCRC32();
7541   const char *stubName = "updateBytesCRC32";
7542 
7543   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7544                                  stubAddr, stubName, TypePtr::BOTTOM,
7545                                  crc, src_start, length);
7546   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7547   set_result(result);
7548   return true;
7549 }
7550 
7551 //------------------------------get_table_from_crc32c_class-----------------------
7552 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7553   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7554   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7555 
7556   return table;
7557 }
7558 
7559 //------------------------------inline_updateBytesCRC32C-----------------------
7560 //
7561 // Calculate CRC32C for byte[] array.
7562 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7563 //
7564 bool LibraryCallKit::inline_updateBytesCRC32C() {
7565   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7566   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7567   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7568   // no receiver since it is a static method
7569   Node* crc     = argument(0); // type: int
7570   Node* src     = argument(1); // type: oop
7571   Node* offset  = argument(2); // type: int
7572   Node* end     = argument(3); // type: int
7573 
7574   Node* length = _gvn.transform(new SubINode(end, offset));
7575 
7576   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7577   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7578     // failed array check
7579     return false;
7580   }
7581 
7582   // Figure out the size and type of the elements we will be copying.
7583   BasicType src_elem = src_type->elem()->array_element_basic_type();
7584   if (src_elem != T_BYTE) {
7585     return false;
7586   }
7587 
7588   // 'src_start' points to src array + scaled offset
7589   src = must_be_not_null(src, true);
7590   Node* src_start = array_element_address(src, offset, src_elem);
7591 
7592   // static final int[] byteTable in class CRC32C
7593   Node* table = get_table_from_crc32c_class(callee()->holder());
7594   table = must_be_not_null(table, true);
7595   Node* table_start = array_element_address(table, intcon(0), T_INT);
7596 
7597   // We assume that range check is done by caller.
7598   // TODO: generate range check (offset+length < src.length) in debug VM.
7599 
7600   // Call the stub.
7601   address stubAddr = StubRoutines::updateBytesCRC32C();
7602   const char *stubName = "updateBytesCRC32C";
7603 
7604   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7605                                  stubAddr, stubName, TypePtr::BOTTOM,
7606                                  crc, src_start, length, table_start);
7607   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7608   set_result(result);
7609   return true;
7610 }
7611 
7612 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7613 //
7614 // Calculate CRC32C for DirectByteBuffer.
7615 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7616 //
7617 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7618   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7619   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7620   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7621   // no receiver since it is a static method
7622   Node* crc     = argument(0); // type: int
7623   Node* src     = argument(1); // type: long
7624   Node* offset  = argument(3); // type: int
7625   Node* end     = argument(4); // type: int
7626 
7627   Node* length = _gvn.transform(new SubINode(end, offset));
7628 
7629   src = ConvL2X(src);  // adjust Java long to machine word
7630   Node* base = _gvn.transform(new CastX2PNode(src));
7631   offset = ConvI2X(offset);
7632 
7633   // 'src_start' points to src array + scaled offset
7634   Node* src_start = basic_plus_adr(top(), base, offset);
7635 
7636   // static final int[] byteTable in class CRC32C
7637   Node* table = get_table_from_crc32c_class(callee()->holder());
7638   table = must_be_not_null(table, true);
7639   Node* table_start = array_element_address(table, intcon(0), T_INT);
7640 
7641   // Call the stub.
7642   address stubAddr = StubRoutines::updateBytesCRC32C();
7643   const char *stubName = "updateBytesCRC32C";
7644 
7645   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7646                                  stubAddr, stubName, TypePtr::BOTTOM,
7647                                  crc, src_start, length, table_start);
7648   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7649   set_result(result);
7650   return true;
7651 }
7652 
7653 //------------------------------inline_updateBytesAdler32----------------------
7654 //
7655 // Calculate Adler32 checksum for byte[] array.
7656 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7657 //
7658 bool LibraryCallKit::inline_updateBytesAdler32() {
7659   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7660   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7661   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7662   // no receiver since it is static method
7663   Node* crc     = argument(0); // type: int
7664   Node* src     = argument(1); // type: oop
7665   Node* offset  = argument(2); // type: int
7666   Node* length  = argument(3); // type: int
7667 
7668   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7669   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7670     // failed array check
7671     return false;
7672   }
7673 
7674   // Figure out the size and type of the elements we will be copying.
7675   BasicType src_elem = src_type->elem()->array_element_basic_type();
7676   if (src_elem != T_BYTE) {
7677     return false;
7678   }
7679 
7680   // 'src_start' points to src array + scaled offset
7681   Node* src_start = array_element_address(src, offset, src_elem);
7682 
7683   // We assume that range check is done by caller.
7684   // TODO: generate range check (offset+length < src.length) in debug VM.
7685 
7686   // Call the stub.
7687   address stubAddr = StubRoutines::updateBytesAdler32();
7688   const char *stubName = "updateBytesAdler32";
7689 
7690   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7691                                  stubAddr, stubName, TypePtr::BOTTOM,
7692                                  crc, src_start, length);
7693   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7694   set_result(result);
7695   return true;
7696 }
7697 
7698 //------------------------------inline_updateByteBufferAdler32---------------
7699 //
7700 // Calculate Adler32 checksum for DirectByteBuffer.
7701 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7702 //
7703 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7704   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7705   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7706   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7707   // no receiver since it is static method
7708   Node* crc     = argument(0); // type: int
7709   Node* src     = argument(1); // type: long
7710   Node* offset  = argument(3); // type: int
7711   Node* length  = argument(4); // type: int
7712 
7713   src = ConvL2X(src);  // adjust Java long to machine word
7714   Node* base = _gvn.transform(new CastX2PNode(src));
7715   offset = ConvI2X(offset);
7716 
7717   // 'src_start' points to src array + scaled offset
7718   Node* src_start = basic_plus_adr(top(), base, offset);
7719 
7720   // Call the stub.
7721   address stubAddr = StubRoutines::updateBytesAdler32();
7722   const char *stubName = "updateBytesAdler32";
7723 
7724   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7725                                  stubAddr, stubName, TypePtr::BOTTOM,
7726                                  crc, src_start, length);
7727 
7728   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7729   set_result(result);
7730   return true;
7731 }
7732 
7733 //----------------------------inline_reference_get0----------------------------
7734 // public T java.lang.ref.Reference.get();
7735 bool LibraryCallKit::inline_reference_get0() {
7736   const int referent_offset = java_lang_ref_Reference::referent_offset();
7737 
7738   // Get the argument:
7739   Node* reference_obj = null_check_receiver();
7740   if (stopped()) return true;
7741 
7742   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7743   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7744                                         decorators, /*is_static*/ false, nullptr);
7745   if (result == nullptr) return false;
7746 
7747   // Add memory barrier to prevent commoning reads from this field
7748   // across safepoint since GC can change its value.
7749   insert_mem_bar(Op_MemBarCPUOrder);
7750 
7751   set_result(result);
7752   return true;
7753 }
7754 
7755 //----------------------------inline_reference_refersTo0----------------------------
7756 // bool java.lang.ref.Reference.refersTo0();
7757 // bool java.lang.ref.PhantomReference.refersTo0();
7758 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7759   // Get arguments:
7760   Node* reference_obj = null_check_receiver();
7761   Node* other_obj = argument(1);
7762   if (stopped()) return true;
7763 
7764   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7765   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7766   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7767                                           decorators, /*is_static*/ false, nullptr);
7768   if (referent == nullptr) return false;
7769 
7770   // Add memory barrier to prevent commoning reads from this field
7771   // across safepoint since GC can change its value.
7772   insert_mem_bar(Op_MemBarCPUOrder);
7773 
7774   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7775   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7776   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7777 
7778   RegionNode* region = new RegionNode(3);
7779   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7780 
7781   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7782   region->init_req(1, if_true);
7783   phi->init_req(1, intcon(1));
7784 
7785   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7786   region->init_req(2, if_false);
7787   phi->init_req(2, intcon(0));
7788 
7789   set_control(_gvn.transform(region));
7790   record_for_igvn(region);
7791   set_result(_gvn.transform(phi));
7792   return true;
7793 }
7794 
7795 //----------------------------inline_reference_clear0----------------------------
7796 // void java.lang.ref.Reference.clear0();
7797 // void java.lang.ref.PhantomReference.clear0();
7798 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7799   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7800 
7801   // Get arguments
7802   Node* reference_obj = null_check_receiver();
7803   if (stopped()) return true;
7804 
7805   // Common access parameters
7806   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7807   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7808   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7809   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7810   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7811 
7812   Node* referent = access_load_at(reference_obj,
7813                                   referent_field_addr,
7814                                   referent_field_addr_type,
7815                                   val_type,
7816                                   T_OBJECT,
7817                                   decorators);
7818 
7819   IdealKit ideal(this);
7820 #define __ ideal.
7821   __ if_then(referent, BoolTest::ne, null());
7822     sync_kit(ideal);
7823     access_store_at(reference_obj,
7824                     referent_field_addr,
7825                     referent_field_addr_type,
7826                     null(),
7827                     val_type,
7828                     T_OBJECT,
7829                     decorators);
7830     __ sync_kit(this);
7831   __ end_if();
7832   final_sync(ideal);
7833 #undef __
7834 
7835   return true;
7836 }
7837 
7838 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7839                                              DecoratorSet decorators, bool is_static,
7840                                              ciInstanceKlass* fromKls) {
7841   if (fromKls == nullptr) {
7842     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7843     assert(tinst != nullptr, "obj is null");
7844     assert(tinst->is_loaded(), "obj is not loaded");
7845     fromKls = tinst->instance_klass();
7846   } else {
7847     assert(is_static, "only for static field access");
7848   }
7849   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7850                                               ciSymbol::make(fieldTypeString),
7851                                               is_static);
7852 
7853   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7854   if (field == nullptr) return (Node *) nullptr;
7855 
7856   if (is_static) {
7857     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7858     fromObj = makecon(tip);
7859   }
7860 
7861   // Next code  copied from Parse::do_get_xxx():
7862 
7863   // Compute address and memory type.
7864   int offset  = field->offset_in_bytes();
7865   bool is_vol = field->is_volatile();
7866   ciType* field_klass = field->type();
7867   assert(field_klass->is_loaded(), "should be loaded");
7868   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7869   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7870   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7871     "slice of address and input slice don't match");
7872   BasicType bt = field->layout_type();
7873 
7874   // Build the resultant type of the load
7875   const Type *type;
7876   if (bt == T_OBJECT) {
7877     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7878   } else {
7879     type = Type::get_const_basic_type(bt);
7880   }
7881 
7882   if (is_vol) {
7883     decorators |= MO_SEQ_CST;
7884   }
7885 
7886   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7887 }
7888 
7889 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7890                                                  bool is_exact /* true */, bool is_static /* false */,
7891                                                  ciInstanceKlass * fromKls /* nullptr */) {
7892   if (fromKls == nullptr) {
7893     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7894     assert(tinst != nullptr, "obj is null");
7895     assert(tinst->is_loaded(), "obj is not loaded");
7896     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7897     fromKls = tinst->instance_klass();
7898   }
7899   else {
7900     assert(is_static, "only for static field access");
7901   }
7902   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7903     ciSymbol::make(fieldTypeString),
7904     is_static);
7905 
7906   assert(field != nullptr, "undefined field");
7907   assert(!field->is_volatile(), "not defined for volatile fields");
7908 
7909   if (is_static) {
7910     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7911     fromObj = makecon(tip);
7912   }
7913 
7914   // Next code  copied from Parse::do_get_xxx():
7915 
7916   // Compute address and memory type.
7917   int offset = field->offset_in_bytes();
7918   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7919 
7920   return adr;
7921 }
7922 
7923 //------------------------------inline_aescrypt_Block-----------------------
7924 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7925   address stubAddr = nullptr;
7926   const char *stubName;
7927   assert(UseAES, "need AES instruction support");
7928 
7929   switch(id) {
7930   case vmIntrinsics::_aescrypt_encryptBlock:
7931     stubAddr = StubRoutines::aescrypt_encryptBlock();
7932     stubName = "aescrypt_encryptBlock";
7933     break;
7934   case vmIntrinsics::_aescrypt_decryptBlock:
7935     stubAddr = StubRoutines::aescrypt_decryptBlock();
7936     stubName = "aescrypt_decryptBlock";
7937     break;
7938   default:
7939     break;
7940   }
7941   if (stubAddr == nullptr) return false;
7942 
7943   Node* aescrypt_object = argument(0);
7944   Node* src             = argument(1);
7945   Node* src_offset      = argument(2);
7946   Node* dest            = argument(3);
7947   Node* dest_offset     = argument(4);
7948 
7949   src = must_be_not_null(src, true);
7950   dest = must_be_not_null(dest, true);
7951 
7952   // (1) src and dest are arrays.
7953   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7954   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7955   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7956          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7957 
7958   // for the quick and dirty code we will skip all the checks.
7959   // we are just trying to get the call to be generated.
7960   Node* src_start  = src;
7961   Node* dest_start = dest;
7962   if (src_offset != nullptr || dest_offset != nullptr) {
7963     assert(src_offset != nullptr && dest_offset != nullptr, "");
7964     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7965     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7966   }
7967 
7968   // now need to get the start of its expanded key array
7969   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7970   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7971   if (k_start == nullptr) return false;
7972 
7973   // Call the stub.
7974   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7975                     stubAddr, stubName, TypePtr::BOTTOM,
7976                     src_start, dest_start, k_start);
7977 
7978   return true;
7979 }
7980 
7981 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7982 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7983   address stubAddr = nullptr;
7984   const char *stubName = nullptr;
7985 
7986   assert(UseAES, "need AES instruction support");
7987 
7988   switch(id) {
7989   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7990     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7991     stubName = "cipherBlockChaining_encryptAESCrypt";
7992     break;
7993   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7994     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7995     stubName = "cipherBlockChaining_decryptAESCrypt";
7996     break;
7997   default:
7998     break;
7999   }
8000   if (stubAddr == nullptr) return false;
8001 
8002   Node* cipherBlockChaining_object = argument(0);
8003   Node* src                        = argument(1);
8004   Node* src_offset                 = argument(2);
8005   Node* len                        = argument(3);
8006   Node* dest                       = argument(4);
8007   Node* dest_offset                = argument(5);
8008 
8009   src = must_be_not_null(src, false);
8010   dest = must_be_not_null(dest, false);
8011 
8012   // (1) src and dest are arrays.
8013   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8014   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8015   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8016          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8017 
8018   // checks are the responsibility of the caller
8019   Node* src_start  = src;
8020   Node* dest_start = dest;
8021   if (src_offset != nullptr || dest_offset != nullptr) {
8022     assert(src_offset != nullptr && dest_offset != nullptr, "");
8023     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8024     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8025   }
8026 
8027   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8028   // (because of the predicated logic executed earlier).
8029   // so we cast it here safely.
8030   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8031 
8032   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8033   if (embeddedCipherObj == nullptr) return false;
8034 
8035   // cast it to what we know it will be at runtime
8036   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8037   assert(tinst != nullptr, "CBC obj is null");
8038   assert(tinst->is_loaded(), "CBC obj is not loaded");
8039   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8040   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8041 
8042   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8043   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8044   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8045   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8046   aescrypt_object = _gvn.transform(aescrypt_object);
8047 
8048   // we need to get the start of the aescrypt_object's expanded key array
8049   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8050   if (k_start == nullptr) return false;
8051 
8052   // similarly, get the start address of the r vector
8053   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8054   if (objRvec == nullptr) return false;
8055   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8056 
8057   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8058   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8059                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8060                                      stubAddr, stubName, TypePtr::BOTTOM,
8061                                      src_start, dest_start, k_start, r_start, len);
8062 
8063   // return cipher length (int)
8064   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8065   set_result(retvalue);
8066   return true;
8067 }
8068 
8069 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8070 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8071   address stubAddr = nullptr;
8072   const char *stubName = nullptr;
8073 
8074   assert(UseAES, "need AES instruction support");
8075 
8076   switch (id) {
8077   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8078     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8079     stubName = "electronicCodeBook_encryptAESCrypt";
8080     break;
8081   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8082     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8083     stubName = "electronicCodeBook_decryptAESCrypt";
8084     break;
8085   default:
8086     break;
8087   }
8088 
8089   if (stubAddr == nullptr) return false;
8090 
8091   Node* electronicCodeBook_object = argument(0);
8092   Node* src                       = argument(1);
8093   Node* src_offset                = argument(2);
8094   Node* len                       = argument(3);
8095   Node* dest                      = argument(4);
8096   Node* dest_offset               = argument(5);
8097 
8098   // (1) src and dest are arrays.
8099   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8100   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8101   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8102          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8103 
8104   // checks are the responsibility of the caller
8105   Node* src_start = src;
8106   Node* dest_start = dest;
8107   if (src_offset != nullptr || dest_offset != nullptr) {
8108     assert(src_offset != nullptr && dest_offset != nullptr, "");
8109     src_start = array_element_address(src, src_offset, T_BYTE);
8110     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8111   }
8112 
8113   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8114   // (because of the predicated logic executed earlier).
8115   // so we cast it here safely.
8116   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8117 
8118   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8119   if (embeddedCipherObj == nullptr) return false;
8120 
8121   // cast it to what we know it will be at runtime
8122   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8123   assert(tinst != nullptr, "ECB obj is null");
8124   assert(tinst->is_loaded(), "ECB obj is not loaded");
8125   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8126   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8127 
8128   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8129   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8130   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8131   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8132   aescrypt_object = _gvn.transform(aescrypt_object);
8133 
8134   // we need to get the start of the aescrypt_object's expanded key array
8135   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8136   if (k_start == nullptr) return false;
8137 
8138   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8139   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8140                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8141                                      stubAddr, stubName, TypePtr::BOTTOM,
8142                                      src_start, dest_start, k_start, len);
8143 
8144   // return cipher length (int)
8145   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8146   set_result(retvalue);
8147   return true;
8148 }
8149 
8150 //------------------------------inline_counterMode_AESCrypt-----------------------
8151 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8152   assert(UseAES, "need AES instruction support");
8153   if (!UseAESCTRIntrinsics) return false;
8154 
8155   address stubAddr = nullptr;
8156   const char *stubName = nullptr;
8157   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8158     stubAddr = StubRoutines::counterMode_AESCrypt();
8159     stubName = "counterMode_AESCrypt";
8160   }
8161   if (stubAddr == nullptr) return false;
8162 
8163   Node* counterMode_object = argument(0);
8164   Node* src = argument(1);
8165   Node* src_offset = argument(2);
8166   Node* len = argument(3);
8167   Node* dest = argument(4);
8168   Node* dest_offset = argument(5);
8169 
8170   // (1) src and dest are arrays.
8171   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8172   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8173   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8174          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8175 
8176   // checks are the responsibility of the caller
8177   Node* src_start = src;
8178   Node* dest_start = dest;
8179   if (src_offset != nullptr || dest_offset != nullptr) {
8180     assert(src_offset != nullptr && dest_offset != nullptr, "");
8181     src_start = array_element_address(src, src_offset, T_BYTE);
8182     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8183   }
8184 
8185   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8186   // (because of the predicated logic executed earlier).
8187   // so we cast it here safely.
8188   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8189   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8190   if (embeddedCipherObj == nullptr) return false;
8191   // cast it to what we know it will be at runtime
8192   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8193   assert(tinst != nullptr, "CTR obj is null");
8194   assert(tinst->is_loaded(), "CTR obj is not loaded");
8195   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8196   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8197   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8198   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8199   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8200   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8201   aescrypt_object = _gvn.transform(aescrypt_object);
8202   // we need to get the start of the aescrypt_object's expanded key array
8203   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8204   if (k_start == nullptr) return false;
8205   // similarly, get the start address of the r vector
8206   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8207   if (obj_counter == nullptr) return false;
8208   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8209 
8210   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8211   if (saved_encCounter == nullptr) return false;
8212   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8213   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8214 
8215   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8216   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8217                                      OptoRuntime::counterMode_aescrypt_Type(),
8218                                      stubAddr, stubName, TypePtr::BOTTOM,
8219                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8220 
8221   // return cipher length (int)
8222   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8223   set_result(retvalue);
8224   return true;
8225 }
8226 
8227 //------------------------------get_key_start_from_aescrypt_object-----------------------
8228 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
8229 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8230   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8231   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8232   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8233   // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
8234   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
8235   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8236   if (objSessionK == nullptr) {
8237     return (Node *) nullptr;
8238   }
8239   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
8240 #else
8241   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
8242 #endif // PPC64
8243   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8244   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8245 
8246   // now have the array, need to get the start address of the K array
8247   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8248   return k_start;
8249 }
8250 
8251 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8252 // Return node representing slow path of predicate check.
8253 // the pseudo code we want to emulate with this predicate is:
8254 // for encryption:
8255 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8256 // for decryption:
8257 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8258 //    note cipher==plain is more conservative than the original java code but that's OK
8259 //
8260 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8261   // The receiver was checked for null already.
8262   Node* objCBC = argument(0);
8263 
8264   Node* src = argument(1);
8265   Node* dest = argument(4);
8266 
8267   // Load embeddedCipher field of CipherBlockChaining object.
8268   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8269 
8270   // get AESCrypt klass for instanceOf check
8271   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8272   // will have same classloader as CipherBlockChaining object
8273   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8274   assert(tinst != nullptr, "CBCobj is null");
8275   assert(tinst->is_loaded(), "CBCobj is not loaded");
8276 
8277   // we want to do an instanceof comparison against the AESCrypt class
8278   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8279   if (!klass_AESCrypt->is_loaded()) {
8280     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8281     Node* ctrl = control();
8282     set_control(top()); // no regular fast path
8283     return ctrl;
8284   }
8285 
8286   src = must_be_not_null(src, true);
8287   dest = must_be_not_null(dest, true);
8288 
8289   // Resolve oops to stable for CmpP below.
8290   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8291 
8292   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8293   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8294   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8295 
8296   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8297 
8298   // for encryption, we are done
8299   if (!decrypting)
8300     return instof_false;  // even if it is null
8301 
8302   // for decryption, we need to add a further check to avoid
8303   // taking the intrinsic path when cipher and plain are the same
8304   // see the original java code for why.
8305   RegionNode* region = new RegionNode(3);
8306   region->init_req(1, instof_false);
8307 
8308   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8309   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8310   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8311   region->init_req(2, src_dest_conjoint);
8312 
8313   record_for_igvn(region);
8314   return _gvn.transform(region);
8315 }
8316 
8317 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8318 // Return node representing slow path of predicate check.
8319 // the pseudo code we want to emulate with this predicate is:
8320 // for encryption:
8321 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8322 // for decryption:
8323 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8324 //    note cipher==plain is more conservative than the original java code but that's OK
8325 //
8326 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8327   // The receiver was checked for null already.
8328   Node* objECB = argument(0);
8329 
8330   // Load embeddedCipher field of ElectronicCodeBook object.
8331   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8332 
8333   // get AESCrypt klass for instanceOf check
8334   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8335   // will have same classloader as ElectronicCodeBook object
8336   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8337   assert(tinst != nullptr, "ECBobj is null");
8338   assert(tinst->is_loaded(), "ECBobj is not loaded");
8339 
8340   // we want to do an instanceof comparison against the AESCrypt class
8341   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8342   if (!klass_AESCrypt->is_loaded()) {
8343     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8344     Node* ctrl = control();
8345     set_control(top()); // no regular fast path
8346     return ctrl;
8347   }
8348   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8349 
8350   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8351   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8352   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8353 
8354   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8355 
8356   // for encryption, we are done
8357   if (!decrypting)
8358     return instof_false;  // even if it is null
8359 
8360   // for decryption, we need to add a further check to avoid
8361   // taking the intrinsic path when cipher and plain are the same
8362   // see the original java code for why.
8363   RegionNode* region = new RegionNode(3);
8364   region->init_req(1, instof_false);
8365   Node* src = argument(1);
8366   Node* dest = argument(4);
8367   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8368   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8369   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8370   region->init_req(2, src_dest_conjoint);
8371 
8372   record_for_igvn(region);
8373   return _gvn.transform(region);
8374 }
8375 
8376 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8377 // Return node representing slow path of predicate check.
8378 // the pseudo code we want to emulate with this predicate is:
8379 // for encryption:
8380 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8381 // for decryption:
8382 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8383 //    note cipher==plain is more conservative than the original java code but that's OK
8384 //
8385 
8386 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8387   // The receiver was checked for null already.
8388   Node* objCTR = argument(0);
8389 
8390   // Load embeddedCipher field of CipherBlockChaining object.
8391   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8392 
8393   // get AESCrypt klass for instanceOf check
8394   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8395   // will have same classloader as CipherBlockChaining object
8396   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8397   assert(tinst != nullptr, "CTRobj is null");
8398   assert(tinst->is_loaded(), "CTRobj is not loaded");
8399 
8400   // we want to do an instanceof comparison against the AESCrypt class
8401   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8402   if (!klass_AESCrypt->is_loaded()) {
8403     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8404     Node* ctrl = control();
8405     set_control(top()); // no regular fast path
8406     return ctrl;
8407   }
8408 
8409   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8410   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8411   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8412   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8413   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8414 
8415   return instof_false; // even if it is null
8416 }
8417 
8418 //------------------------------inline_ghash_processBlocks
8419 bool LibraryCallKit::inline_ghash_processBlocks() {
8420   address stubAddr;
8421   const char *stubName;
8422   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8423 
8424   stubAddr = StubRoutines::ghash_processBlocks();
8425   stubName = "ghash_processBlocks";
8426 
8427   Node* data           = argument(0);
8428   Node* offset         = argument(1);
8429   Node* len            = argument(2);
8430   Node* state          = argument(3);
8431   Node* subkeyH        = argument(4);
8432 
8433   state = must_be_not_null(state, true);
8434   subkeyH = must_be_not_null(subkeyH, true);
8435   data = must_be_not_null(data, true);
8436 
8437   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8438   assert(state_start, "state is null");
8439   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8440   assert(subkeyH_start, "subkeyH is null");
8441   Node* data_start  = array_element_address(data, offset, T_BYTE);
8442   assert(data_start, "data is null");
8443 
8444   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8445                                   OptoRuntime::ghash_processBlocks_Type(),
8446                                   stubAddr, stubName, TypePtr::BOTTOM,
8447                                   state_start, subkeyH_start, data_start, len);
8448   return true;
8449 }
8450 
8451 //------------------------------inline_chacha20Block
8452 bool LibraryCallKit::inline_chacha20Block() {
8453   address stubAddr;
8454   const char *stubName;
8455   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8456 
8457   stubAddr = StubRoutines::chacha20Block();
8458   stubName = "chacha20Block";
8459 
8460   Node* state          = argument(0);
8461   Node* result         = argument(1);
8462 
8463   state = must_be_not_null(state, true);
8464   result = must_be_not_null(result, true);
8465 
8466   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8467   assert(state_start, "state is null");
8468   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8469   assert(result_start, "result is null");
8470 
8471   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8472                                   OptoRuntime::chacha20Block_Type(),
8473                                   stubAddr, stubName, TypePtr::BOTTOM,
8474                                   state_start, result_start);
8475   // return key stream length (int)
8476   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8477   set_result(retvalue);
8478   return true;
8479 }
8480 
8481 //------------------------------inline_kyberNtt
8482 bool LibraryCallKit::inline_kyberNtt() {
8483   address stubAddr;
8484   const char *stubName;
8485   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8486   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8487 
8488   stubAddr = StubRoutines::kyberNtt();
8489   stubName = "kyberNtt";
8490   if (!stubAddr) return false;
8491 
8492   Node* coeffs          = argument(0);
8493   Node* ntt_zetas        = argument(1);
8494 
8495   coeffs = must_be_not_null(coeffs, true);
8496   ntt_zetas = must_be_not_null(ntt_zetas, true);
8497 
8498   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8499   assert(coeffs_start, "coeffs is null");
8500   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8501   assert(ntt_zetas_start, "ntt_zetas is null");
8502   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8503                                   OptoRuntime::kyberNtt_Type(),
8504                                   stubAddr, stubName, TypePtr::BOTTOM,
8505                                   coeffs_start, ntt_zetas_start);
8506   // return an int
8507   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8508   set_result(retvalue);
8509   return true;
8510 }
8511 
8512 //------------------------------inline_kyberInverseNtt
8513 bool LibraryCallKit::inline_kyberInverseNtt() {
8514   address stubAddr;
8515   const char *stubName;
8516   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8517   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8518 
8519   stubAddr = StubRoutines::kyberInverseNtt();
8520   stubName = "kyberInverseNtt";
8521   if (!stubAddr) return false;
8522 
8523   Node* coeffs          = argument(0);
8524   Node* zetas           = argument(1);
8525 
8526   coeffs = must_be_not_null(coeffs, true);
8527   zetas = must_be_not_null(zetas, true);
8528 
8529   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8530   assert(coeffs_start, "coeffs is null");
8531   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8532   assert(zetas_start, "inverseNtt_zetas is null");
8533   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8534                                   OptoRuntime::kyberInverseNtt_Type(),
8535                                   stubAddr, stubName, TypePtr::BOTTOM,
8536                                   coeffs_start, zetas_start);
8537 
8538   // return an int
8539   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8540   set_result(retvalue);
8541   return true;
8542 }
8543 
8544 //------------------------------inline_kyberNttMult
8545 bool LibraryCallKit::inline_kyberNttMult() {
8546   address stubAddr;
8547   const char *stubName;
8548   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8549   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8550 
8551   stubAddr = StubRoutines::kyberNttMult();
8552   stubName = "kyberNttMult";
8553   if (!stubAddr) return false;
8554 
8555   Node* result          = argument(0);
8556   Node* ntta            = argument(1);
8557   Node* nttb            = argument(2);
8558   Node* zetas           = argument(3);
8559 
8560   result = must_be_not_null(result, true);
8561   ntta = must_be_not_null(ntta, true);
8562   nttb = must_be_not_null(nttb, true);
8563   zetas = must_be_not_null(zetas, true);
8564 
8565   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8566   assert(result_start, "result is null");
8567   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8568   assert(ntta_start, "ntta is null");
8569   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8570   assert(nttb_start, "nttb is null");
8571   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8572   assert(zetas_start, "nttMult_zetas is null");
8573   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8574                                   OptoRuntime::kyberNttMult_Type(),
8575                                   stubAddr, stubName, TypePtr::BOTTOM,
8576                                   result_start, ntta_start, nttb_start,
8577                                   zetas_start);
8578 
8579   // return an int
8580   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8581   set_result(retvalue);
8582 
8583   return true;
8584 }
8585 
8586 //------------------------------inline_kyberAddPoly_2
8587 bool LibraryCallKit::inline_kyberAddPoly_2() {
8588   address stubAddr;
8589   const char *stubName;
8590   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8591   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8592 
8593   stubAddr = StubRoutines::kyberAddPoly_2();
8594   stubName = "kyberAddPoly_2";
8595   if (!stubAddr) return false;
8596 
8597   Node* result          = argument(0);
8598   Node* a               = argument(1);
8599   Node* b               = argument(2);
8600 
8601   result = must_be_not_null(result, true);
8602   a = must_be_not_null(a, true);
8603   b = must_be_not_null(b, true);
8604 
8605   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8606   assert(result_start, "result is null");
8607   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8608   assert(a_start, "a is null");
8609   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8610   assert(b_start, "b is null");
8611   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8612                                   OptoRuntime::kyberAddPoly_2_Type(),
8613                                   stubAddr, stubName, TypePtr::BOTTOM,
8614                                   result_start, a_start, b_start);
8615   // return an int
8616   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8617   set_result(retvalue);
8618   return true;
8619 }
8620 
8621 //------------------------------inline_kyberAddPoly_3
8622 bool LibraryCallKit::inline_kyberAddPoly_3() {
8623   address stubAddr;
8624   const char *stubName;
8625   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8626   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8627 
8628   stubAddr = StubRoutines::kyberAddPoly_3();
8629   stubName = "kyberAddPoly_3";
8630   if (!stubAddr) return false;
8631 
8632   Node* result          = argument(0);
8633   Node* a               = argument(1);
8634   Node* b               = argument(2);
8635   Node* c               = argument(3);
8636 
8637   result = must_be_not_null(result, true);
8638   a = must_be_not_null(a, true);
8639   b = must_be_not_null(b, true);
8640   c = must_be_not_null(c, true);
8641 
8642   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8643   assert(result_start, "result is null");
8644   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8645   assert(a_start, "a is null");
8646   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8647   assert(b_start, "b is null");
8648   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8649   assert(c_start, "c is null");
8650   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8651                                   OptoRuntime::kyberAddPoly_3_Type(),
8652                                   stubAddr, stubName, TypePtr::BOTTOM,
8653                                   result_start, a_start, b_start, c_start);
8654   // return an int
8655   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8656   set_result(retvalue);
8657   return true;
8658 }
8659 
8660 //------------------------------inline_kyber12To16
8661 bool LibraryCallKit::inline_kyber12To16() {
8662   address stubAddr;
8663   const char *stubName;
8664   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8665   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8666 
8667   stubAddr = StubRoutines::kyber12To16();
8668   stubName = "kyber12To16";
8669   if (!stubAddr) return false;
8670 
8671   Node* condensed       = argument(0);
8672   Node* condensedOffs   = argument(1);
8673   Node* parsed          = argument(2);
8674   Node* parsedLength    = argument(3);
8675 
8676   condensed = must_be_not_null(condensed, true);
8677   parsed = must_be_not_null(parsed, true);
8678 
8679   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8680   assert(condensed_start, "condensed is null");
8681   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8682   assert(parsed_start, "parsed is null");
8683   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8684                                   OptoRuntime::kyber12To16_Type(),
8685                                   stubAddr, stubName, TypePtr::BOTTOM,
8686                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8687   // return an int
8688   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8689   set_result(retvalue);
8690   return true;
8691 
8692 }
8693 
8694 //------------------------------inline_kyberBarrettReduce
8695 bool LibraryCallKit::inline_kyberBarrettReduce() {
8696   address stubAddr;
8697   const char *stubName;
8698   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8699   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8700 
8701   stubAddr = StubRoutines::kyberBarrettReduce();
8702   stubName = "kyberBarrettReduce";
8703   if (!stubAddr) return false;
8704 
8705   Node* coeffs          = argument(0);
8706 
8707   coeffs = must_be_not_null(coeffs, true);
8708 
8709   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8710   assert(coeffs_start, "coeffs is null");
8711   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8712                                   OptoRuntime::kyberBarrettReduce_Type(),
8713                                   stubAddr, stubName, TypePtr::BOTTOM,
8714                                   coeffs_start);
8715   // return an int
8716   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8717   set_result(retvalue);
8718   return true;
8719 }
8720 
8721 //------------------------------inline_dilithiumAlmostNtt
8722 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8723   address stubAddr;
8724   const char *stubName;
8725   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8726   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8727 
8728   stubAddr = StubRoutines::dilithiumAlmostNtt();
8729   stubName = "dilithiumAlmostNtt";
8730   if (!stubAddr) return false;
8731 
8732   Node* coeffs          = argument(0);
8733   Node* ntt_zetas        = argument(1);
8734 
8735   coeffs = must_be_not_null(coeffs, true);
8736   ntt_zetas = must_be_not_null(ntt_zetas, true);
8737 
8738   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8739   assert(coeffs_start, "coeffs is null");
8740   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8741   assert(ntt_zetas_start, "ntt_zetas is null");
8742   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8743                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8744                                   stubAddr, stubName, TypePtr::BOTTOM,
8745                                   coeffs_start, ntt_zetas_start);
8746   // return an int
8747   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8748   set_result(retvalue);
8749   return true;
8750 }
8751 
8752 //------------------------------inline_dilithiumAlmostInverseNtt
8753 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8754   address stubAddr;
8755   const char *stubName;
8756   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8757   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8758 
8759   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8760   stubName = "dilithiumAlmostInverseNtt";
8761   if (!stubAddr) return false;
8762 
8763   Node* coeffs          = argument(0);
8764   Node* zetas           = argument(1);
8765 
8766   coeffs = must_be_not_null(coeffs, true);
8767   zetas = must_be_not_null(zetas, true);
8768 
8769   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8770   assert(coeffs_start, "coeffs is null");
8771   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8772   assert(zetas_start, "inverseNtt_zetas is null");
8773   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8774                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8775                                   stubAddr, stubName, TypePtr::BOTTOM,
8776                                   coeffs_start, zetas_start);
8777   // return an int
8778   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8779   set_result(retvalue);
8780   return true;
8781 }
8782 
8783 //------------------------------inline_dilithiumNttMult
8784 bool LibraryCallKit::inline_dilithiumNttMult() {
8785   address stubAddr;
8786   const char *stubName;
8787   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8788   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8789 
8790   stubAddr = StubRoutines::dilithiumNttMult();
8791   stubName = "dilithiumNttMult";
8792   if (!stubAddr) return false;
8793 
8794   Node* result          = argument(0);
8795   Node* ntta            = argument(1);
8796   Node* nttb            = argument(2);
8797   Node* zetas           = argument(3);
8798 
8799   result = must_be_not_null(result, true);
8800   ntta = must_be_not_null(ntta, true);
8801   nttb = must_be_not_null(nttb, true);
8802   zetas = must_be_not_null(zetas, true);
8803 
8804   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8805   assert(result_start, "result is null");
8806   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8807   assert(ntta_start, "ntta is null");
8808   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8809   assert(nttb_start, "nttb is null");
8810   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8811                                   OptoRuntime::dilithiumNttMult_Type(),
8812                                   stubAddr, stubName, TypePtr::BOTTOM,
8813                                   result_start, ntta_start, nttb_start);
8814 
8815   // return an int
8816   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8817   set_result(retvalue);
8818 
8819   return true;
8820 }
8821 
8822 //------------------------------inline_dilithiumMontMulByConstant
8823 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8824   address stubAddr;
8825   const char *stubName;
8826   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8827   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8828 
8829   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8830   stubName = "dilithiumMontMulByConstant";
8831   if (!stubAddr) return false;
8832 
8833   Node* coeffs          = argument(0);
8834   Node* constant        = argument(1);
8835 
8836   coeffs = must_be_not_null(coeffs, true);
8837 
8838   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8839   assert(coeffs_start, "coeffs is null");
8840   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8841                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8842                                   stubAddr, stubName, TypePtr::BOTTOM,
8843                                   coeffs_start, constant);
8844 
8845   // return an int
8846   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8847   set_result(retvalue);
8848   return true;
8849 }
8850 
8851 
8852 //------------------------------inline_dilithiumDecomposePoly
8853 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8854   address stubAddr;
8855   const char *stubName;
8856   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8857   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8858 
8859   stubAddr = StubRoutines::dilithiumDecomposePoly();
8860   stubName = "dilithiumDecomposePoly";
8861   if (!stubAddr) return false;
8862 
8863   Node* input          = argument(0);
8864   Node* lowPart        = argument(1);
8865   Node* highPart       = argument(2);
8866   Node* twoGamma2      = argument(3);
8867   Node* multiplier     = argument(4);
8868 
8869   input = must_be_not_null(input, true);
8870   lowPart = must_be_not_null(lowPart, true);
8871   highPart = must_be_not_null(highPart, true);
8872 
8873   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8874   assert(input_start, "input is null");
8875   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8876   assert(lowPart_start, "lowPart is null");
8877   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8878   assert(highPart_start, "highPart is null");
8879 
8880   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8881                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8882                                   stubAddr, stubName, TypePtr::BOTTOM,
8883                                   input_start, lowPart_start, highPart_start,
8884                                   twoGamma2, multiplier);
8885 
8886   // return an int
8887   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8888   set_result(retvalue);
8889   return true;
8890 }
8891 
8892 bool LibraryCallKit::inline_base64_encodeBlock() {
8893   address stubAddr;
8894   const char *stubName;
8895   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8896   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8897   stubAddr = StubRoutines::base64_encodeBlock();
8898   stubName = "encodeBlock";
8899 
8900   if (!stubAddr) return false;
8901   Node* base64obj = argument(0);
8902   Node* src = argument(1);
8903   Node* offset = argument(2);
8904   Node* len = argument(3);
8905   Node* dest = argument(4);
8906   Node* dp = argument(5);
8907   Node* isURL = argument(6);
8908 
8909   src = must_be_not_null(src, true);
8910   dest = must_be_not_null(dest, true);
8911 
8912   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8913   assert(src_start, "source array is null");
8914   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8915   assert(dest_start, "destination array is null");
8916 
8917   Node* base64 = make_runtime_call(RC_LEAF,
8918                                    OptoRuntime::base64_encodeBlock_Type(),
8919                                    stubAddr, stubName, TypePtr::BOTTOM,
8920                                    src_start, offset, len, dest_start, dp, isURL);
8921   return true;
8922 }
8923 
8924 bool LibraryCallKit::inline_base64_decodeBlock() {
8925   address stubAddr;
8926   const char *stubName;
8927   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8928   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8929   stubAddr = StubRoutines::base64_decodeBlock();
8930   stubName = "decodeBlock";
8931 
8932   if (!stubAddr) return false;
8933   Node* base64obj = argument(0);
8934   Node* src = argument(1);
8935   Node* src_offset = argument(2);
8936   Node* len = argument(3);
8937   Node* dest = argument(4);
8938   Node* dest_offset = argument(5);
8939   Node* isURL = argument(6);
8940   Node* isMIME = argument(7);
8941 
8942   src = must_be_not_null(src, true);
8943   dest = must_be_not_null(dest, true);
8944 
8945   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8946   assert(src_start, "source array is null");
8947   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8948   assert(dest_start, "destination array is null");
8949 
8950   Node* call = make_runtime_call(RC_LEAF,
8951                                  OptoRuntime::base64_decodeBlock_Type(),
8952                                  stubAddr, stubName, TypePtr::BOTTOM,
8953                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8954   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8955   set_result(result);
8956   return true;
8957 }
8958 
8959 bool LibraryCallKit::inline_poly1305_processBlocks() {
8960   address stubAddr;
8961   const char *stubName;
8962   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8963   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8964   stubAddr = StubRoutines::poly1305_processBlocks();
8965   stubName = "poly1305_processBlocks";
8966 
8967   if (!stubAddr) return false;
8968   null_check_receiver();  // null-check receiver
8969   if (stopped())  return true;
8970 
8971   Node* input = argument(1);
8972   Node* input_offset = argument(2);
8973   Node* len = argument(3);
8974   Node* alimbs = argument(4);
8975   Node* rlimbs = argument(5);
8976 
8977   input = must_be_not_null(input, true);
8978   alimbs = must_be_not_null(alimbs, true);
8979   rlimbs = must_be_not_null(rlimbs, true);
8980 
8981   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8982   assert(input_start, "input array is null");
8983   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8984   assert(acc_start, "acc array is null");
8985   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8986   assert(r_start, "r array is null");
8987 
8988   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8989                                  OptoRuntime::poly1305_processBlocks_Type(),
8990                                  stubAddr, stubName, TypePtr::BOTTOM,
8991                                  input_start, len, acc_start, r_start);
8992   return true;
8993 }
8994 
8995 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8996   address stubAddr;
8997   const char *stubName;
8998   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8999   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9000   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9001   stubName = "intpoly_montgomeryMult_P256";
9002 
9003   if (!stubAddr) return false;
9004   null_check_receiver();  // null-check receiver
9005   if (stopped())  return true;
9006 
9007   Node* a = argument(1);
9008   Node* b = argument(2);
9009   Node* r = argument(3);
9010 
9011   a = must_be_not_null(a, true);
9012   b = must_be_not_null(b, true);
9013   r = must_be_not_null(r, true);
9014 
9015   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9016   assert(a_start, "a array is null");
9017   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9018   assert(b_start, "b array is null");
9019   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9020   assert(r_start, "r array is null");
9021 
9022   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9023                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9024                                  stubAddr, stubName, TypePtr::BOTTOM,
9025                                  a_start, b_start, r_start);
9026   return true;
9027 }
9028 
9029 bool LibraryCallKit::inline_intpoly_assign() {
9030   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9031   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9032   const char *stubName = "intpoly_assign";
9033   address stubAddr = StubRoutines::intpoly_assign();
9034   if (!stubAddr) return false;
9035 
9036   Node* set = argument(0);
9037   Node* a = argument(1);
9038   Node* b = argument(2);
9039   Node* arr_length = load_array_length(a);
9040 
9041   a = must_be_not_null(a, true);
9042   b = must_be_not_null(b, true);
9043 
9044   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9045   assert(a_start, "a array is null");
9046   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9047   assert(b_start, "b array is null");
9048 
9049   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9050                                  OptoRuntime::intpoly_assign_Type(),
9051                                  stubAddr, stubName, TypePtr::BOTTOM,
9052                                  set, a_start, b_start, arr_length);
9053   return true;
9054 }
9055 
9056 //------------------------------inline_digestBase_implCompress-----------------------
9057 //
9058 // Calculate MD5 for single-block byte[] array.
9059 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9060 //
9061 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9062 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9063 //
9064 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9065 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9066 //
9067 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9068 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9069 //
9070 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9071 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9072 //
9073 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9074   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9075 
9076   Node* digestBase_obj = argument(0);
9077   Node* src            = argument(1); // type oop
9078   Node* ofs            = argument(2); // type int
9079 
9080   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9081   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9082     // failed array check
9083     return false;
9084   }
9085   // Figure out the size and type of the elements we will be copying.
9086   BasicType src_elem = src_type->elem()->array_element_basic_type();
9087   if (src_elem != T_BYTE) {
9088     return false;
9089   }
9090   // 'src_start' points to src array + offset
9091   src = must_be_not_null(src, true);
9092   Node* src_start = array_element_address(src, ofs, src_elem);
9093   Node* state = nullptr;
9094   Node* block_size = nullptr;
9095   address stubAddr;
9096   const char *stubName;
9097 
9098   switch(id) {
9099   case vmIntrinsics::_md5_implCompress:
9100     assert(UseMD5Intrinsics, "need MD5 instruction support");
9101     state = get_state_from_digest_object(digestBase_obj, T_INT);
9102     stubAddr = StubRoutines::md5_implCompress();
9103     stubName = "md5_implCompress";
9104     break;
9105   case vmIntrinsics::_sha_implCompress:
9106     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9107     state = get_state_from_digest_object(digestBase_obj, T_INT);
9108     stubAddr = StubRoutines::sha1_implCompress();
9109     stubName = "sha1_implCompress";
9110     break;
9111   case vmIntrinsics::_sha2_implCompress:
9112     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9113     state = get_state_from_digest_object(digestBase_obj, T_INT);
9114     stubAddr = StubRoutines::sha256_implCompress();
9115     stubName = "sha256_implCompress";
9116     break;
9117   case vmIntrinsics::_sha5_implCompress:
9118     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9119     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9120     stubAddr = StubRoutines::sha512_implCompress();
9121     stubName = "sha512_implCompress";
9122     break;
9123   case vmIntrinsics::_sha3_implCompress:
9124     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9125     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9126     stubAddr = StubRoutines::sha3_implCompress();
9127     stubName = "sha3_implCompress";
9128     block_size = get_block_size_from_digest_object(digestBase_obj);
9129     if (block_size == nullptr) return false;
9130     break;
9131   default:
9132     fatal_unexpected_iid(id);
9133     return false;
9134   }
9135   if (state == nullptr) return false;
9136 
9137   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9138   if (stubAddr == nullptr) return false;
9139 
9140   // Call the stub.
9141   Node* call;
9142   if (block_size == nullptr) {
9143     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9144                              stubAddr, stubName, TypePtr::BOTTOM,
9145                              src_start, state);
9146   } else {
9147     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9148                              stubAddr, stubName, TypePtr::BOTTOM,
9149                              src_start, state, block_size);
9150   }
9151 
9152   return true;
9153 }
9154 
9155 //------------------------------inline_double_keccak
9156 bool LibraryCallKit::inline_double_keccak() {
9157   address stubAddr;
9158   const char *stubName;
9159   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9160   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9161 
9162   stubAddr = StubRoutines::double_keccak();
9163   stubName = "double_keccak";
9164   if (!stubAddr) return false;
9165 
9166   Node* status0        = argument(0);
9167   Node* status1        = argument(1);
9168 
9169   status0 = must_be_not_null(status0, true);
9170   status1 = must_be_not_null(status1, true);
9171 
9172   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9173   assert(status0_start, "status0 is null");
9174   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9175   assert(status1_start, "status1 is null");
9176   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9177                                   OptoRuntime::double_keccak_Type(),
9178                                   stubAddr, stubName, TypePtr::BOTTOM,
9179                                   status0_start, status1_start);
9180   // return an int
9181   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9182   set_result(retvalue);
9183   return true;
9184 }
9185 
9186 
9187 //------------------------------inline_digestBase_implCompressMB-----------------------
9188 //
9189 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9190 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9191 //
9192 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9193   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9194          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9195   assert((uint)predicate < 5, "sanity");
9196   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9197 
9198   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9199   Node* src            = argument(1); // byte[] array
9200   Node* ofs            = argument(2); // type int
9201   Node* limit          = argument(3); // type int
9202 
9203   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9204   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9205     // failed array check
9206     return false;
9207   }
9208   // Figure out the size and type of the elements we will be copying.
9209   BasicType src_elem = src_type->elem()->array_element_basic_type();
9210   if (src_elem != T_BYTE) {
9211     return false;
9212   }
9213   // 'src_start' points to src array + offset
9214   src = must_be_not_null(src, false);
9215   Node* src_start = array_element_address(src, ofs, src_elem);
9216 
9217   const char* klass_digestBase_name = nullptr;
9218   const char* stub_name = nullptr;
9219   address     stub_addr = nullptr;
9220   BasicType elem_type = T_INT;
9221 
9222   switch (predicate) {
9223   case 0:
9224     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9225       klass_digestBase_name = "sun/security/provider/MD5";
9226       stub_name = "md5_implCompressMB";
9227       stub_addr = StubRoutines::md5_implCompressMB();
9228     }
9229     break;
9230   case 1:
9231     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9232       klass_digestBase_name = "sun/security/provider/SHA";
9233       stub_name = "sha1_implCompressMB";
9234       stub_addr = StubRoutines::sha1_implCompressMB();
9235     }
9236     break;
9237   case 2:
9238     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9239       klass_digestBase_name = "sun/security/provider/SHA2";
9240       stub_name = "sha256_implCompressMB";
9241       stub_addr = StubRoutines::sha256_implCompressMB();
9242     }
9243     break;
9244   case 3:
9245     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9246       klass_digestBase_name = "sun/security/provider/SHA5";
9247       stub_name = "sha512_implCompressMB";
9248       stub_addr = StubRoutines::sha512_implCompressMB();
9249       elem_type = T_LONG;
9250     }
9251     break;
9252   case 4:
9253     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9254       klass_digestBase_name = "sun/security/provider/SHA3";
9255       stub_name = "sha3_implCompressMB";
9256       stub_addr = StubRoutines::sha3_implCompressMB();
9257       elem_type = T_LONG;
9258     }
9259     break;
9260   default:
9261     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9262   }
9263   if (klass_digestBase_name != nullptr) {
9264     assert(stub_addr != nullptr, "Stub is generated");
9265     if (stub_addr == nullptr) return false;
9266 
9267     // get DigestBase klass to lookup for SHA klass
9268     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9269     assert(tinst != nullptr, "digestBase_obj is not instance???");
9270     assert(tinst->is_loaded(), "DigestBase is not loaded");
9271 
9272     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9273     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9274     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9275     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9276   }
9277   return false;
9278 }
9279 
9280 //------------------------------inline_digestBase_implCompressMB-----------------------
9281 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9282                                                       BasicType elem_type, address stubAddr, const char *stubName,
9283                                                       Node* src_start, Node* ofs, Node* limit) {
9284   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9285   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9286   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9287   digest_obj = _gvn.transform(digest_obj);
9288 
9289   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9290   if (state == nullptr) return false;
9291 
9292   Node* block_size = nullptr;
9293   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9294     block_size = get_block_size_from_digest_object(digest_obj);
9295     if (block_size == nullptr) return false;
9296   }
9297 
9298   // Call the stub.
9299   Node* call;
9300   if (block_size == nullptr) {
9301     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9302                              OptoRuntime::digestBase_implCompressMB_Type(false),
9303                              stubAddr, stubName, TypePtr::BOTTOM,
9304                              src_start, state, ofs, limit);
9305   } else {
9306      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9307                              OptoRuntime::digestBase_implCompressMB_Type(true),
9308                              stubAddr, stubName, TypePtr::BOTTOM,
9309                              src_start, state, block_size, ofs, limit);
9310   }
9311 
9312   // return ofs (int)
9313   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9314   set_result(result);
9315 
9316   return true;
9317 }
9318 
9319 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9320 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9321   assert(UseAES, "need AES instruction support");
9322   address stubAddr = nullptr;
9323   const char *stubName = nullptr;
9324   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9325   stubName = "galoisCounterMode_AESCrypt";
9326 
9327   if (stubAddr == nullptr) return false;
9328 
9329   Node* in      = argument(0);
9330   Node* inOfs   = argument(1);
9331   Node* len     = argument(2);
9332   Node* ct      = argument(3);
9333   Node* ctOfs   = argument(4);
9334   Node* out     = argument(5);
9335   Node* outOfs  = argument(6);
9336   Node* gctr_object = argument(7);
9337   Node* ghash_object = argument(8);
9338 
9339   // (1) in, ct and out are arrays.
9340   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9341   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9342   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9343   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9344           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9345          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9346 
9347   // checks are the responsibility of the caller
9348   Node* in_start = in;
9349   Node* ct_start = ct;
9350   Node* out_start = out;
9351   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9352     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9353     in_start = array_element_address(in, inOfs, T_BYTE);
9354     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9355     out_start = array_element_address(out, outOfs, T_BYTE);
9356   }
9357 
9358   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9359   // (because of the predicated logic executed earlier).
9360   // so we cast it here safely.
9361   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9362   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9363   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9364   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9365   Node* state = load_field_from_object(ghash_object, "state", "[J");
9366 
9367   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9368     return false;
9369   }
9370   // cast it to what we know it will be at runtime
9371   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9372   assert(tinst != nullptr, "GCTR obj is null");
9373   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9374   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9375   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9376   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9377   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9378   const TypeOopPtr* xtype = aklass->as_instance_type();
9379   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9380   aescrypt_object = _gvn.transform(aescrypt_object);
9381   // we need to get the start of the aescrypt_object's expanded key array
9382   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9383   if (k_start == nullptr) return false;
9384   // similarly, get the start address of the r vector
9385   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9386   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9387   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9388 
9389 
9390   // Call the stub, passing params
9391   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9392                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9393                                stubAddr, stubName, TypePtr::BOTTOM,
9394                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9395 
9396   // return cipher length (int)
9397   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9398   set_result(retvalue);
9399 
9400   return true;
9401 }
9402 
9403 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9404 // Return node representing slow path of predicate check.
9405 // the pseudo code we want to emulate with this predicate is:
9406 // for encryption:
9407 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9408 // for decryption:
9409 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9410 //    note cipher==plain is more conservative than the original java code but that's OK
9411 //
9412 
9413 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9414   // The receiver was checked for null already.
9415   Node* objGCTR = argument(7);
9416   // Load embeddedCipher field of GCTR object.
9417   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9418   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9419 
9420   // get AESCrypt klass for instanceOf check
9421   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9422   // will have same classloader as CipherBlockChaining object
9423   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9424   assert(tinst != nullptr, "GCTR obj is null");
9425   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9426 
9427   // we want to do an instanceof comparison against the AESCrypt class
9428   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9429   if (!klass_AESCrypt->is_loaded()) {
9430     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9431     Node* ctrl = control();
9432     set_control(top()); // no regular fast path
9433     return ctrl;
9434   }
9435 
9436   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9437   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9438   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9439   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9440   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9441 
9442   return instof_false; // even if it is null
9443 }
9444 
9445 //------------------------------get_state_from_digest_object-----------------------
9446 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9447   const char* state_type;
9448   switch (elem_type) {
9449     case T_BYTE: state_type = "[B"; break;
9450     case T_INT:  state_type = "[I"; break;
9451     case T_LONG: state_type = "[J"; break;
9452     default: ShouldNotReachHere();
9453   }
9454   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9455   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9456   if (digest_state == nullptr) return (Node *) nullptr;
9457 
9458   // now have the array, need to get the start address of the state array
9459   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9460   return state;
9461 }
9462 
9463 //------------------------------get_block_size_from_sha3_object----------------------------------
9464 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9465   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9466   assert (block_size != nullptr, "sanity");
9467   return block_size;
9468 }
9469 
9470 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9471 // Return node representing slow path of predicate check.
9472 // the pseudo code we want to emulate with this predicate is:
9473 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9474 //
9475 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9476   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9477          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9478   assert((uint)predicate < 5, "sanity");
9479 
9480   // The receiver was checked for null already.
9481   Node* digestBaseObj = argument(0);
9482 
9483   // get DigestBase klass for instanceOf check
9484   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9485   assert(tinst != nullptr, "digestBaseObj is null");
9486   assert(tinst->is_loaded(), "DigestBase is not loaded");
9487 
9488   const char* klass_name = nullptr;
9489   switch (predicate) {
9490   case 0:
9491     if (UseMD5Intrinsics) {
9492       // we want to do an instanceof comparison against the MD5 class
9493       klass_name = "sun/security/provider/MD5";
9494     }
9495     break;
9496   case 1:
9497     if (UseSHA1Intrinsics) {
9498       // we want to do an instanceof comparison against the SHA class
9499       klass_name = "sun/security/provider/SHA";
9500     }
9501     break;
9502   case 2:
9503     if (UseSHA256Intrinsics) {
9504       // we want to do an instanceof comparison against the SHA2 class
9505       klass_name = "sun/security/provider/SHA2";
9506     }
9507     break;
9508   case 3:
9509     if (UseSHA512Intrinsics) {
9510       // we want to do an instanceof comparison against the SHA5 class
9511       klass_name = "sun/security/provider/SHA5";
9512     }
9513     break;
9514   case 4:
9515     if (UseSHA3Intrinsics) {
9516       // we want to do an instanceof comparison against the SHA3 class
9517       klass_name = "sun/security/provider/SHA3";
9518     }
9519     break;
9520   default:
9521     fatal("unknown SHA intrinsic predicate: %d", predicate);
9522   }
9523 
9524   ciKlass* klass = nullptr;
9525   if (klass_name != nullptr) {
9526     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9527   }
9528   if ((klass == nullptr) || !klass->is_loaded()) {
9529     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9530     Node* ctrl = control();
9531     set_control(top()); // no intrinsic path
9532     return ctrl;
9533   }
9534   ciInstanceKlass* instklass = klass->as_instance_klass();
9535 
9536   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9537   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9538   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9539   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9540 
9541   return instof_false;  // even if it is null
9542 }
9543 
9544 //-------------inline_fma-----------------------------------
9545 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9546   Node *a = nullptr;
9547   Node *b = nullptr;
9548   Node *c = nullptr;
9549   Node* result = nullptr;
9550   switch (id) {
9551   case vmIntrinsics::_fmaD:
9552     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9553     // no receiver since it is static method
9554     a = argument(0);
9555     b = argument(2);
9556     c = argument(4);
9557     result = _gvn.transform(new FmaDNode(a, b, c));
9558     break;
9559   case vmIntrinsics::_fmaF:
9560     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9561     a = argument(0);
9562     b = argument(1);
9563     c = argument(2);
9564     result = _gvn.transform(new FmaFNode(a, b, c));
9565     break;
9566   default:
9567     fatal_unexpected_iid(id);  break;
9568   }
9569   set_result(result);
9570   return true;
9571 }
9572 
9573 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9574   // argument(0) is receiver
9575   Node* codePoint = argument(1);
9576   Node* n = nullptr;
9577 
9578   switch (id) {
9579     case vmIntrinsics::_isDigit :
9580       n = new DigitNode(control(), codePoint);
9581       break;
9582     case vmIntrinsics::_isLowerCase :
9583       n = new LowerCaseNode(control(), codePoint);
9584       break;
9585     case vmIntrinsics::_isUpperCase :
9586       n = new UpperCaseNode(control(), codePoint);
9587       break;
9588     case vmIntrinsics::_isWhitespace :
9589       n = new WhitespaceNode(control(), codePoint);
9590       break;
9591     default:
9592       fatal_unexpected_iid(id);
9593   }
9594 
9595   set_result(_gvn.transform(n));
9596   return true;
9597 }
9598 
9599 bool LibraryCallKit::inline_profileBoolean() {
9600   Node* counts = argument(1);
9601   const TypeAryPtr* ary = nullptr;
9602   ciArray* aobj = nullptr;
9603   if (counts->is_Con()
9604       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9605       && (aobj = ary->const_oop()->as_array()) != nullptr
9606       && (aobj->length() == 2)) {
9607     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9608     jint false_cnt = aobj->element_value(0).as_int();
9609     jint  true_cnt = aobj->element_value(1).as_int();
9610 
9611     if (C->log() != nullptr) {
9612       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9613                      false_cnt, true_cnt);
9614     }
9615 
9616     if (false_cnt + true_cnt == 0) {
9617       // According to profile, never executed.
9618       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9619                           Deoptimization::Action_reinterpret);
9620       return true;
9621     }
9622 
9623     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9624     // is a number of each value occurrences.
9625     Node* result = argument(0);
9626     if (false_cnt == 0 || true_cnt == 0) {
9627       // According to profile, one value has been never seen.
9628       int expected_val = (false_cnt == 0) ? 1 : 0;
9629 
9630       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9631       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9632 
9633       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9634       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9635       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9636 
9637       { // Slow path: uncommon trap for never seen value and then reexecute
9638         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9639         // the value has been seen at least once.
9640         PreserveJVMState pjvms(this);
9641         PreserveReexecuteState preexecs(this);
9642         jvms()->set_should_reexecute(true);
9643 
9644         set_control(slow_path);
9645         set_i_o(i_o());
9646 
9647         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9648                             Deoptimization::Action_reinterpret);
9649       }
9650       // The guard for never seen value enables sharpening of the result and
9651       // returning a constant. It allows to eliminate branches on the same value
9652       // later on.
9653       set_control(fast_path);
9654       result = intcon(expected_val);
9655     }
9656     // Stop profiling.
9657     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9658     // By replacing method body with profile data (represented as ProfileBooleanNode
9659     // on IR level) we effectively disable profiling.
9660     // It enables full speed execution once optimized code is generated.
9661     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9662     C->record_for_igvn(profile);
9663     set_result(profile);
9664     return true;
9665   } else {
9666     // Continue profiling.
9667     // Profile data isn't available at the moment. So, execute method's bytecode version.
9668     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9669     // is compiled and counters aren't available since corresponding MethodHandle
9670     // isn't a compile-time constant.
9671     return false;
9672   }
9673 }
9674 
9675 bool LibraryCallKit::inline_isCompileConstant() {
9676   Node* n = argument(0);
9677   set_result(n->is_Con() ? intcon(1) : intcon(0));
9678   return true;
9679 }
9680 
9681 //------------------------------- inline_getObjectSize --------------------------------------
9682 //
9683 // Calculate the runtime size of the object/array.
9684 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9685 //
9686 bool LibraryCallKit::inline_getObjectSize() {
9687   Node* obj = argument(3);
9688   Node* klass_node = load_object_klass(obj);
9689 
9690   jint  layout_con = Klass::_lh_neutral_value;
9691   Node* layout_val = get_layout_helper(klass_node, layout_con);
9692   int   layout_is_con = (layout_val == nullptr);
9693 
9694   if (layout_is_con) {
9695     // Layout helper is constant, can figure out things at compile time.
9696 
9697     if (Klass::layout_helper_is_instance(layout_con)) {
9698       // Instance case:  layout_con contains the size itself.
9699       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9700       set_result(size);
9701     } else {
9702       // Array case: size is round(header + element_size*arraylength).
9703       // Since arraylength is different for every array instance, we have to
9704       // compute the whole thing at runtime.
9705 
9706       Node* arr_length = load_array_length(obj);
9707 
9708       int round_mask = MinObjAlignmentInBytes - 1;
9709       int hsize  = Klass::layout_helper_header_size(layout_con);
9710       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9711 
9712       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9713         round_mask = 0;  // strength-reduce it if it goes away completely
9714       }
9715       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9716       Node* header_size = intcon(hsize + round_mask);
9717 
9718       Node* lengthx = ConvI2X(arr_length);
9719       Node* headerx = ConvI2X(header_size);
9720 
9721       Node* abody = lengthx;
9722       if (eshift != 0) {
9723         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9724       }
9725       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9726       if (round_mask != 0) {
9727         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9728       }
9729       size = ConvX2L(size);
9730       set_result(size);
9731     }
9732   } else {
9733     // Layout helper is not constant, need to test for array-ness at runtime.
9734 
9735     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9736     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9737     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9738     record_for_igvn(result_reg);
9739 
9740     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9741     if (array_ctl != nullptr) {
9742       // Array case: size is round(header + element_size*arraylength).
9743       // Since arraylength is different for every array instance, we have to
9744       // compute the whole thing at runtime.
9745 
9746       PreserveJVMState pjvms(this);
9747       set_control(array_ctl);
9748       Node* arr_length = load_array_length(obj);
9749 
9750       int round_mask = MinObjAlignmentInBytes - 1;
9751       Node* mask = intcon(round_mask);
9752 
9753       Node* hss = intcon(Klass::_lh_header_size_shift);
9754       Node* hsm = intcon(Klass::_lh_header_size_mask);
9755       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9756       header_size = _gvn.transform(new AndINode(header_size, hsm));
9757       header_size = _gvn.transform(new AddINode(header_size, mask));
9758 
9759       // There is no need to mask or shift this value.
9760       // The semantics of LShiftINode include an implicit mask to 0x1F.
9761       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9762       Node* elem_shift = layout_val;
9763 
9764       Node* lengthx = ConvI2X(arr_length);
9765       Node* headerx = ConvI2X(header_size);
9766 
9767       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9768       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9769       if (round_mask != 0) {
9770         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9771       }
9772       size = ConvX2L(size);
9773 
9774       result_reg->init_req(_array_path, control());
9775       result_val->init_req(_array_path, size);
9776     }
9777 
9778     if (!stopped()) {
9779       // Instance case: the layout helper gives us instance size almost directly,
9780       // but we need to mask out the _lh_instance_slow_path_bit.
9781       Node* size = ConvI2X(layout_val);
9782       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9783       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9784       size = _gvn.transform(new AndXNode(size, mask));
9785       size = ConvX2L(size);
9786 
9787       result_reg->init_req(_instance_path, control());
9788       result_val->init_req(_instance_path, size);
9789     }
9790 
9791     set_result(result_reg, result_val);
9792   }
9793 
9794   return true;
9795 }
9796 
9797 //------------------------------- inline_blackhole --------------------------------------
9798 //
9799 // Make sure all arguments to this node are alive.
9800 // This matches methods that were requested to be blackholed through compile commands.
9801 //
9802 bool LibraryCallKit::inline_blackhole() {
9803   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9804   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9805   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9806 
9807   // Blackhole node pinches only the control, not memory. This allows
9808   // the blackhole to be pinned in the loop that computes blackholed
9809   // values, but have no other side effects, like breaking the optimizations
9810   // across the blackhole.
9811 
9812   Node* bh = _gvn.transform(new BlackholeNode(control()));
9813   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9814 
9815   // Bind call arguments as blackhole arguments to keep them alive
9816   uint nargs = callee()->arg_size();
9817   for (uint i = 0; i < nargs; i++) {
9818     bh->add_req(argument(i));
9819   }
9820 
9821   return true;
9822 }
9823 
9824 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9825   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9826   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9827     return nullptr; // box klass is not Float16
9828   }
9829 
9830   // Null check; get notnull casted pointer
9831   Node* null_ctl = top();
9832   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9833   // If not_null_box is dead, only null-path is taken
9834   if (stopped()) {
9835     set_control(null_ctl);
9836     return nullptr;
9837   }
9838   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9839   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9840   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9841   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9842 }
9843 
9844 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9845   PreserveReexecuteState preexecs(this);
9846   jvms()->set_should_reexecute(true);
9847 
9848   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9849   Node* klass_node = makecon(klass_type);
9850   Node* box = new_instance(klass_node);
9851 
9852   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9853   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9854 
9855   Node* field_store = _gvn.transform(access_store_at(box,
9856                                                      value_field,
9857                                                      value_adr_type,
9858                                                      value,
9859                                                      TypeInt::SHORT,
9860                                                      T_SHORT,
9861                                                      IN_HEAP));
9862   set_memory(field_store, value_adr_type);
9863   return box;
9864 }
9865 
9866 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9867   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9868       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9869     return false;
9870   }
9871 
9872   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9873   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9874     return false;
9875   }
9876 
9877   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9878   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9879   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9880                                                     ciSymbols::short_signature(),
9881                                                     false);
9882   assert(field != nullptr, "");
9883 
9884   // Transformed nodes
9885   Node* fld1 = nullptr;
9886   Node* fld2 = nullptr;
9887   Node* fld3 = nullptr;
9888   switch(num_args) {
9889     case 3:
9890       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9891       if (fld3 == nullptr) {
9892         return false;
9893       }
9894       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9895     // fall-through
9896     case 2:
9897       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9898       if (fld2 == nullptr) {
9899         return false;
9900       }
9901       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9902     // fall-through
9903     case 1:
9904       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9905       if (fld1 == nullptr) {
9906         return false;
9907       }
9908       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9909       break;
9910     default: fatal("Unsupported number of arguments %d", num_args);
9911   }
9912 
9913   Node* result = nullptr;
9914   switch (id) {
9915     // Unary operations
9916     case vmIntrinsics::_sqrt_float16:
9917       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9918       break;
9919     // Ternary operations
9920     case vmIntrinsics::_fma_float16:
9921       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9922       break;
9923     default:
9924       fatal_unexpected_iid(id);
9925       break;
9926   }
9927   result = _gvn.transform(new ReinterpretHF2SNode(result));
9928   set_result(box_fp16_value(float16_box_type, field, result));
9929   return true;
9930 }
9931