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