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