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