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