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