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