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