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