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