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