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