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.
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     if (bailout->req() > 1) {
4282       PreserveJVMState pjvms(this);
4283       set_control(_gvn.transform(bailout));
4284       uncommon_trap(Deoptimization::Reason_intrinsic,
4285                     Deoptimization::Action_maybe_recompile);
4286     }
4287 
4288     if (!stopped()) {
4289       // How many elements will we copy from the original?
4290       // The answer is MinI(orig_length - start, length).
4291       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4292       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
4293 
4294       // Generate a direct call to the right arraycopy function(s).
4295       // We know the copy is disjoint but we might not know if the
4296       // oop stores need checking.
4297       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
4298       // This will fail a store-check if x contains any non-nulls.
4299 
4300       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4301       // loads/stores but it is legal only if we're sure the
4302       // Arrays.copyOf would succeed. So we need all input arguments
4303       // to the copyOf to be validated, including that the copy to the
4304       // new array won't trigger an ArrayStoreException. That subtype
4305       // check can be optimized if we know something on the type of
4306       // the input array from type speculation.
4307       if (_gvn.type(klass_node)->singleton()) {
4308         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4309         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4310 
4311         int test = C->static_subtype_check(superk, subk);
4312         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4313           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4314           if (t_original->speculative_type() != nullptr) {
4315             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4316           }
4317         }
4318       }
4319 
4320       bool validated = false;
4321       // Reason_class_check rather than Reason_intrinsic because we
4322       // want to intrinsify even if this traps.
4323       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4324         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4325 
4326         if (not_subtype_ctrl != top()) {
4327           PreserveJVMState pjvms(this);
4328           set_control(not_subtype_ctrl);
4329           uncommon_trap(Deoptimization::Reason_class_check,
4330                         Deoptimization::Action_make_not_entrant);
4331           assert(stopped(), "Should be stopped");
4332         }
4333         validated = true;
4334       }
4335 
4336       if (!stopped()) {
4337         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4338 
4339         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, false,
4340                                                 load_object_klass(original), klass_node);
4341         if (!is_copyOfRange) {
4342           ac->set_copyof(validated);
4343         } else {
4344           ac->set_copyofrange(validated);
4345         }
4346         Node* n = _gvn.transform(ac);
4347         if (n == ac) {
4348           ac->connect_outputs(this);
4349         } else {
4350           assert(validated, "shouldn't transform if all arguments not validated");
4351           set_all_memory(n);
4352         }
4353       }
4354     }
4355   } // original reexecute is set back here
4356 
4357   C->set_has_split_ifs(true); // Has chance for split-if optimization
4358   if (!stopped()) {
4359     set_result(newcopy);
4360   }
4361   return true;
4362 }
4363 
4364 
4365 //----------------------generate_virtual_guard---------------------------
4366 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4367 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4368                                              RegionNode* slow_region) {
4369   ciMethod* method = callee();
4370   int vtable_index = method->vtable_index();
4371   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4372          "bad index %d", vtable_index);
4373   // Get the Method* out of the appropriate vtable entry.
4374   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4375                      vtable_index*vtableEntry::size_in_bytes() +
4376                      in_bytes(vtableEntry::method_offset());
4377   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4378   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4379 
4380   // Compare the target method with the expected method (e.g., Object.hashCode).
4381   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4382 
4383   Node* native_call = makecon(native_call_addr);
4384   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4385   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4386 
4387   return generate_slow_guard(test_native, slow_region);
4388 }
4389 
4390 //-----------------------generate_method_call----------------------------
4391 // Use generate_method_call to make a slow-call to the real
4392 // method if the fast path fails.  An alternative would be to
4393 // use a stub like OptoRuntime::slow_arraycopy_Java.
4394 // This only works for expanding the current library call,
4395 // not another intrinsic.  (E.g., don't use this for making an
4396 // arraycopy call inside of the copyOf intrinsic.)
4397 CallJavaNode*
4398 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4399   // When compiling the intrinsic method itself, do not use this technique.
4400   guarantee(callee() != C->method(), "cannot make slow-call to self");
4401 
4402   ciMethod* method = callee();
4403   // ensure the JVMS we have will be correct for this call
4404   guarantee(method_id == method->intrinsic_id(), "must match");
4405 
4406   const TypeFunc* tf = TypeFunc::make(method);
4407   if (res_not_null) {
4408     assert(tf->return_type() == T_OBJECT, "");
4409     const TypeTuple* range = tf->range();
4410     const Type** fields = TypeTuple::fields(range->cnt());
4411     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4412     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4413     tf = TypeFunc::make(tf->domain(), new_range);
4414   }
4415   CallJavaNode* slow_call;
4416   if (is_static) {
4417     assert(!is_virtual, "");
4418     slow_call = new CallStaticJavaNode(C, tf,
4419                            SharedRuntime::get_resolve_static_call_stub(), method);
4420   } else if (is_virtual) {
4421     null_check_receiver();
4422     int vtable_index = Method::invalid_vtable_index;
4423     if (UseInlineCaches) {
4424       // Suppress the vtable call
4425     } else {
4426       // hashCode and clone are not a miranda methods,
4427       // so the vtable index is fixed.
4428       // No need to use the linkResolver to get it.
4429        vtable_index = method->vtable_index();
4430        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4431               "bad index %d", vtable_index);
4432     }
4433     slow_call = new CallDynamicJavaNode(tf,
4434                           SharedRuntime::get_resolve_virtual_call_stub(),
4435                           method, vtable_index);
4436   } else {  // neither virtual nor static:  opt_virtual
4437     null_check_receiver();
4438     slow_call = new CallStaticJavaNode(C, tf,
4439                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
4440     slow_call->set_optimized_virtual(true);
4441   }
4442   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
4443     // To be able to issue a direct call (optimized virtual or virtual)
4444     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
4445     // about the method being invoked should be attached to the call site to
4446     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
4447     slow_call->set_override_symbolic_info(true);
4448   }
4449   set_arguments_for_java_call(slow_call);
4450   set_edges_for_java_call(slow_call);
4451   return slow_call;
4452 }
4453 
4454 
4455 /**
4456  * Build special case code for calls to hashCode on an object. This call may
4457  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4458  * slightly different code.
4459  */
4460 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4461   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4462   assert(!(is_virtual && is_static), "either virtual, special, or static");
4463 
4464   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4465 
4466   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4467   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4468   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4469   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4470   Node* obj = nullptr;
4471   if (!is_static) {
4472     // Check for hashing null object
4473     obj = null_check_receiver();
4474     if (stopped())  return true;        // unconditionally null
4475     result_reg->init_req(_null_path, top());
4476     result_val->init_req(_null_path, top());
4477   } else {
4478     // Do a null check, and return zero if null.
4479     // System.identityHashCode(null) == 0
4480     obj = argument(0);
4481     Node* null_ctl = top();
4482     obj = null_check_oop(obj, &null_ctl);
4483     result_reg->init_req(_null_path, null_ctl);
4484     result_val->init_req(_null_path, _gvn.intcon(0));
4485   }
4486 
4487   // Unconditionally null?  Then return right away.
4488   if (stopped()) {
4489     set_control( result_reg->in(_null_path));
4490     if (!stopped())
4491       set_result(result_val->in(_null_path));
4492     return true;
4493   }
4494 
4495   // We only go to the fast case code if we pass a number of guards.  The
4496   // paths which do not pass are accumulated in the slow_region.
4497   RegionNode* slow_region = new RegionNode(1);
4498   record_for_igvn(slow_region);
4499 
4500   // If this is a virtual call, we generate a funny guard.  We pull out
4501   // the vtable entry corresponding to hashCode() from the target object.
4502   // If the target method which we are calling happens to be the native
4503   // Object hashCode() method, we pass the guard.  We do not need this
4504   // guard for non-virtual calls -- the caller is known to be the native
4505   // Object hashCode().
4506   if (is_virtual) {
4507     // After null check, get the object's klass.
4508     Node* obj_klass = load_object_klass(obj);
4509     generate_virtual_guard(obj_klass, slow_region);
4510   }
4511 
4512   // Get the header out of the object, use LoadMarkNode when available
4513   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4514   // The control of the load must be null. Otherwise, the load can move before
4515   // the null check after castPP removal.
4516   Node* no_ctrl = nullptr;
4517   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4518 
4519   // Test the header to see if it is unlocked.
4520   Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
4521   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4522   Node *unlocked_val   = _gvn.MakeConX(markWord::unlocked_value);
4523   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4524   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4525 
4526   generate_slow_guard(test_unlocked, slow_region);
4527 
4528   // Get the hash value and check to see that it has been properly assigned.
4529   // We depend on hash_mask being at most 32 bits and avoid the use of
4530   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4531   // vm: see markWord.hpp.
4532   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
4533   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
4534   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4535   // This hack lets the hash bits live anywhere in the mark object now, as long
4536   // as the shift drops the relevant bits into the low 32 bits.  Note that
4537   // Java spec says that HashCode is an int so there's no point in capturing
4538   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4539   hshifted_header      = ConvX2I(hshifted_header);
4540   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4541 
4542   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
4543   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4544   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4545 
4546   generate_slow_guard(test_assigned, slow_region);
4547 
4548   Node* init_mem = reset_memory();
4549   // fill in the rest of the null path:
4550   result_io ->init_req(_null_path, i_o());
4551   result_mem->init_req(_null_path, init_mem);
4552 
4553   result_val->init_req(_fast_path, hash_val);
4554   result_reg->init_req(_fast_path, control());
4555   result_io ->init_req(_fast_path, i_o());
4556   result_mem->init_req(_fast_path, init_mem);
4557 
4558   // Generate code for the slow case.  We make a call to hashCode().
4559   set_control(_gvn.transform(slow_region));
4560   if (!stopped()) {
4561     // No need for PreserveJVMState, because we're using up the present state.
4562     set_all_memory(init_mem);
4563     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4564     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
4565     Node* slow_result = set_results_for_java_call(slow_call);
4566     // this->control() comes from set_results_for_java_call
4567     result_reg->init_req(_slow_path, control());
4568     result_val->init_req(_slow_path, slow_result);
4569     result_io  ->set_req(_slow_path, i_o());
4570     result_mem ->set_req(_slow_path, reset_memory());
4571   }
4572 
4573   // Return the combined state.
4574   set_i_o(        _gvn.transform(result_io)  );
4575   set_all_memory( _gvn.transform(result_mem));
4576 
4577   set_result(result_reg, result_val);
4578   return true;
4579 }
4580 
4581 //---------------------------inline_native_getClass----------------------------
4582 // public final native Class<?> java.lang.Object.getClass();
4583 //
4584 // Build special case code for calls to getClass on an object.
4585 bool LibraryCallKit::inline_native_getClass() {
4586   Node* obj = null_check_receiver();
4587   if (stopped())  return true;
4588   set_result(load_mirror_from_klass(load_object_klass(obj)));
4589   return true;
4590 }
4591 
4592 //-----------------inline_native_Reflection_getCallerClass---------------------
4593 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4594 //
4595 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4596 //
4597 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4598 // in that it must skip particular security frames and checks for
4599 // caller sensitive methods.
4600 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4601 #ifndef PRODUCT
4602   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4603     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4604   }
4605 #endif
4606 
4607   if (!jvms()->has_method()) {
4608 #ifndef PRODUCT
4609     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4610       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4611     }
4612 #endif
4613     return false;
4614   }
4615 
4616   // Walk back up the JVM state to find the caller at the required
4617   // depth.
4618   JVMState* caller_jvms = jvms();
4619 
4620   // Cf. JVM_GetCallerClass
4621   // NOTE: Start the loop at depth 1 because the current JVM state does
4622   // not include the Reflection.getCallerClass() frame.
4623   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
4624     ciMethod* m = caller_jvms->method();
4625     switch (n) {
4626     case 0:
4627       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4628       break;
4629     case 1:
4630       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4631       if (!m->caller_sensitive()) {
4632 #ifndef PRODUCT
4633         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4634           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4635         }
4636 #endif
4637         return false;  // bail-out; let JVM_GetCallerClass do the work
4638       }
4639       break;
4640     default:
4641       if (!m->is_ignored_by_security_stack_walk()) {
4642         // We have reached the desired frame; return the holder class.
4643         // Acquire method holder as java.lang.Class and push as constant.
4644         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4645         ciInstance* caller_mirror = caller_klass->java_mirror();
4646         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4647 
4648 #ifndef PRODUCT
4649         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4650           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());
4651           tty->print_cr("  JVM state at this point:");
4652           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4653             ciMethod* m = jvms()->of_depth(i)->method();
4654             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4655           }
4656         }
4657 #endif
4658         return true;
4659       }
4660       break;
4661     }
4662   }
4663 
4664 #ifndef PRODUCT
4665   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4666     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4667     tty->print_cr("  JVM state at this point:");
4668     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4669       ciMethod* m = jvms()->of_depth(i)->method();
4670       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4671     }
4672   }
4673 #endif
4674 
4675   return false;  // bail-out; let JVM_GetCallerClass do the work
4676 }
4677 
4678 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4679   Node* arg = argument(0);
4680   Node* result = nullptr;
4681 
4682   switch (id) {
4683   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4684   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4685   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4686   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4687   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
4688   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
4689 
4690   case vmIntrinsics::_doubleToLongBits: {
4691     // two paths (plus control) merge in a wood
4692     RegionNode *r = new RegionNode(3);
4693     Node *phi = new PhiNode(r, TypeLong::LONG);
4694 
4695     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4696     // Build the boolean node
4697     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4698 
4699     // Branch either way.
4700     // NaN case is less traveled, which makes all the difference.
4701     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4702     Node *opt_isnan = _gvn.transform(ifisnan);
4703     assert( opt_isnan->is_If(), "Expect an IfNode");
4704     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4705     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4706 
4707     set_control(iftrue);
4708 
4709     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4710     Node *slow_result = longcon(nan_bits); // return NaN
4711     phi->init_req(1, _gvn.transform( slow_result ));
4712     r->init_req(1, iftrue);
4713 
4714     // Else fall through
4715     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4716     set_control(iffalse);
4717 
4718     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4719     r->init_req(2, iffalse);
4720 
4721     // Post merge
4722     set_control(_gvn.transform(r));
4723     record_for_igvn(r);
4724 
4725     C->set_has_split_ifs(true); // Has chance for split-if optimization
4726     result = phi;
4727     assert(result->bottom_type()->isa_long(), "must be");
4728     break;
4729   }
4730 
4731   case vmIntrinsics::_floatToIntBits: {
4732     // two paths (plus control) merge in a wood
4733     RegionNode *r = new RegionNode(3);
4734     Node *phi = new PhiNode(r, TypeInt::INT);
4735 
4736     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4737     // Build the boolean node
4738     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4739 
4740     // Branch either way.
4741     // NaN case is less traveled, which makes all the difference.
4742     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4743     Node *opt_isnan = _gvn.transform(ifisnan);
4744     assert( opt_isnan->is_If(), "Expect an IfNode");
4745     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4746     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4747 
4748     set_control(iftrue);
4749 
4750     static const jint nan_bits = 0x7fc00000;
4751     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4752     phi->init_req(1, _gvn.transform( slow_result ));
4753     r->init_req(1, iftrue);
4754 
4755     // Else fall through
4756     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4757     set_control(iffalse);
4758 
4759     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4760     r->init_req(2, iffalse);
4761 
4762     // Post merge
4763     set_control(_gvn.transform(r));
4764     record_for_igvn(r);
4765 
4766     C->set_has_split_ifs(true); // Has chance for split-if optimization
4767     result = phi;
4768     assert(result->bottom_type()->isa_int(), "must be");
4769     break;
4770   }
4771 
4772   default:
4773     fatal_unexpected_iid(id);
4774     break;
4775   }
4776   set_result(_gvn.transform(result));
4777   return true;
4778 }
4779 
4780 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
4781   Node* arg = argument(0);
4782   Node* result = nullptr;
4783 
4784   switch (id) {
4785   case vmIntrinsics::_floatIsInfinite:
4786     result = new IsInfiniteFNode(arg);
4787     break;
4788   case vmIntrinsics::_floatIsFinite:
4789     result = new IsFiniteFNode(arg);
4790     break;
4791   case vmIntrinsics::_doubleIsInfinite:
4792     result = new IsInfiniteDNode(arg);
4793     break;
4794   case vmIntrinsics::_doubleIsFinite:
4795     result = new IsFiniteDNode(arg);
4796     break;
4797   default:
4798     fatal_unexpected_iid(id);
4799     break;
4800   }
4801   set_result(_gvn.transform(result));
4802   return true;
4803 }
4804 
4805 //----------------------inline_unsafe_copyMemory-------------------------
4806 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4807 
4808 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
4809   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
4810   const Type*       base_t = gvn.type(base);
4811 
4812   bool in_native = (base_t == TypePtr::NULL_PTR);
4813   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
4814   bool is_mixed  = !in_heap && !in_native;
4815 
4816   if (is_mixed) {
4817     return true; // mixed accesses can touch both on-heap and off-heap memory
4818   }
4819   if (in_heap) {
4820     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
4821     if (!is_prim_array) {
4822       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
4823       // there's not enough type information available to determine proper memory slice for it.
4824       return true;
4825     }
4826   }
4827   return false;
4828 }
4829 
4830 bool LibraryCallKit::inline_unsafe_copyMemory() {
4831   if (callee()->is_static())  return false;  // caller must have the capability!
4832   null_check_receiver();  // null-check receiver
4833   if (stopped())  return true;
4834 
4835   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4836 
4837   Node* src_base =         argument(1);  // type: oop
4838   Node* src_off  = ConvL2X(argument(2)); // type: long
4839   Node* dst_base =         argument(4);  // type: oop
4840   Node* dst_off  = ConvL2X(argument(5)); // type: long
4841   Node* size     = ConvL2X(argument(7)); // type: long
4842 
4843   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4844          "fieldOffset must be byte-scaled");
4845 
4846   Node* src_addr = make_unsafe_address(src_base, src_off);
4847   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
4848 
4849   Node* thread = _gvn.transform(new ThreadLocalNode());
4850   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
4851   BasicType doing_unsafe_access_bt = T_BYTE;
4852   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
4853 
4854   // update volatile field
4855   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
4856 
4857   int flags = RC_LEAF | RC_NO_FP;
4858 
4859   const TypePtr* dst_type = TypePtr::BOTTOM;
4860 
4861   // Adjust memory effects of the runtime call based on input values.
4862   if (!has_wide_mem(_gvn, src_addr, src_base) &&
4863       !has_wide_mem(_gvn, dst_addr, dst_base)) {
4864     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
4865 
4866     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
4867     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
4868       flags |= RC_NARROW_MEM; // narrow in memory
4869     }
4870   }
4871 
4872   // Call it.  Note that the length argument is not scaled.
4873   make_runtime_call(flags,
4874                     OptoRuntime::fast_arraycopy_Type(),
4875                     StubRoutines::unsafe_arraycopy(),
4876                     "unsafe_arraycopy",
4877                     dst_type,
4878                     src_addr, dst_addr, size XTOP);
4879 
4880   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
4881 
4882   return true;
4883 }
4884 
4885 #undef XTOP
4886 
4887 //------------------------clone_coping-----------------------------------
4888 // Helper function for inline_native_clone.
4889 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
4890   assert(obj_size != nullptr, "");
4891   Node* raw_obj = alloc_obj->in(1);
4892   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4893 
4894   AllocateNode* alloc = nullptr;
4895   if (ReduceBulkZeroing) {
4896     // We will be completely responsible for initializing this object -
4897     // mark Initialize node as complete.
4898     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4899     // The object was just allocated - there should be no any stores!
4900     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
4901     // Mark as complete_with_arraycopy so that on AllocateNode
4902     // expansion, we know this AllocateNode is initialized by an array
4903     // copy and a StoreStore barrier exists after the array copy.
4904     alloc->initialization()->set_complete_with_arraycopy();
4905   }
4906 
4907   Node* size = _gvn.transform(obj_size);
4908   access_clone(obj, alloc_obj, size, is_array);
4909 
4910   // Do not let reads from the cloned object float above the arraycopy.
4911   if (alloc != nullptr) {
4912     // Do not let stores that initialize this object be reordered with
4913     // a subsequent store that would make this object accessible by
4914     // other threads.
4915     // Record what AllocateNode this StoreStore protects so that
4916     // escape analysis can go from the MemBarStoreStoreNode to the
4917     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4918     // based on the escape status of the AllocateNode.
4919     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
4920   } else {
4921     insert_mem_bar(Op_MemBarCPUOrder);
4922   }
4923 }
4924 
4925 //------------------------inline_native_clone----------------------------
4926 // protected native Object java.lang.Object.clone();
4927 //
4928 // Here are the simple edge cases:
4929 //  null receiver => normal trap
4930 //  virtual and clone was overridden => slow path to out-of-line clone
4931 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4932 //
4933 // The general case has two steps, allocation and copying.
4934 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4935 //
4936 // Copying also has two cases, oop arrays and everything else.
4937 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4938 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4939 //
4940 // These steps fold up nicely if and when the cloned object's klass
4941 // can be sharply typed as an object array, a type array, or an instance.
4942 //
4943 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4944   PhiNode* result_val;
4945 
4946   // Set the reexecute bit for the interpreter to reexecute
4947   // the bytecode that invokes Object.clone if deoptimization happens.
4948   { PreserveReexecuteState preexecs(this);
4949     jvms()->set_should_reexecute(true);
4950 
4951     Node* obj = null_check_receiver();
4952     if (stopped())  return true;
4953 
4954     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4955 
4956     // If we are going to clone an instance, we need its exact type to
4957     // know the number and types of fields to convert the clone to
4958     // loads/stores. Maybe a speculative type can help us.
4959     if (!obj_type->klass_is_exact() &&
4960         obj_type->speculative_type() != nullptr &&
4961         obj_type->speculative_type()->is_instance_klass()) {
4962       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4963       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4964           !spec_ik->has_injected_fields()) {
4965         if (!obj_type->isa_instptr() ||
4966             obj_type->is_instptr()->instance_klass()->has_subklass()) {
4967           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4968         }
4969       }
4970     }
4971 
4972     // Conservatively insert a memory barrier on all memory slices.
4973     // Do not let writes into the original float below the clone.
4974     insert_mem_bar(Op_MemBarCPUOrder);
4975 
4976     // paths into result_reg:
4977     enum {
4978       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4979       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4980       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4981       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4982       PATH_LIMIT
4983     };
4984     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4985     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4986     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4987     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4988     record_for_igvn(result_reg);
4989 
4990     Node* obj_klass = load_object_klass(obj);
4991     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr);
4992     if (array_ctl != nullptr) {
4993       // It's an array.
4994       PreserveJVMState pjvms(this);
4995       set_control(array_ctl);
4996       Node* obj_length = load_array_length(obj);
4997       Node* array_size = nullptr; // Size of the array without object alignment padding.
4998       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
4999 
5000       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5001       if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5002         // If it is an oop array, it requires very special treatment,
5003         // because gc barriers are required when accessing the array.
5004         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5005         if (is_obja != nullptr) {
5006           PreserveJVMState pjvms2(this);
5007           set_control(is_obja);
5008           // Generate a direct call to the right arraycopy function(s).
5009           // Clones are always tightly coupled.
5010           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5011           ac->set_clone_oop_array();
5012           Node* n = _gvn.transform(ac);
5013           assert(n == ac, "cannot disappear");
5014           ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5015 
5016           result_reg->init_req(_objArray_path, control());
5017           result_val->init_req(_objArray_path, alloc_obj);
5018           result_i_o ->set_req(_objArray_path, i_o());
5019           result_mem ->set_req(_objArray_path, reset_memory());
5020         }
5021       }
5022       // Otherwise, there are no barriers to worry about.
5023       // (We can dispense with card marks if we know the allocation
5024       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5025       //  causes the non-eden paths to take compensating steps to
5026       //  simulate a fresh allocation, so that no further
5027       //  card marks are required in compiled code to initialize
5028       //  the object.)
5029 
5030       if (!stopped()) {
5031         copy_to_clone(obj, alloc_obj, array_size, true);
5032 
5033         // Present the results of the copy.
5034         result_reg->init_req(_array_path, control());
5035         result_val->init_req(_array_path, alloc_obj);
5036         result_i_o ->set_req(_array_path, i_o());
5037         result_mem ->set_req(_array_path, reset_memory());
5038       }
5039     }
5040 
5041     // We only go to the instance fast case code if we pass a number of guards.
5042     // The paths which do not pass are accumulated in the slow_region.
5043     RegionNode* slow_region = new RegionNode(1);
5044     record_for_igvn(slow_region);
5045     if (!stopped()) {
5046       // It's an instance (we did array above).  Make the slow-path tests.
5047       // If this is a virtual call, we generate a funny guard.  We grab
5048       // the vtable entry corresponding to clone() from the target object.
5049       // If the target method which we are calling happens to be the
5050       // Object clone() method, we pass the guard.  We do not need this
5051       // guard for non-virtual calls; the caller is known to be the native
5052       // Object clone().
5053       if (is_virtual) {
5054         generate_virtual_guard(obj_klass, slow_region);
5055       }
5056 
5057       // The object must be easily cloneable and must not have a finalizer.
5058       // Both of these conditions may be checked in a single test.
5059       // We could optimize the test further, but we don't care.
5060       generate_access_flags_guard(obj_klass,
5061                                   // Test both conditions:
5062                                   JVM_ACC_IS_CLONEABLE_FAST | JVM_ACC_HAS_FINALIZER,
5063                                   // Must be cloneable but not finalizer:
5064                                   JVM_ACC_IS_CLONEABLE_FAST,
5065                                   slow_region);
5066     }
5067 
5068     if (!stopped()) {
5069       // It's an instance, and it passed the slow-path tests.
5070       PreserveJVMState pjvms(this);
5071       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5072       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5073       // is reexecuted if deoptimization occurs and there could be problems when merging
5074       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5075       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5076 
5077       copy_to_clone(obj, alloc_obj, obj_size, false);
5078 
5079       // Present the results of the slow call.
5080       result_reg->init_req(_instance_path, control());
5081       result_val->init_req(_instance_path, alloc_obj);
5082       result_i_o ->set_req(_instance_path, i_o());
5083       result_mem ->set_req(_instance_path, reset_memory());
5084     }
5085 
5086     // Generate code for the slow case.  We make a call to clone().
5087     set_control(_gvn.transform(slow_region));
5088     if (!stopped()) {
5089       PreserveJVMState pjvms(this);
5090       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5091       // We need to deoptimize on exception (see comment above)
5092       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5093       // this->control() comes from set_results_for_java_call
5094       result_reg->init_req(_slow_path, control());
5095       result_val->init_req(_slow_path, slow_result);
5096       result_i_o ->set_req(_slow_path, i_o());
5097       result_mem ->set_req(_slow_path, reset_memory());
5098     }
5099 
5100     // Return the combined state.
5101     set_control(    _gvn.transform(result_reg));
5102     set_i_o(        _gvn.transform(result_i_o));
5103     set_all_memory( _gvn.transform(result_mem));
5104   } // original reexecute is set back here
5105 
5106   set_result(_gvn.transform(result_val));
5107   return true;
5108 }
5109 
5110 // If we have a tightly coupled allocation, the arraycopy may take care
5111 // of the array initialization. If one of the guards we insert between
5112 // the allocation and the arraycopy causes a deoptimization, an
5113 // uninitialized array will escape the compiled method. To prevent that
5114 // we set the JVM state for uncommon traps between the allocation and
5115 // the arraycopy to the state before the allocation so, in case of
5116 // deoptimization, we'll reexecute the allocation and the
5117 // initialization.
5118 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
5119   if (alloc != nullptr) {
5120     ciMethod* trap_method = alloc->jvms()->method();
5121     int trap_bci = alloc->jvms()->bci();
5122 
5123     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5124         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
5125       // Make sure there's no store between the allocation and the
5126       // arraycopy otherwise visible side effects could be rexecuted
5127       // in case of deoptimization and cause incorrect execution.
5128       bool no_interfering_store = true;
5129       Node* mem = alloc->in(TypeFunc::Memory);
5130       if (mem->is_MergeMem()) {
5131         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
5132           Node* n = mms.memory();
5133           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5134             assert(n->is_Store(), "what else?");
5135             no_interfering_store = false;
5136             break;
5137           }
5138         }
5139       } else {
5140         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
5141           Node* n = mms.memory();
5142           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5143             assert(n->is_Store(), "what else?");
5144             no_interfering_store = false;
5145             break;
5146           }
5147         }
5148       }
5149 
5150       if (no_interfering_store) {
5151         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5152 
5153         JVMState* saved_jvms = jvms();
5154         saved_reexecute_sp = _reexecute_sp;
5155 
5156         set_jvms(sfpt->jvms());
5157         _reexecute_sp = jvms()->sp();
5158 
5159         return saved_jvms;
5160       }
5161     }
5162   }
5163   return nullptr;
5164 }
5165 
5166 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5167 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5168 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5169   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5170   uint size = alloc->req();
5171   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5172   old_jvms->set_map(sfpt);
5173   for (uint i = 0; i < size; i++) {
5174     sfpt->init_req(i, alloc->in(i));
5175   }
5176   // re-push array length for deoptimization
5177   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5178   old_jvms->set_sp(old_jvms->sp()+1);
5179   old_jvms->set_monoff(old_jvms->monoff()+1);
5180   old_jvms->set_scloff(old_jvms->scloff()+1);
5181   old_jvms->set_endoff(old_jvms->endoff()+1);
5182   old_jvms->set_should_reexecute(true);
5183 
5184   sfpt->set_i_o(map()->i_o());
5185   sfpt->set_memory(map()->memory());
5186   sfpt->set_control(map()->control());
5187   return sfpt;
5188 }
5189 
5190 // In case of a deoptimization, we restart execution at the
5191 // allocation, allocating a new array. We would leave an uninitialized
5192 // array in the heap that GCs wouldn't expect. Move the allocation
5193 // after the traps so we don't allocate the array if we
5194 // deoptimize. This is possible because tightly_coupled_allocation()
5195 // guarantees there's no observer of the allocated array at this point
5196 // and the control flow is simple enough.
5197 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5198                                                     int saved_reexecute_sp, uint new_idx) {
5199   if (saved_jvms_before_guards != nullptr && !stopped()) {
5200     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5201 
5202     assert(alloc != nullptr, "only with a tightly coupled allocation");
5203     // restore JVM state to the state at the arraycopy
5204     saved_jvms_before_guards->map()->set_control(map()->control());
5205     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5206     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5207     // If we've improved the types of some nodes (null check) while
5208     // emitting the guards, propagate them to the current state
5209     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5210     set_jvms(saved_jvms_before_guards);
5211     _reexecute_sp = saved_reexecute_sp;
5212 
5213     // Remove the allocation from above the guards
5214     CallProjections callprojs;
5215     alloc->extract_projections(&callprojs, true);
5216     InitializeNode* init = alloc->initialization();
5217     Node* alloc_mem = alloc->in(TypeFunc::Memory);
5218     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5219     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5220 
5221     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5222     // the allocation (i.e. is only valid if the allocation succeeds):
5223     // 1) replace CastIINode with AllocateArrayNode's length here
5224     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5225     //
5226     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5227     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5228     Node* init_control = init->proj_out(TypeFunc::Control);
5229     Node* alloc_length = alloc->Ideal_length();
5230 #ifdef ASSERT
5231     Node* prev_cast = nullptr;
5232 #endif
5233     for (uint i = 0; i < init_control->outcnt(); i++) {
5234       Node* init_out = init_control->raw_out(i);
5235       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5236 #ifdef ASSERT
5237         if (prev_cast == nullptr) {
5238           prev_cast = init_out;
5239         } else {
5240           if (prev_cast->cmp(*init_out) == false) {
5241             prev_cast->dump();
5242             init_out->dump();
5243             assert(false, "not equal CastIINode");
5244           }
5245         }
5246 #endif
5247         C->gvn_replace_by(init_out, alloc_length);
5248       }
5249     }
5250     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5251 
5252     // move the allocation here (after the guards)
5253     _gvn.hash_delete(alloc);
5254     alloc->set_req(TypeFunc::Control, control());
5255     alloc->set_req(TypeFunc::I_O, i_o());
5256     Node *mem = reset_memory();
5257     set_all_memory(mem);
5258     alloc->set_req(TypeFunc::Memory, mem);
5259     set_control(init->proj_out_or_null(TypeFunc::Control));
5260     set_i_o(callprojs.fallthrough_ioproj);
5261 
5262     // Update memory as done in GraphKit::set_output_for_allocation()
5263     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5264     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5265     if (ary_type->isa_aryptr() && length_type != nullptr) {
5266       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5267     }
5268     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5269     int            elemidx  = C->get_alias_index(telemref);
5270     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5271     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5272 
5273     Node* allocx = _gvn.transform(alloc);
5274     assert(allocx == alloc, "where has the allocation gone?");
5275     assert(dest->is_CheckCastPP(), "not an allocation result?");
5276 
5277     _gvn.hash_delete(dest);
5278     dest->set_req(0, control());
5279     Node* destx = _gvn.transform(dest);
5280     assert(destx == dest, "where has the allocation result gone?");
5281 
5282     array_ideal_length(alloc, ary_type, true);
5283   }
5284 }
5285 
5286 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
5287 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
5288 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
5289 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
5290 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
5291 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
5292 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
5293                                                                        JVMState* saved_jvms_before_guards) {
5294   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
5295     // There is at least one unrelated uncommon trap which needs to be replaced.
5296     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5297 
5298     JVMState* saved_jvms = jvms();
5299     const int saved_reexecute_sp = _reexecute_sp;
5300     set_jvms(sfpt->jvms());
5301     _reexecute_sp = jvms()->sp();
5302 
5303     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
5304 
5305     // Restore state
5306     set_jvms(saved_jvms);
5307     _reexecute_sp = saved_reexecute_sp;
5308   }
5309 }
5310 
5311 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
5312 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
5313 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
5314   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
5315   while (if_proj->is_IfProj()) {
5316     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
5317     if (uncommon_trap != nullptr) {
5318       create_new_uncommon_trap(uncommon_trap);
5319     }
5320     assert(if_proj->in(0)->is_If(), "must be If");
5321     if_proj = if_proj->in(0)->in(0);
5322   }
5323   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
5324          "must have reached control projection of init node");
5325 }
5326 
5327 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
5328   const int trap_request = uncommon_trap_call->uncommon_trap_request();
5329   assert(trap_request != 0, "no valid UCT trap request");
5330   PreserveJVMState pjvms(this);
5331   set_control(uncommon_trap_call->in(0));
5332   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
5333                 Deoptimization::trap_request_action(trap_request));
5334   assert(stopped(), "Should be stopped");
5335   _gvn.hash_delete(uncommon_trap_call);
5336   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
5337 }
5338 
5339 //------------------------------inline_arraycopy-----------------------
5340 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
5341 //                                                      Object dest, int destPos,
5342 //                                                      int length);
5343 bool LibraryCallKit::inline_arraycopy() {
5344   // Get the arguments.
5345   Node* src         = argument(0);  // type: oop
5346   Node* src_offset  = argument(1);  // type: int
5347   Node* dest        = argument(2);  // type: oop
5348   Node* dest_offset = argument(3);  // type: int
5349   Node* length      = argument(4);  // type: int
5350 
5351   uint new_idx = C->unique();
5352 
5353   // Check for allocation before we add nodes that would confuse
5354   // tightly_coupled_allocation()
5355   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
5356 
5357   int saved_reexecute_sp = -1;
5358   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
5359   // See arraycopy_restore_alloc_state() comment
5360   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
5361   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
5362   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
5363   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
5364 
5365   // The following tests must be performed
5366   // (1) src and dest are arrays.
5367   // (2) src and dest arrays must have elements of the same BasicType
5368   // (3) src and dest must not be null.
5369   // (4) src_offset must not be negative.
5370   // (5) dest_offset must not be negative.
5371   // (6) length must not be negative.
5372   // (7) src_offset + length must not exceed length of src.
5373   // (8) dest_offset + length must not exceed length of dest.
5374   // (9) each element of an oop array must be assignable
5375 
5376   // (3) src and dest must not be null.
5377   // always do this here because we need the JVM state for uncommon traps
5378   Node* null_ctl = top();
5379   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
5380   assert(null_ctl->is_top(), "no null control here");
5381   dest = null_check(dest, T_ARRAY);
5382 
5383   if (!can_emit_guards) {
5384     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
5385     // guards but the arraycopy node could still take advantage of a
5386     // tightly allocated allocation. tightly_coupled_allocation() is
5387     // called again to make sure it takes the null check above into
5388     // account: the null check is mandatory and if it caused an
5389     // uncommon trap to be emitted then the allocation can't be
5390     // considered tightly coupled in this context.
5391     alloc = tightly_coupled_allocation(dest);
5392   }
5393 
5394   bool validated = false;
5395 
5396   const Type* src_type  = _gvn.type(src);
5397   const Type* dest_type = _gvn.type(dest);
5398   const TypeAryPtr* top_src  = src_type->isa_aryptr();
5399   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5400 
5401   // Do we have the type of src?
5402   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5403   // Do we have the type of dest?
5404   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5405   // Is the type for src from speculation?
5406   bool src_spec = false;
5407   // Is the type for dest from speculation?
5408   bool dest_spec = false;
5409 
5410   if ((!has_src || !has_dest) && can_emit_guards) {
5411     // We don't have sufficient type information, let's see if
5412     // speculative types can help. We need to have types for both src
5413     // and dest so that it pays off.
5414 
5415     // Do we already have or could we have type information for src
5416     bool could_have_src = has_src;
5417     // Do we already have or could we have type information for dest
5418     bool could_have_dest = has_dest;
5419 
5420     ciKlass* src_k = nullptr;
5421     if (!has_src) {
5422       src_k = src_type->speculative_type_not_null();
5423       if (src_k != nullptr && src_k->is_array_klass()) {
5424         could_have_src = true;
5425       }
5426     }
5427 
5428     ciKlass* dest_k = nullptr;
5429     if (!has_dest) {
5430       dest_k = dest_type->speculative_type_not_null();
5431       if (dest_k != nullptr && dest_k->is_array_klass()) {
5432         could_have_dest = true;
5433       }
5434     }
5435 
5436     if (could_have_src && could_have_dest) {
5437       // This is going to pay off so emit the required guards
5438       if (!has_src) {
5439         src = maybe_cast_profiled_obj(src, src_k, true);
5440         src_type  = _gvn.type(src);
5441         top_src  = src_type->isa_aryptr();
5442         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5443         src_spec = true;
5444       }
5445       if (!has_dest) {
5446         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5447         dest_type  = _gvn.type(dest);
5448         top_dest  = dest_type->isa_aryptr();
5449         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5450         dest_spec = true;
5451       }
5452     }
5453   }
5454 
5455   if (has_src && has_dest && can_emit_guards) {
5456     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5457     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5458     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5459     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5460 
5461     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5462       // If both arrays are object arrays then having the exact types
5463       // for both will remove the need for a subtype check at runtime
5464       // before the call and may make it possible to pick a faster copy
5465       // routine (without a subtype check on every element)
5466       // Do we have the exact type of src?
5467       bool could_have_src = src_spec;
5468       // Do we have the exact type of dest?
5469       bool could_have_dest = dest_spec;
5470       ciKlass* src_k = nullptr;
5471       ciKlass* dest_k = nullptr;
5472       if (!src_spec) {
5473         src_k = src_type->speculative_type_not_null();
5474         if (src_k != nullptr && src_k->is_array_klass()) {
5475           could_have_src = true;
5476         }
5477       }
5478       if (!dest_spec) {
5479         dest_k = dest_type->speculative_type_not_null();
5480         if (dest_k != nullptr && dest_k->is_array_klass()) {
5481           could_have_dest = true;
5482         }
5483       }
5484       if (could_have_src && could_have_dest) {
5485         // If we can have both exact types, emit the missing guards
5486         if (could_have_src && !src_spec) {
5487           src = maybe_cast_profiled_obj(src, src_k, true);
5488         }
5489         if (could_have_dest && !dest_spec) {
5490           dest = maybe_cast_profiled_obj(dest, dest_k, true);
5491         }
5492       }
5493     }
5494   }
5495 
5496   ciMethod* trap_method = method();
5497   int trap_bci = bci();
5498   if (saved_jvms_before_guards != nullptr) {
5499     trap_method = alloc->jvms()->method();
5500     trap_bci = alloc->jvms()->bci();
5501   }
5502 
5503   bool negative_length_guard_generated = false;
5504 
5505   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5506       can_emit_guards &&
5507       !src->is_top() && !dest->is_top()) {
5508     // validate arguments: enables transformation the ArrayCopyNode
5509     validated = true;
5510 
5511     RegionNode* slow_region = new RegionNode(1);
5512     record_for_igvn(slow_region);
5513 
5514     // (1) src and dest are arrays.
5515     generate_non_array_guard(load_object_klass(src), slow_region);
5516     generate_non_array_guard(load_object_klass(dest), slow_region);
5517 
5518     // (2) src and dest arrays must have elements of the same BasicType
5519     // done at macro expansion or at Ideal transformation time
5520 
5521     // (4) src_offset must not be negative.
5522     generate_negative_guard(src_offset, slow_region);
5523 
5524     // (5) dest_offset must not be negative.
5525     generate_negative_guard(dest_offset, slow_region);
5526 
5527     // (7) src_offset + length must not exceed length of src.
5528     generate_limit_guard(src_offset, length,
5529                          load_array_length(src),
5530                          slow_region);
5531 
5532     // (8) dest_offset + length must not exceed length of dest.
5533     generate_limit_guard(dest_offset, length,
5534                          load_array_length(dest),
5535                          slow_region);
5536 
5537     // (6) length must not be negative.
5538     // This is also checked in generate_arraycopy() during macro expansion, but
5539     // we also have to check it here for the case where the ArrayCopyNode will
5540     // be eliminated by Escape Analysis.
5541     if (EliminateAllocations) {
5542       generate_negative_guard(length, slow_region);
5543       negative_length_guard_generated = true;
5544     }
5545 
5546     // (9) each element of an oop array must be assignable
5547     Node* dest_klass = load_object_klass(dest);
5548     if (src != dest) {
5549       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5550 
5551       if (not_subtype_ctrl != top()) {
5552         PreserveJVMState pjvms(this);
5553         set_control(not_subtype_ctrl);
5554         uncommon_trap(Deoptimization::Reason_intrinsic,
5555                       Deoptimization::Action_make_not_entrant);
5556         assert(stopped(), "Should be stopped");
5557       }
5558     }
5559     {
5560       PreserveJVMState pjvms(this);
5561       set_control(_gvn.transform(slow_region));
5562       uncommon_trap(Deoptimization::Reason_intrinsic,
5563                     Deoptimization::Action_make_not_entrant);
5564       assert(stopped(), "Should be stopped");
5565     }
5566 
5567     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5568     const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
5569     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
5570     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
5571   }
5572 
5573   if (stopped()) {
5574     return true;
5575   }
5576 
5577   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
5578                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5579                                           // so the compiler has a chance to eliminate them: during macro expansion,
5580                                           // we have to set their control (CastPP nodes are eliminated).
5581                                           load_object_klass(src), load_object_klass(dest),
5582                                           load_array_length(src), load_array_length(dest));
5583 
5584   ac->set_arraycopy(validated);
5585 
5586   Node* n = _gvn.transform(ac);
5587   if (n == ac) {
5588     ac->connect_outputs(this);
5589   } else {
5590     assert(validated, "shouldn't transform if all arguments not validated");
5591     set_all_memory(n);
5592   }
5593   clear_upper_avx();
5594 
5595 
5596   return true;
5597 }
5598 
5599 
5600 // Helper function which determines if an arraycopy immediately follows
5601 // an allocation, with no intervening tests or other escapes for the object.
5602 AllocateArrayNode*
5603 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
5604   if (stopped())             return nullptr;  // no fast path
5605   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
5606 
5607   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5608   if (alloc == nullptr)  return nullptr;
5609 
5610   Node* rawmem = memory(Compile::AliasIdxRaw);
5611   // Is the allocation's memory state untouched?
5612   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5613     // Bail out if there have been raw-memory effects since the allocation.
5614     // (Example:  There might have been a call or safepoint.)
5615     return nullptr;
5616   }
5617   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5618   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5619     return nullptr;
5620   }
5621 
5622   // There must be no unexpected observers of this allocation.
5623   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5624     Node* obs = ptr->fast_out(i);
5625     if (obs != this->map()) {
5626       return nullptr;
5627     }
5628   }
5629 
5630   // This arraycopy must unconditionally follow the allocation of the ptr.
5631   Node* alloc_ctl = ptr->in(0);
5632   Node* ctl = control();
5633   while (ctl != alloc_ctl) {
5634     // There may be guards which feed into the slow_region.
5635     // Any other control flow means that we might not get a chance
5636     // to finish initializing the allocated object.
5637     // Various low-level checks bottom out in uncommon traps. These
5638     // are considered safe since we've already checked above that
5639     // there is no unexpected observer of this allocation.
5640     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
5641       assert(ctl->in(0)->is_If(), "must be If");
5642       ctl = ctl->in(0)->in(0);
5643     } else {
5644       return nullptr;
5645     }
5646   }
5647 
5648   // If we get this far, we have an allocation which immediately
5649   // precedes the arraycopy, and we can take over zeroing the new object.
5650   // The arraycopy will finish the initialization, and provide
5651   // a new control state to which we will anchor the destination pointer.
5652 
5653   return alloc;
5654 }
5655 
5656 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
5657   if (node->is_IfProj()) {
5658     Node* other_proj = node->as_IfProj()->other_if_proj();
5659     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
5660       Node* obs = other_proj->fast_out(j);
5661       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
5662           (obs->as_CallStaticJava()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5663         return obs->as_CallStaticJava();
5664       }
5665     }
5666   }
5667   return nullptr;
5668 }
5669 
5670 //-------------inline_encodeISOArray-----------------------------------
5671 // encode char[] to byte[] in ISO_8859_1 or ASCII
5672 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
5673   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5674   // no receiver since it is static method
5675   Node *src         = argument(0);
5676   Node *src_offset  = argument(1);
5677   Node *dst         = argument(2);
5678   Node *dst_offset  = argument(3);
5679   Node *length      = argument(4);
5680 
5681   src = must_be_not_null(src, true);
5682   dst = must_be_not_null(dst, true);
5683 
5684   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
5685   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
5686   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
5687       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
5688     // failed array check
5689     return false;
5690   }
5691 
5692   // Figure out the size and type of the elements we will be copying.
5693   BasicType src_elem = src_type->elem()->array_element_basic_type();
5694   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
5695   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
5696     return false;
5697   }
5698 
5699   Node* src_start = array_element_address(src, src_offset, T_CHAR);
5700   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5701   // 'src_start' points to src array + scaled offset
5702   // 'dst_start' points to dst array + scaled offset
5703 
5704   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5705   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
5706   enc = _gvn.transform(enc);
5707   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5708   set_memory(res_mem, mtype);
5709   set_result(enc);
5710   clear_upper_avx();
5711 
5712   return true;
5713 }
5714 
5715 //-------------inline_multiplyToLen-----------------------------------
5716 bool LibraryCallKit::inline_multiplyToLen() {
5717   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5718 
5719   address stubAddr = StubRoutines::multiplyToLen();
5720   if (stubAddr == nullptr) {
5721     return false; // Intrinsic's stub is not implemented on this platform
5722   }
5723   const char* stubName = "multiplyToLen";
5724 
5725   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5726 
5727   // no receiver because it is a static method
5728   Node* x    = argument(0);
5729   Node* xlen = argument(1);
5730   Node* y    = argument(2);
5731   Node* ylen = argument(3);
5732   Node* z    = argument(4);
5733 
5734   x = must_be_not_null(x, true);
5735   y = must_be_not_null(y, true);
5736 
5737   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
5738   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
5739   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
5740       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
5741     // failed array check
5742     return false;
5743   }
5744 
5745   BasicType x_elem = x_type->elem()->array_element_basic_type();
5746   BasicType y_elem = y_type->elem()->array_element_basic_type();
5747   if (x_elem != T_INT || y_elem != T_INT) {
5748     return false;
5749   }
5750 
5751   // Set the original stack and the reexecute bit for the interpreter to reexecute
5752   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5753   // on the return from z array allocation in runtime.
5754   { PreserveReexecuteState preexecs(this);
5755     jvms()->set_should_reexecute(true);
5756 
5757     Node* x_start = array_element_address(x, intcon(0), x_elem);
5758     Node* y_start = array_element_address(y, intcon(0), y_elem);
5759     // 'x_start' points to x array + scaled xlen
5760     // 'y_start' points to y array + scaled ylen
5761 
5762     // Allocate the result array
5763     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5764     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5765     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5766 
5767     IdealKit ideal(this);
5768 
5769 #define __ ideal.
5770      Node* one = __ ConI(1);
5771      Node* zero = __ ConI(0);
5772      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5773      __ set(need_alloc, zero);
5774      __ set(z_alloc, z);
5775      __ if_then(z, BoolTest::eq, null()); {
5776        __ increment (need_alloc, one);
5777      } __ else_(); {
5778        // Update graphKit memory and control from IdealKit.
5779        sync_kit(ideal);
5780        Node *cast = new CastPPNode(z, TypePtr::NOTNULL);
5781        cast->init_req(0, control());
5782        _gvn.set_type(cast, cast->bottom_type());
5783        C->record_for_igvn(cast);
5784 
5785        Node* zlen_arg = load_array_length(cast);
5786        // Update IdealKit memory and control from graphKit.
5787        __ sync_kit(this);
5788        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5789          __ increment (need_alloc, one);
5790        } __ end_if();
5791      } __ end_if();
5792 
5793      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5794        // Update graphKit memory and control from IdealKit.
5795        sync_kit(ideal);
5796        Node * narr = new_array(klass_node, zlen, 1);
5797        // Update IdealKit memory and control from graphKit.
5798        __ sync_kit(this);
5799        __ set(z_alloc, narr);
5800      } __ end_if();
5801 
5802      sync_kit(ideal);
5803      z = __ value(z_alloc);
5804      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5805      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5806      // Final sync IdealKit and GraphKit.
5807      final_sync(ideal);
5808 #undef __
5809 
5810     Node* z_start = array_element_address(z, intcon(0), T_INT);
5811 
5812     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5813                                    OptoRuntime::multiplyToLen_Type(),
5814                                    stubAddr, stubName, TypePtr::BOTTOM,
5815                                    x_start, xlen, y_start, ylen, z_start, zlen);
5816   } // original reexecute is set back here
5817 
5818   C->set_has_split_ifs(true); // Has chance for split-if optimization
5819   set_result(z);
5820   return true;
5821 }
5822 
5823 //-------------inline_squareToLen------------------------------------
5824 bool LibraryCallKit::inline_squareToLen() {
5825   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
5826 
5827   address stubAddr = StubRoutines::squareToLen();
5828   if (stubAddr == nullptr) {
5829     return false; // Intrinsic's stub is not implemented on this platform
5830   }
5831   const char* stubName = "squareToLen";
5832 
5833   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5834 
5835   Node* x    = argument(0);
5836   Node* len  = argument(1);
5837   Node* z    = argument(2);
5838   Node* zlen = argument(3);
5839 
5840   x = must_be_not_null(x, true);
5841   z = must_be_not_null(z, true);
5842 
5843   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
5844   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
5845   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
5846       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
5847     // failed array check
5848     return false;
5849   }
5850 
5851   BasicType x_elem = x_type->elem()->array_element_basic_type();
5852   BasicType z_elem = z_type->elem()->array_element_basic_type();
5853   if (x_elem != T_INT || z_elem != T_INT) {
5854     return false;
5855   }
5856 
5857 
5858   Node* x_start = array_element_address(x, intcon(0), x_elem);
5859   Node* z_start = array_element_address(z, intcon(0), z_elem);
5860 
5861   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5862                                   OptoRuntime::squareToLen_Type(),
5863                                   stubAddr, stubName, TypePtr::BOTTOM,
5864                                   x_start, len, z_start, zlen);
5865 
5866   set_result(z);
5867   return true;
5868 }
5869 
5870 //-------------inline_mulAdd------------------------------------------
5871 bool LibraryCallKit::inline_mulAdd() {
5872   assert(UseMulAddIntrinsic, "not implemented on this platform");
5873 
5874   address stubAddr = StubRoutines::mulAdd();
5875   if (stubAddr == nullptr) {
5876     return false; // Intrinsic's stub is not implemented on this platform
5877   }
5878   const char* stubName = "mulAdd";
5879 
5880   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5881 
5882   Node* out      = argument(0);
5883   Node* in       = argument(1);
5884   Node* offset   = argument(2);
5885   Node* len      = argument(3);
5886   Node* k        = argument(4);
5887 
5888   in = must_be_not_null(in, true);
5889   out = must_be_not_null(out, true);
5890 
5891   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
5892   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
5893   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
5894        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
5895     // failed array check
5896     return false;
5897   }
5898 
5899   BasicType out_elem = out_type->elem()->array_element_basic_type();
5900   BasicType in_elem = in_type->elem()->array_element_basic_type();
5901   if (out_elem != T_INT || in_elem != T_INT) {
5902     return false;
5903   }
5904 
5905   Node* outlen = load_array_length(out);
5906   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5907   Node* out_start = array_element_address(out, intcon(0), out_elem);
5908   Node* in_start = array_element_address(in, intcon(0), in_elem);
5909 
5910   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5911                                   OptoRuntime::mulAdd_Type(),
5912                                   stubAddr, stubName, TypePtr::BOTTOM,
5913                                   out_start,in_start, new_offset, len, k);
5914   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5915   set_result(result);
5916   return true;
5917 }
5918 
5919 //-------------inline_montgomeryMultiply-----------------------------------
5920 bool LibraryCallKit::inline_montgomeryMultiply() {
5921   address stubAddr = StubRoutines::montgomeryMultiply();
5922   if (stubAddr == nullptr) {
5923     return false; // Intrinsic's stub is not implemented on this platform
5924   }
5925 
5926   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5927   const char* stubName = "montgomery_multiply";
5928 
5929   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5930 
5931   Node* a    = argument(0);
5932   Node* b    = argument(1);
5933   Node* n    = argument(2);
5934   Node* len  = argument(3);
5935   Node* inv  = argument(4);
5936   Node* m    = argument(6);
5937 
5938   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
5939   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
5940   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
5941   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
5942   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
5943       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
5944       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
5945       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
5946     // failed array check
5947     return false;
5948   }
5949 
5950   BasicType a_elem = a_type->elem()->array_element_basic_type();
5951   BasicType b_elem = b_type->elem()->array_element_basic_type();
5952   BasicType n_elem = n_type->elem()->array_element_basic_type();
5953   BasicType m_elem = m_type->elem()->array_element_basic_type();
5954   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5955     return false;
5956   }
5957 
5958   // Make the call
5959   {
5960     Node* a_start = array_element_address(a, intcon(0), a_elem);
5961     Node* b_start = array_element_address(b, intcon(0), b_elem);
5962     Node* n_start = array_element_address(n, intcon(0), n_elem);
5963     Node* m_start = array_element_address(m, intcon(0), m_elem);
5964 
5965     Node* call = make_runtime_call(RC_LEAF,
5966                                    OptoRuntime::montgomeryMultiply_Type(),
5967                                    stubAddr, stubName, TypePtr::BOTTOM,
5968                                    a_start, b_start, n_start, len, inv, top(),
5969                                    m_start);
5970     set_result(m);
5971   }
5972 
5973   return true;
5974 }
5975 
5976 bool LibraryCallKit::inline_montgomerySquare() {
5977   address stubAddr = StubRoutines::montgomerySquare();
5978   if (stubAddr == nullptr) {
5979     return false; // Intrinsic's stub is not implemented on this platform
5980   }
5981 
5982   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5983   const char* stubName = "montgomery_square";
5984 
5985   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5986 
5987   Node* a    = argument(0);
5988   Node* n    = argument(1);
5989   Node* len  = argument(2);
5990   Node* inv  = argument(3);
5991   Node* m    = argument(5);
5992 
5993   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
5994   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
5995   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
5996   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
5997       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
5998       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
5999     // failed array check
6000     return false;
6001   }
6002 
6003   BasicType a_elem = a_type->elem()->array_element_basic_type();
6004   BasicType n_elem = n_type->elem()->array_element_basic_type();
6005   BasicType m_elem = m_type->elem()->array_element_basic_type();
6006   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6007     return false;
6008   }
6009 
6010   // Make the call
6011   {
6012     Node* a_start = array_element_address(a, intcon(0), a_elem);
6013     Node* n_start = array_element_address(n, intcon(0), n_elem);
6014     Node* m_start = array_element_address(m, intcon(0), m_elem);
6015 
6016     Node* call = make_runtime_call(RC_LEAF,
6017                                    OptoRuntime::montgomerySquare_Type(),
6018                                    stubAddr, stubName, TypePtr::BOTTOM,
6019                                    a_start, n_start, len, inv, top(),
6020                                    m_start);
6021     set_result(m);
6022   }
6023 
6024   return true;
6025 }
6026 
6027 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
6028   address stubAddr = nullptr;
6029   const char* stubName = nullptr;
6030 
6031   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
6032   if (stubAddr == nullptr) {
6033     return false; // Intrinsic's stub is not implemented on this platform
6034   }
6035 
6036   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
6037 
6038   assert(callee()->signature()->size() == 5, "expected 5 arguments");
6039 
6040   Node* newArr = argument(0);
6041   Node* oldArr = argument(1);
6042   Node* newIdx = argument(2);
6043   Node* shiftCount = argument(3);
6044   Node* numIter = argument(4);
6045 
6046   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
6047   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
6048   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
6049       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
6050     return false;
6051   }
6052 
6053   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
6054   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
6055   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
6056     return false;
6057   }
6058 
6059   // Make the call
6060   {
6061     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
6062     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
6063 
6064     Node* call = make_runtime_call(RC_LEAF,
6065                                    OptoRuntime::bigIntegerShift_Type(),
6066                                    stubAddr,
6067                                    stubName,
6068                                    TypePtr::BOTTOM,
6069                                    newArr_start,
6070                                    oldArr_start,
6071                                    newIdx,
6072                                    shiftCount,
6073                                    numIter);
6074   }
6075 
6076   return true;
6077 }
6078 
6079 //-------------inline_vectorizedMismatch------------------------------
6080 bool LibraryCallKit::inline_vectorizedMismatch() {
6081   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
6082 
6083   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
6084   Node* obja    = argument(0); // Object
6085   Node* aoffset = argument(1); // long
6086   Node* objb    = argument(3); // Object
6087   Node* boffset = argument(4); // long
6088   Node* length  = argument(6); // int
6089   Node* scale   = argument(7); // int
6090 
6091   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
6092   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
6093   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
6094       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
6095       scale == top()) {
6096     return false; // failed input validation
6097   }
6098 
6099   Node* obja_adr = make_unsafe_address(obja, aoffset);
6100   Node* objb_adr = make_unsafe_address(objb, boffset);
6101 
6102   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
6103   //
6104   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
6105   //    if (length <= inline_limit) {
6106   //      inline_path:
6107   //        vmask   = VectorMaskGen length
6108   //        vload1  = LoadVectorMasked obja, vmask
6109   //        vload2  = LoadVectorMasked objb, vmask
6110   //        result1 = VectorCmpMasked vload1, vload2, vmask
6111   //    } else {
6112   //      call_stub_path:
6113   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
6114   //    }
6115   //    exit_block:
6116   //      return Phi(result1, result2);
6117   //
6118   enum { inline_path = 1,  // input is small enough to process it all at once
6119          stub_path   = 2,  // input is too large; call into the VM
6120          PATH_LIMIT  = 3
6121   };
6122 
6123   Node* exit_block = new RegionNode(PATH_LIMIT);
6124   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
6125   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
6126 
6127   Node* call_stub_path = control();
6128 
6129   BasicType elem_bt = T_ILLEGAL;
6130 
6131   const TypeInt* scale_t = _gvn.type(scale)->is_int();
6132   if (scale_t->is_con()) {
6133     switch (scale_t->get_con()) {
6134       case 0: elem_bt = T_BYTE;  break;
6135       case 1: elem_bt = T_SHORT; break;
6136       case 2: elem_bt = T_INT;   break;
6137       case 3: elem_bt = T_LONG;  break;
6138 
6139       default: elem_bt = T_ILLEGAL; break; // not supported
6140     }
6141   }
6142 
6143   int inline_limit = 0;
6144   bool do_partial_inline = false;
6145 
6146   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
6147     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
6148     do_partial_inline = inline_limit >= 16;
6149   }
6150 
6151   if (do_partial_inline) {
6152     assert(elem_bt != T_ILLEGAL, "sanity");
6153 
6154     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
6155         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
6156         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
6157 
6158       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
6159       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
6160       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
6161 
6162       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
6163 
6164       if (!stopped()) {
6165         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
6166 
6167         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
6168         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
6169         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
6170         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
6171 
6172         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
6173         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
6174         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
6175         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
6176 
6177         exit_block->init_req(inline_path, control());
6178         memory_phi->init_req(inline_path, map()->memory());
6179         result_phi->init_req(inline_path, result);
6180 
6181         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
6182         clear_upper_avx();
6183       }
6184     }
6185   }
6186 
6187   if (call_stub_path != nullptr) {
6188     set_control(call_stub_path);
6189 
6190     Node* call = make_runtime_call(RC_LEAF,
6191                                    OptoRuntime::vectorizedMismatch_Type(),
6192                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
6193                                    obja_adr, objb_adr, length, scale);
6194 
6195     exit_block->init_req(stub_path, control());
6196     memory_phi->init_req(stub_path, map()->memory());
6197     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
6198   }
6199 
6200   exit_block = _gvn.transform(exit_block);
6201   memory_phi = _gvn.transform(memory_phi);
6202   result_phi = _gvn.transform(result_phi);
6203 
6204   set_control(exit_block);
6205   set_all_memory(memory_phi);
6206   set_result(result_phi);
6207 
6208   return true;
6209 }
6210 
6211 //------------------------------inline_vectorizedHashcode----------------------------
6212 bool LibraryCallKit::inline_vectorizedHashCode() {
6213   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
6214 
6215   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
6216   Node* array          = argument(0);
6217   Node* offset         = argument(1);
6218   Node* length         = argument(2);
6219   Node* initialValue   = argument(3);
6220   Node* basic_type     = argument(4);
6221 
6222   if (basic_type == top()) {
6223     return false; // failed input validation
6224   }
6225 
6226   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
6227   if (!basic_type_t->is_con()) {
6228     return false; // Only intrinsify if mode argument is constant
6229   }
6230 
6231   array = must_be_not_null(array, true);
6232 
6233   BasicType bt = (BasicType)basic_type_t->get_con();
6234 
6235   // Resolve address of first element
6236   Node* array_start = array_element_address(array, offset, bt);
6237 
6238   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
6239     array_start, length, initialValue, basic_type)));
6240   clear_upper_avx();
6241 
6242   return true;
6243 }
6244 
6245 /**
6246  * Calculate CRC32 for byte.
6247  * int java.util.zip.CRC32.update(int crc, int b)
6248  */
6249 bool LibraryCallKit::inline_updateCRC32() {
6250   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
6251   assert(callee()->signature()->size() == 2, "update has 2 parameters");
6252   // no receiver since it is static method
6253   Node* crc  = argument(0); // type: int
6254   Node* b    = argument(1); // type: int
6255 
6256   /*
6257    *    int c = ~ crc;
6258    *    b = timesXtoThe32[(b ^ c) & 0xFF];
6259    *    b = b ^ (c >>> 8);
6260    *    crc = ~b;
6261    */
6262 
6263   Node* M1 = intcon(-1);
6264   crc = _gvn.transform(new XorINode(crc, M1));
6265   Node* result = _gvn.transform(new XorINode(crc, b));
6266   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
6267 
6268   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
6269   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
6270   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
6271   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
6272 
6273   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
6274   result = _gvn.transform(new XorINode(crc, result));
6275   result = _gvn.transform(new XorINode(result, M1));
6276   set_result(result);
6277   return true;
6278 }
6279 
6280 /**
6281  * Calculate CRC32 for byte[] array.
6282  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
6283  */
6284 bool LibraryCallKit::inline_updateBytesCRC32() {
6285   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
6286   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6287   // no receiver since it is static method
6288   Node* crc     = argument(0); // type: int
6289   Node* src     = argument(1); // type: oop
6290   Node* offset  = argument(2); // type: int
6291   Node* length  = argument(3); // type: int
6292 
6293   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6294   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6295     // failed array check
6296     return false;
6297   }
6298 
6299   // Figure out the size and type of the elements we will be copying.
6300   BasicType src_elem = src_type->elem()->array_element_basic_type();
6301   if (src_elem != T_BYTE) {
6302     return false;
6303   }
6304 
6305   // 'src_start' points to src array + scaled offset
6306   src = must_be_not_null(src, true);
6307   Node* src_start = array_element_address(src, offset, src_elem);
6308 
6309   // We assume that range check is done by caller.
6310   // TODO: generate range check (offset+length < src.length) in debug VM.
6311 
6312   // Call the stub.
6313   address stubAddr = StubRoutines::updateBytesCRC32();
6314   const char *stubName = "updateBytesCRC32";
6315 
6316   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6317                                  stubAddr, stubName, TypePtr::BOTTOM,
6318                                  crc, src_start, length);
6319   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6320   set_result(result);
6321   return true;
6322 }
6323 
6324 /**
6325  * Calculate CRC32 for ByteBuffer.
6326  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
6327  */
6328 bool LibraryCallKit::inline_updateByteBufferCRC32() {
6329   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
6330   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6331   // no receiver since it is static method
6332   Node* crc     = argument(0); // type: int
6333   Node* src     = argument(1); // type: long
6334   Node* offset  = argument(3); // type: int
6335   Node* length  = argument(4); // type: int
6336 
6337   src = ConvL2X(src);  // adjust Java long to machine word
6338   Node* base = _gvn.transform(new CastX2PNode(src));
6339   offset = ConvI2X(offset);
6340 
6341   // 'src_start' points to src array + scaled offset
6342   Node* src_start = basic_plus_adr(top(), base, offset);
6343 
6344   // Call the stub.
6345   address stubAddr = StubRoutines::updateBytesCRC32();
6346   const char *stubName = "updateBytesCRC32";
6347 
6348   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6349                                  stubAddr, stubName, TypePtr::BOTTOM,
6350                                  crc, src_start, length);
6351   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6352   set_result(result);
6353   return true;
6354 }
6355 
6356 //------------------------------get_table_from_crc32c_class-----------------------
6357 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
6358   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
6359   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
6360 
6361   return table;
6362 }
6363 
6364 //------------------------------inline_updateBytesCRC32C-----------------------
6365 //
6366 // Calculate CRC32C for byte[] array.
6367 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
6368 //
6369 bool LibraryCallKit::inline_updateBytesCRC32C() {
6370   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6371   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6372   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6373   // no receiver since it is a static method
6374   Node* crc     = argument(0); // type: int
6375   Node* src     = argument(1); // type: oop
6376   Node* offset  = argument(2); // type: int
6377   Node* end     = argument(3); // type: int
6378 
6379   Node* length = _gvn.transform(new SubINode(end, offset));
6380 
6381   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6382   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6383     // failed array check
6384     return false;
6385   }
6386 
6387   // Figure out the size and type of the elements we will be copying.
6388   BasicType src_elem = src_type->elem()->array_element_basic_type();
6389   if (src_elem != T_BYTE) {
6390     return false;
6391   }
6392 
6393   // 'src_start' points to src array + scaled offset
6394   src = must_be_not_null(src, true);
6395   Node* src_start = array_element_address(src, offset, src_elem);
6396 
6397   // static final int[] byteTable in class CRC32C
6398   Node* table = get_table_from_crc32c_class(callee()->holder());
6399   table = must_be_not_null(table, true);
6400   Node* table_start = array_element_address(table, intcon(0), T_INT);
6401 
6402   // We assume that range check is done by caller.
6403   // TODO: generate range check (offset+length < src.length) in debug VM.
6404 
6405   // Call the stub.
6406   address stubAddr = StubRoutines::updateBytesCRC32C();
6407   const char *stubName = "updateBytesCRC32C";
6408 
6409   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6410                                  stubAddr, stubName, TypePtr::BOTTOM,
6411                                  crc, src_start, length, table_start);
6412   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6413   set_result(result);
6414   return true;
6415 }
6416 
6417 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
6418 //
6419 // Calculate CRC32C for DirectByteBuffer.
6420 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
6421 //
6422 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
6423   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6424   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
6425   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6426   // no receiver since it is a static method
6427   Node* crc     = argument(0); // type: int
6428   Node* src     = argument(1); // type: long
6429   Node* offset  = argument(3); // type: int
6430   Node* end     = argument(4); // type: int
6431 
6432   Node* length = _gvn.transform(new SubINode(end, offset));
6433 
6434   src = ConvL2X(src);  // adjust Java long to machine word
6435   Node* base = _gvn.transform(new CastX2PNode(src));
6436   offset = ConvI2X(offset);
6437 
6438   // 'src_start' points to src array + scaled offset
6439   Node* src_start = basic_plus_adr(top(), base, offset);
6440 
6441   // static final int[] byteTable in class CRC32C
6442   Node* table = get_table_from_crc32c_class(callee()->holder());
6443   table = must_be_not_null(table, true);
6444   Node* table_start = array_element_address(table, intcon(0), T_INT);
6445 
6446   // Call the stub.
6447   address stubAddr = StubRoutines::updateBytesCRC32C();
6448   const char *stubName = "updateBytesCRC32C";
6449 
6450   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6451                                  stubAddr, stubName, TypePtr::BOTTOM,
6452                                  crc, src_start, length, table_start);
6453   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6454   set_result(result);
6455   return true;
6456 }
6457 
6458 //------------------------------inline_updateBytesAdler32----------------------
6459 //
6460 // Calculate Adler32 checksum for byte[] array.
6461 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
6462 //
6463 bool LibraryCallKit::inline_updateBytesAdler32() {
6464   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6465   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6466   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6467   // no receiver since it is static method
6468   Node* crc     = argument(0); // type: int
6469   Node* src     = argument(1); // type: oop
6470   Node* offset  = argument(2); // type: int
6471   Node* length  = argument(3); // type: int
6472 
6473   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6474   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6475     // failed array check
6476     return false;
6477   }
6478 
6479   // Figure out the size and type of the elements we will be copying.
6480   BasicType src_elem = src_type->elem()->array_element_basic_type();
6481   if (src_elem != T_BYTE) {
6482     return false;
6483   }
6484 
6485   // 'src_start' points to src array + scaled offset
6486   Node* src_start = array_element_address(src, offset, src_elem);
6487 
6488   // We assume that range check is done by caller.
6489   // TODO: generate range check (offset+length < src.length) in debug VM.
6490 
6491   // Call the stub.
6492   address stubAddr = StubRoutines::updateBytesAdler32();
6493   const char *stubName = "updateBytesAdler32";
6494 
6495   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
6496                                  stubAddr, stubName, TypePtr::BOTTOM,
6497                                  crc, src_start, length);
6498   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6499   set_result(result);
6500   return true;
6501 }
6502 
6503 //------------------------------inline_updateByteBufferAdler32---------------
6504 //
6505 // Calculate Adler32 checksum for DirectByteBuffer.
6506 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
6507 //
6508 bool LibraryCallKit::inline_updateByteBufferAdler32() {
6509   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6510   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6511   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6512   // no receiver since it is static method
6513   Node* crc     = argument(0); // type: int
6514   Node* src     = argument(1); // type: long
6515   Node* offset  = argument(3); // type: int
6516   Node* length  = argument(4); // type: int
6517 
6518   src = ConvL2X(src);  // adjust Java long to machine word
6519   Node* base = _gvn.transform(new CastX2PNode(src));
6520   offset = ConvI2X(offset);
6521 
6522   // 'src_start' points to src array + scaled offset
6523   Node* src_start = basic_plus_adr(top(), base, offset);
6524 
6525   // Call the stub.
6526   address stubAddr = StubRoutines::updateBytesAdler32();
6527   const char *stubName = "updateBytesAdler32";
6528 
6529   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
6530                                  stubAddr, stubName, TypePtr::BOTTOM,
6531                                  crc, src_start, length);
6532 
6533   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6534   set_result(result);
6535   return true;
6536 }
6537 
6538 //----------------------------inline_reference_get----------------------------
6539 // public T java.lang.ref.Reference.get();
6540 bool LibraryCallKit::inline_reference_get() {
6541   const int referent_offset = java_lang_ref_Reference::referent_offset();
6542 
6543   // Get the argument:
6544   Node* reference_obj = null_check_receiver();
6545   if (stopped()) return true;
6546 
6547   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
6548   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
6549                                         decorators, /*is_static*/ false, nullptr);
6550   if (result == nullptr) return false;
6551 
6552   // Add memory barrier to prevent commoning reads from this field
6553   // across safepoint since GC can change its value.
6554   insert_mem_bar(Op_MemBarCPUOrder);
6555 
6556   set_result(result);
6557   return true;
6558 }
6559 
6560 //----------------------------inline_reference_refersTo0----------------------------
6561 // bool java.lang.ref.Reference.refersTo0();
6562 // bool java.lang.ref.PhantomReference.refersTo0();
6563 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
6564   // Get arguments:
6565   Node* reference_obj = null_check_receiver();
6566   Node* other_obj = argument(1);
6567   if (stopped()) return true;
6568 
6569   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
6570   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
6571   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
6572                                           decorators, /*is_static*/ false, nullptr);
6573   if (referent == nullptr) return false;
6574 
6575   // Add memory barrier to prevent commoning reads from this field
6576   // across safepoint since GC can change its value.
6577   insert_mem_bar(Op_MemBarCPUOrder);
6578 
6579   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
6580   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6581   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
6582 
6583   RegionNode* region = new RegionNode(3);
6584   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
6585 
6586   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
6587   region->init_req(1, if_true);
6588   phi->init_req(1, intcon(1));
6589 
6590   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
6591   region->init_req(2, if_false);
6592   phi->init_req(2, intcon(0));
6593 
6594   set_control(_gvn.transform(region));
6595   record_for_igvn(region);
6596   set_result(_gvn.transform(phi));
6597   return true;
6598 }
6599 
6600 
6601 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
6602                                              DecoratorSet decorators, bool is_static,
6603                                              ciInstanceKlass* fromKls) {
6604   if (fromKls == nullptr) {
6605     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6606     assert(tinst != nullptr, "obj is null");
6607     assert(tinst->is_loaded(), "obj is not loaded");
6608     fromKls = tinst->instance_klass();
6609   } else {
6610     assert(is_static, "only for static field access");
6611   }
6612   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6613                                               ciSymbol::make(fieldTypeString),
6614                                               is_static);
6615 
6616   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
6617   if (field == nullptr) return (Node *) nullptr;
6618 
6619   if (is_static) {
6620     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6621     fromObj = makecon(tip);
6622   }
6623 
6624   // Next code  copied from Parse::do_get_xxx():
6625 
6626   // Compute address and memory type.
6627   int offset  = field->offset_in_bytes();
6628   bool is_vol = field->is_volatile();
6629   ciType* field_klass = field->type();
6630   assert(field_klass->is_loaded(), "should be loaded");
6631   const TypePtr* adr_type = C->alias_type(field)->adr_type();
6632   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6633   BasicType bt = field->layout_type();
6634 
6635   // Build the resultant type of the load
6636   const Type *type;
6637   if (bt == T_OBJECT) {
6638     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
6639   } else {
6640     type = Type::get_const_basic_type(bt);
6641   }
6642 
6643   if (is_vol) {
6644     decorators |= MO_SEQ_CST;
6645   }
6646 
6647   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
6648 }
6649 
6650 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
6651                                                  bool is_exact /* true */, bool is_static /* false */,
6652                                                  ciInstanceKlass * fromKls /* nullptr */) {
6653   if (fromKls == nullptr) {
6654     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6655     assert(tinst != nullptr, "obj is null");
6656     assert(tinst->is_loaded(), "obj is not loaded");
6657     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
6658     fromKls = tinst->instance_klass();
6659   }
6660   else {
6661     assert(is_static, "only for static field access");
6662   }
6663   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6664     ciSymbol::make(fieldTypeString),
6665     is_static);
6666 
6667   assert(field != nullptr, "undefined field");
6668   assert(!field->is_volatile(), "not defined for volatile fields");
6669 
6670   if (is_static) {
6671     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6672     fromObj = makecon(tip);
6673   }
6674 
6675   // Next code  copied from Parse::do_get_xxx():
6676 
6677   // Compute address and memory type.
6678   int offset = field->offset_in_bytes();
6679   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6680 
6681   return adr;
6682 }
6683 
6684 //------------------------------inline_aescrypt_Block-----------------------
6685 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
6686   address stubAddr = nullptr;
6687   const char *stubName;
6688   assert(UseAES, "need AES instruction support");
6689 
6690   switch(id) {
6691   case vmIntrinsics::_aescrypt_encryptBlock:
6692     stubAddr = StubRoutines::aescrypt_encryptBlock();
6693     stubName = "aescrypt_encryptBlock";
6694     break;
6695   case vmIntrinsics::_aescrypt_decryptBlock:
6696     stubAddr = StubRoutines::aescrypt_decryptBlock();
6697     stubName = "aescrypt_decryptBlock";
6698     break;
6699   default:
6700     break;
6701   }
6702   if (stubAddr == nullptr) return false;
6703 
6704   Node* aescrypt_object = argument(0);
6705   Node* src             = argument(1);
6706   Node* src_offset      = argument(2);
6707   Node* dest            = argument(3);
6708   Node* dest_offset     = argument(4);
6709 
6710   src = must_be_not_null(src, true);
6711   dest = must_be_not_null(dest, true);
6712 
6713   // (1) src and dest are arrays.
6714   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6715   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
6716   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
6717          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
6718 
6719   // for the quick and dirty code we will skip all the checks.
6720   // we are just trying to get the call to be generated.
6721   Node* src_start  = src;
6722   Node* dest_start = dest;
6723   if (src_offset != nullptr || dest_offset != nullptr) {
6724     assert(src_offset != nullptr && dest_offset != nullptr, "");
6725     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6726     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6727   }
6728 
6729   // now need to get the start of its expanded key array
6730   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6731   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6732   if (k_start == nullptr) return false;
6733 
6734   // Call the stub.
6735   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6736                     stubAddr, stubName, TypePtr::BOTTOM,
6737                     src_start, dest_start, k_start);
6738 
6739   return true;
6740 }
6741 
6742 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
6743 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
6744   address stubAddr = nullptr;
6745   const char *stubName = nullptr;
6746 
6747   assert(UseAES, "need AES instruction support");
6748 
6749   switch(id) {
6750   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
6751     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
6752     stubName = "cipherBlockChaining_encryptAESCrypt";
6753     break;
6754   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
6755     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
6756     stubName = "cipherBlockChaining_decryptAESCrypt";
6757     break;
6758   default:
6759     break;
6760   }
6761   if (stubAddr == nullptr) return false;
6762 
6763   Node* cipherBlockChaining_object = argument(0);
6764   Node* src                        = argument(1);
6765   Node* src_offset                 = argument(2);
6766   Node* len                        = argument(3);
6767   Node* dest                       = argument(4);
6768   Node* dest_offset                = argument(5);
6769 
6770   src = must_be_not_null(src, false);
6771   dest = must_be_not_null(dest, false);
6772 
6773   // (1) src and dest are arrays.
6774   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6775   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
6776   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
6777          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
6778 
6779   // checks are the responsibility of the caller
6780   Node* src_start  = src;
6781   Node* dest_start = dest;
6782   if (src_offset != nullptr || dest_offset != nullptr) {
6783     assert(src_offset != nullptr && dest_offset != nullptr, "");
6784     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6785     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6786   }
6787 
6788   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6789   // (because of the predicated logic executed earlier).
6790   // so we cast it here safely.
6791   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6792 
6793   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6794   if (embeddedCipherObj == nullptr) return false;
6795 
6796   // cast it to what we know it will be at runtime
6797   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6798   assert(tinst != nullptr, "CBC obj is null");
6799   assert(tinst->is_loaded(), "CBC obj is not loaded");
6800   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6801   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6802 
6803   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6804   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6805   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6806   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6807   aescrypt_object = _gvn.transform(aescrypt_object);
6808 
6809   // we need to get the start of the aescrypt_object's expanded key array
6810   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6811   if (k_start == nullptr) return false;
6812 
6813   // similarly, get the start address of the r vector
6814   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
6815   if (objRvec == nullptr) return false;
6816   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6817 
6818   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6819   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6820                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6821                                      stubAddr, stubName, TypePtr::BOTTOM,
6822                                      src_start, dest_start, k_start, r_start, len);
6823 
6824   // return cipher length (int)
6825   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6826   set_result(retvalue);
6827   return true;
6828 }
6829 
6830 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
6831 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
6832   address stubAddr = nullptr;
6833   const char *stubName = nullptr;
6834 
6835   assert(UseAES, "need AES instruction support");
6836 
6837   switch (id) {
6838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
6839     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
6840     stubName = "electronicCodeBook_encryptAESCrypt";
6841     break;
6842   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
6843     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
6844     stubName = "electronicCodeBook_decryptAESCrypt";
6845     break;
6846   default:
6847     break;
6848   }
6849 
6850   if (stubAddr == nullptr) return false;
6851 
6852   Node* electronicCodeBook_object = argument(0);
6853   Node* src                       = argument(1);
6854   Node* src_offset                = argument(2);
6855   Node* len                       = argument(3);
6856   Node* dest                      = argument(4);
6857   Node* dest_offset               = argument(5);
6858 
6859   // (1) src and dest are arrays.
6860   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6861   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
6862   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
6863          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
6864 
6865   // checks are the responsibility of the caller
6866   Node* src_start = src;
6867   Node* dest_start = dest;
6868   if (src_offset != nullptr || dest_offset != nullptr) {
6869     assert(src_offset != nullptr && dest_offset != nullptr, "");
6870     src_start = array_element_address(src, src_offset, T_BYTE);
6871     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6872   }
6873 
6874   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6875   // (because of the predicated logic executed earlier).
6876   // so we cast it here safely.
6877   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6878 
6879   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6880   if (embeddedCipherObj == nullptr) return false;
6881 
6882   // cast it to what we know it will be at runtime
6883   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
6884   assert(tinst != nullptr, "ECB obj is null");
6885   assert(tinst->is_loaded(), "ECB obj is not loaded");
6886   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6887   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6888 
6889   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6890   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6891   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6892   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6893   aescrypt_object = _gvn.transform(aescrypt_object);
6894 
6895   // we need to get the start of the aescrypt_object's expanded key array
6896   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6897   if (k_start == nullptr) return false;
6898 
6899   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6900   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
6901                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
6902                                      stubAddr, stubName, TypePtr::BOTTOM,
6903                                      src_start, dest_start, k_start, len);
6904 
6905   // return cipher length (int)
6906   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
6907   set_result(retvalue);
6908   return true;
6909 }
6910 
6911 //------------------------------inline_counterMode_AESCrypt-----------------------
6912 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
6913   assert(UseAES, "need AES instruction support");
6914   if (!UseAESCTRIntrinsics) return false;
6915 
6916   address stubAddr = nullptr;
6917   const char *stubName = nullptr;
6918   if (id == vmIntrinsics::_counterMode_AESCrypt) {
6919     stubAddr = StubRoutines::counterMode_AESCrypt();
6920     stubName = "counterMode_AESCrypt";
6921   }
6922   if (stubAddr == nullptr) return false;
6923 
6924   Node* counterMode_object = argument(0);
6925   Node* src = argument(1);
6926   Node* src_offset = argument(2);
6927   Node* len = argument(3);
6928   Node* dest = argument(4);
6929   Node* dest_offset = argument(5);
6930 
6931   // (1) src and dest are arrays.
6932   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6933   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
6934   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
6935          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
6936 
6937   // checks are the responsibility of the caller
6938   Node* src_start = src;
6939   Node* dest_start = dest;
6940   if (src_offset != nullptr || dest_offset != nullptr) {
6941     assert(src_offset != nullptr && dest_offset != nullptr, "");
6942     src_start = array_element_address(src, src_offset, T_BYTE);
6943     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6944   }
6945 
6946   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6947   // (because of the predicated logic executed earlier).
6948   // so we cast it here safely.
6949   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6950   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6951   if (embeddedCipherObj == nullptr) return false;
6952   // cast it to what we know it will be at runtime
6953   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
6954   assert(tinst != nullptr, "CTR obj is null");
6955   assert(tinst->is_loaded(), "CTR obj is not loaded");
6956   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6957   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6958   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6959   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6960   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6961   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6962   aescrypt_object = _gvn.transform(aescrypt_object);
6963   // we need to get the start of the aescrypt_object's expanded key array
6964   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6965   if (k_start == nullptr) return false;
6966   // similarly, get the start address of the r vector
6967   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
6968   if (obj_counter == nullptr) return false;
6969   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
6970 
6971   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
6972   if (saved_encCounter == nullptr) return false;
6973   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
6974   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
6975 
6976   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6977   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6978                                      OptoRuntime::counterMode_aescrypt_Type(),
6979                                      stubAddr, stubName, TypePtr::BOTTOM,
6980                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
6981 
6982   // return cipher length (int)
6983   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
6984   set_result(retvalue);
6985   return true;
6986 }
6987 
6988 //------------------------------get_key_start_from_aescrypt_object-----------------------
6989 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6990 #if defined(PPC64) || defined(S390)
6991   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
6992   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
6993   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
6994   // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
6995   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
6996   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
6997   if (objSessionK == nullptr) {
6998     return (Node *) nullptr;
6999   }
7000   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
7001 #else
7002   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
7003 #endif // PPC64
7004   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
7005   if (objAESCryptKey == nullptr) return (Node *) nullptr;
7006 
7007   // now have the array, need to get the start address of the K array
7008   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
7009   return k_start;
7010 }
7011 
7012 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
7013 // Return node representing slow path of predicate check.
7014 // the pseudo code we want to emulate with this predicate is:
7015 // for encryption:
7016 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7017 // for decryption:
7018 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7019 //    note cipher==plain is more conservative than the original java code but that's OK
7020 //
7021 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
7022   // The receiver was checked for null already.
7023   Node* objCBC = argument(0);
7024 
7025   Node* src = argument(1);
7026   Node* dest = argument(4);
7027 
7028   // Load embeddedCipher field of CipherBlockChaining object.
7029   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7030 
7031   // get AESCrypt klass for instanceOf check
7032   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7033   // will have same classloader as CipherBlockChaining object
7034   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
7035   assert(tinst != nullptr, "CBCobj is null");
7036   assert(tinst->is_loaded(), "CBCobj is not loaded");
7037 
7038   // we want to do an instanceof comparison against the AESCrypt class
7039   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7040   if (!klass_AESCrypt->is_loaded()) {
7041     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7042     Node* ctrl = control();
7043     set_control(top()); // no regular fast path
7044     return ctrl;
7045   }
7046 
7047   src = must_be_not_null(src, true);
7048   dest = must_be_not_null(dest, true);
7049 
7050   // Resolve oops to stable for CmpP below.
7051   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7052 
7053   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7054   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
7055   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7056 
7057   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7058 
7059   // for encryption, we are done
7060   if (!decrypting)
7061     return instof_false;  // even if it is null
7062 
7063   // for decryption, we need to add a further check to avoid
7064   // taking the intrinsic path when cipher and plain are the same
7065   // see the original java code for why.
7066   RegionNode* region = new RegionNode(3);
7067   region->init_req(1, instof_false);
7068 
7069   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7070   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7071   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7072   region->init_req(2, src_dest_conjoint);
7073 
7074   record_for_igvn(region);
7075   return _gvn.transform(region);
7076 }
7077 
7078 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
7079 // Return node representing slow path of predicate check.
7080 // the pseudo code we want to emulate with this predicate is:
7081 // for encryption:
7082 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7083 // for decryption:
7084 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7085 //    note cipher==plain is more conservative than the original java code but that's OK
7086 //
7087 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
7088   // The receiver was checked for null already.
7089   Node* objECB = argument(0);
7090 
7091   // Load embeddedCipher field of ElectronicCodeBook object.
7092   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7093 
7094   // get AESCrypt klass for instanceOf check
7095   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7096   // will have same classloader as ElectronicCodeBook object
7097   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
7098   assert(tinst != nullptr, "ECBobj is null");
7099   assert(tinst->is_loaded(), "ECBobj is not loaded");
7100 
7101   // we want to do an instanceof comparison against the AESCrypt class
7102   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7103   if (!klass_AESCrypt->is_loaded()) {
7104     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7105     Node* ctrl = control();
7106     set_control(top()); // no regular fast path
7107     return ctrl;
7108   }
7109   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7110 
7111   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7112   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7113   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7114 
7115   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7116 
7117   // for encryption, we are done
7118   if (!decrypting)
7119     return instof_false;  // even if it is null
7120 
7121   // for decryption, we need to add a further check to avoid
7122   // taking the intrinsic path when cipher and plain are the same
7123   // see the original java code for why.
7124   RegionNode* region = new RegionNode(3);
7125   region->init_req(1, instof_false);
7126   Node* src = argument(1);
7127   Node* dest = argument(4);
7128   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7129   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7130   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7131   region->init_req(2, src_dest_conjoint);
7132 
7133   record_for_igvn(region);
7134   return _gvn.transform(region);
7135 }
7136 
7137 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
7138 // Return node representing slow path of predicate check.
7139 // the pseudo code we want to emulate with this predicate is:
7140 // for encryption:
7141 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7142 // for decryption:
7143 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7144 //    note cipher==plain is more conservative than the original java code but that's OK
7145 //
7146 
7147 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
7148   // The receiver was checked for null already.
7149   Node* objCTR = argument(0);
7150 
7151   // Load embeddedCipher field of CipherBlockChaining object.
7152   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7153 
7154   // get AESCrypt klass for instanceOf check
7155   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7156   // will have same classloader as CipherBlockChaining object
7157   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
7158   assert(tinst != nullptr, "CTRobj is null");
7159   assert(tinst->is_loaded(), "CTRobj is not loaded");
7160 
7161   // we want to do an instanceof comparison against the AESCrypt class
7162   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7163   if (!klass_AESCrypt->is_loaded()) {
7164     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7165     Node* ctrl = control();
7166     set_control(top()); // no regular fast path
7167     return ctrl;
7168   }
7169 
7170   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7171   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7172   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7173   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7174   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7175 
7176   return instof_false; // even if it is null
7177 }
7178 
7179 //------------------------------inline_ghash_processBlocks
7180 bool LibraryCallKit::inline_ghash_processBlocks() {
7181   address stubAddr;
7182   const char *stubName;
7183   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
7184 
7185   stubAddr = StubRoutines::ghash_processBlocks();
7186   stubName = "ghash_processBlocks";
7187 
7188   Node* data           = argument(0);
7189   Node* offset         = argument(1);
7190   Node* len            = argument(2);
7191   Node* state          = argument(3);
7192   Node* subkeyH        = argument(4);
7193 
7194   state = must_be_not_null(state, true);
7195   subkeyH = must_be_not_null(subkeyH, true);
7196   data = must_be_not_null(data, true);
7197 
7198   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
7199   assert(state_start, "state is null");
7200   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
7201   assert(subkeyH_start, "subkeyH is null");
7202   Node* data_start  = array_element_address(data, offset, T_BYTE);
7203   assert(data_start, "data is null");
7204 
7205   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
7206                                   OptoRuntime::ghash_processBlocks_Type(),
7207                                   stubAddr, stubName, TypePtr::BOTTOM,
7208                                   state_start, subkeyH_start, data_start, len);
7209   return true;
7210 }
7211 
7212 //------------------------------inline_chacha20Block
7213 bool LibraryCallKit::inline_chacha20Block() {
7214   address stubAddr;
7215   const char *stubName;
7216   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
7217 
7218   stubAddr = StubRoutines::chacha20Block();
7219   stubName = "chacha20Block";
7220 
7221   Node* state          = argument(0);
7222   Node* result         = argument(1);
7223 
7224   state = must_be_not_null(state, true);
7225   result = must_be_not_null(result, true);
7226 
7227   Node* state_start  = array_element_address(state, intcon(0), T_INT);
7228   assert(state_start, "state is null");
7229   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
7230   assert(result_start, "result is null");
7231 
7232   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
7233                                   OptoRuntime::chacha20Block_Type(),
7234                                   stubAddr, stubName, TypePtr::BOTTOM,
7235                                   state_start, result_start);
7236   // return key stream length (int)
7237   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
7238   set_result(retvalue);
7239   return true;
7240 }
7241 
7242 bool LibraryCallKit::inline_base64_encodeBlock() {
7243   address stubAddr;
7244   const char *stubName;
7245   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
7246   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
7247   stubAddr = StubRoutines::base64_encodeBlock();
7248   stubName = "encodeBlock";
7249 
7250   if (!stubAddr) return false;
7251   Node* base64obj = argument(0);
7252   Node* src = argument(1);
7253   Node* offset = argument(2);
7254   Node* len = argument(3);
7255   Node* dest = argument(4);
7256   Node* dp = argument(5);
7257   Node* isURL = argument(6);
7258 
7259   src = must_be_not_null(src, true);
7260   dest = must_be_not_null(dest, true);
7261 
7262   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
7263   assert(src_start, "source array is null");
7264   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
7265   assert(dest_start, "destination array is null");
7266 
7267   Node* base64 = make_runtime_call(RC_LEAF,
7268                                    OptoRuntime::base64_encodeBlock_Type(),
7269                                    stubAddr, stubName, TypePtr::BOTTOM,
7270                                    src_start, offset, len, dest_start, dp, isURL);
7271   return true;
7272 }
7273 
7274 bool LibraryCallKit::inline_base64_decodeBlock() {
7275   address stubAddr;
7276   const char *stubName;
7277   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
7278   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
7279   stubAddr = StubRoutines::base64_decodeBlock();
7280   stubName = "decodeBlock";
7281 
7282   if (!stubAddr) return false;
7283   Node* base64obj = argument(0);
7284   Node* src = argument(1);
7285   Node* src_offset = argument(2);
7286   Node* len = argument(3);
7287   Node* dest = argument(4);
7288   Node* dest_offset = argument(5);
7289   Node* isURL = argument(6);
7290   Node* isMIME = argument(7);
7291 
7292   src = must_be_not_null(src, true);
7293   dest = must_be_not_null(dest, true);
7294 
7295   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
7296   assert(src_start, "source array is null");
7297   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
7298   assert(dest_start, "destination array is null");
7299 
7300   Node* call = make_runtime_call(RC_LEAF,
7301                                  OptoRuntime::base64_decodeBlock_Type(),
7302                                  stubAddr, stubName, TypePtr::BOTTOM,
7303                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
7304   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7305   set_result(result);
7306   return true;
7307 }
7308 
7309 bool LibraryCallKit::inline_poly1305_processBlocks() {
7310   address stubAddr;
7311   const char *stubName;
7312   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
7313   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
7314   stubAddr = StubRoutines::poly1305_processBlocks();
7315   stubName = "poly1305_processBlocks";
7316 
7317   if (!stubAddr) return false;
7318   null_check_receiver();  // null-check receiver
7319   if (stopped())  return true;
7320 
7321   Node* input = argument(1);
7322   Node* input_offset = argument(2);
7323   Node* len = argument(3);
7324   Node* alimbs = argument(4);
7325   Node* rlimbs = argument(5);
7326 
7327   input = must_be_not_null(input, true);
7328   alimbs = must_be_not_null(alimbs, true);
7329   rlimbs = must_be_not_null(rlimbs, true);
7330 
7331   Node* input_start = array_element_address(input, input_offset, T_BYTE);
7332   assert(input_start, "input array is null");
7333   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
7334   assert(acc_start, "acc array is null");
7335   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
7336   assert(r_start, "r array is null");
7337 
7338   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
7339                                  OptoRuntime::poly1305_processBlocks_Type(),
7340                                  stubAddr, stubName, TypePtr::BOTTOM,
7341                                  input_start, len, acc_start, r_start);
7342   return true;
7343 }
7344 
7345 //------------------------------inline_digestBase_implCompress-----------------------
7346 //
7347 // Calculate MD5 for single-block byte[] array.
7348 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
7349 //
7350 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
7351 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
7352 //
7353 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
7354 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
7355 //
7356 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
7357 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
7358 //
7359 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
7360 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
7361 //
7362 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
7363   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
7364 
7365   Node* digestBase_obj = argument(0);
7366   Node* src            = argument(1); // type oop
7367   Node* ofs            = argument(2); // type int
7368 
7369   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7370   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7371     // failed array check
7372     return false;
7373   }
7374   // Figure out the size and type of the elements we will be copying.
7375   BasicType src_elem = src_type->elem()->array_element_basic_type();
7376   if (src_elem != T_BYTE) {
7377     return false;
7378   }
7379   // 'src_start' points to src array + offset
7380   src = must_be_not_null(src, true);
7381   Node* src_start = array_element_address(src, ofs, src_elem);
7382   Node* state = nullptr;
7383   Node* block_size = nullptr;
7384   address stubAddr;
7385   const char *stubName;
7386 
7387   switch(id) {
7388   case vmIntrinsics::_md5_implCompress:
7389     assert(UseMD5Intrinsics, "need MD5 instruction support");
7390     state = get_state_from_digest_object(digestBase_obj, T_INT);
7391     stubAddr = StubRoutines::md5_implCompress();
7392     stubName = "md5_implCompress";
7393     break;
7394   case vmIntrinsics::_sha_implCompress:
7395     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
7396     state = get_state_from_digest_object(digestBase_obj, T_INT);
7397     stubAddr = StubRoutines::sha1_implCompress();
7398     stubName = "sha1_implCompress";
7399     break;
7400   case vmIntrinsics::_sha2_implCompress:
7401     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
7402     state = get_state_from_digest_object(digestBase_obj, T_INT);
7403     stubAddr = StubRoutines::sha256_implCompress();
7404     stubName = "sha256_implCompress";
7405     break;
7406   case vmIntrinsics::_sha5_implCompress:
7407     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
7408     state = get_state_from_digest_object(digestBase_obj, T_LONG);
7409     stubAddr = StubRoutines::sha512_implCompress();
7410     stubName = "sha512_implCompress";
7411     break;
7412   case vmIntrinsics::_sha3_implCompress:
7413     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
7414     state = get_state_from_digest_object(digestBase_obj, T_BYTE);
7415     stubAddr = StubRoutines::sha3_implCompress();
7416     stubName = "sha3_implCompress";
7417     block_size = get_block_size_from_digest_object(digestBase_obj);
7418     if (block_size == nullptr) return false;
7419     break;
7420   default:
7421     fatal_unexpected_iid(id);
7422     return false;
7423   }
7424   if (state == nullptr) return false;
7425 
7426   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
7427   if (stubAddr == nullptr) return false;
7428 
7429   // Call the stub.
7430   Node* call;
7431   if (block_size == nullptr) {
7432     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
7433                              stubAddr, stubName, TypePtr::BOTTOM,
7434                              src_start, state);
7435   } else {
7436     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
7437                              stubAddr, stubName, TypePtr::BOTTOM,
7438                              src_start, state, block_size);
7439   }
7440 
7441   return true;
7442 }
7443 
7444 //------------------------------inline_digestBase_implCompressMB-----------------------
7445 //
7446 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
7447 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
7448 //
7449 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
7450   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
7451          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
7452   assert((uint)predicate < 5, "sanity");
7453   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
7454 
7455   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
7456   Node* src            = argument(1); // byte[] array
7457   Node* ofs            = argument(2); // type int
7458   Node* limit          = argument(3); // type int
7459 
7460   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7461   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7462     // failed array check
7463     return false;
7464   }
7465   // Figure out the size and type of the elements we will be copying.
7466   BasicType src_elem = src_type->elem()->array_element_basic_type();
7467   if (src_elem != T_BYTE) {
7468     return false;
7469   }
7470   // 'src_start' points to src array + offset
7471   src = must_be_not_null(src, false);
7472   Node* src_start = array_element_address(src, ofs, src_elem);
7473 
7474   const char* klass_digestBase_name = nullptr;
7475   const char* stub_name = nullptr;
7476   address     stub_addr = nullptr;
7477   BasicType elem_type = T_INT;
7478 
7479   switch (predicate) {
7480   case 0:
7481     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
7482       klass_digestBase_name = "sun/security/provider/MD5";
7483       stub_name = "md5_implCompressMB";
7484       stub_addr = StubRoutines::md5_implCompressMB();
7485     }
7486     break;
7487   case 1:
7488     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
7489       klass_digestBase_name = "sun/security/provider/SHA";
7490       stub_name = "sha1_implCompressMB";
7491       stub_addr = StubRoutines::sha1_implCompressMB();
7492     }
7493     break;
7494   case 2:
7495     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
7496       klass_digestBase_name = "sun/security/provider/SHA2";
7497       stub_name = "sha256_implCompressMB";
7498       stub_addr = StubRoutines::sha256_implCompressMB();
7499     }
7500     break;
7501   case 3:
7502     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
7503       klass_digestBase_name = "sun/security/provider/SHA5";
7504       stub_name = "sha512_implCompressMB";
7505       stub_addr = StubRoutines::sha512_implCompressMB();
7506       elem_type = T_LONG;
7507     }
7508     break;
7509   case 4:
7510     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
7511       klass_digestBase_name = "sun/security/provider/SHA3";
7512       stub_name = "sha3_implCompressMB";
7513       stub_addr = StubRoutines::sha3_implCompressMB();
7514       elem_type = T_BYTE;
7515     }
7516     break;
7517   default:
7518     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
7519   }
7520   if (klass_digestBase_name != nullptr) {
7521     assert(stub_addr != nullptr, "Stub is generated");
7522     if (stub_addr == nullptr) return false;
7523 
7524     // get DigestBase klass to lookup for SHA klass
7525     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
7526     assert(tinst != nullptr, "digestBase_obj is not instance???");
7527     assert(tinst->is_loaded(), "DigestBase is not loaded");
7528 
7529     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
7530     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
7531     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
7532     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
7533   }
7534   return false;
7535 }
7536 
7537 //------------------------------inline_digestBase_implCompressMB-----------------------
7538 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
7539                                                       BasicType elem_type, address stubAddr, const char *stubName,
7540                                                       Node* src_start, Node* ofs, Node* limit) {
7541   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
7542   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7543   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
7544   digest_obj = _gvn.transform(digest_obj);
7545 
7546   Node* state = get_state_from_digest_object(digest_obj, elem_type);
7547   if (state == nullptr) return false;
7548 
7549   Node* block_size = nullptr;
7550   if (strcmp("sha3_implCompressMB", stubName) == 0) {
7551     block_size = get_block_size_from_digest_object(digest_obj);
7552     if (block_size == nullptr) return false;
7553   }
7554 
7555   // Call the stub.
7556   Node* call;
7557   if (block_size == nullptr) {
7558     call = make_runtime_call(RC_LEAF|RC_NO_FP,
7559                              OptoRuntime::digestBase_implCompressMB_Type(false),
7560                              stubAddr, stubName, TypePtr::BOTTOM,
7561                              src_start, state, ofs, limit);
7562   } else {
7563      call = make_runtime_call(RC_LEAF|RC_NO_FP,
7564                              OptoRuntime::digestBase_implCompressMB_Type(true),
7565                              stubAddr, stubName, TypePtr::BOTTOM,
7566                              src_start, state, block_size, ofs, limit);
7567   }
7568 
7569   // return ofs (int)
7570   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7571   set_result(result);
7572 
7573   return true;
7574 }
7575 
7576 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
7577 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
7578   assert(UseAES, "need AES instruction support");
7579   address stubAddr = nullptr;
7580   const char *stubName = nullptr;
7581   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
7582   stubName = "galoisCounterMode_AESCrypt";
7583 
7584   if (stubAddr == nullptr) return false;
7585 
7586   Node* in      = argument(0);
7587   Node* inOfs   = argument(1);
7588   Node* len     = argument(2);
7589   Node* ct      = argument(3);
7590   Node* ctOfs   = argument(4);
7591   Node* out     = argument(5);
7592   Node* outOfs  = argument(6);
7593   Node* gctr_object = argument(7);
7594   Node* ghash_object = argument(8);
7595 
7596   // (1) in, ct and out are arrays.
7597   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7598   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
7599   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7600   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
7601           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
7602          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
7603 
7604   // checks are the responsibility of the caller
7605   Node* in_start = in;
7606   Node* ct_start = ct;
7607   Node* out_start = out;
7608   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
7609     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
7610     in_start = array_element_address(in, inOfs, T_BYTE);
7611     ct_start = array_element_address(ct, ctOfs, T_BYTE);
7612     out_start = array_element_address(out, outOfs, T_BYTE);
7613   }
7614 
7615   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7616   // (because of the predicated logic executed earlier).
7617   // so we cast it here safely.
7618   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7619   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7620   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
7621   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
7622   Node* state = load_field_from_object(ghash_object, "state", "[J");
7623 
7624   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
7625     return false;
7626   }
7627   // cast it to what we know it will be at runtime
7628   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
7629   assert(tinst != nullptr, "GCTR obj is null");
7630   assert(tinst->is_loaded(), "GCTR obj is not loaded");
7631   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7632   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7633   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7634   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7635   const TypeOopPtr* xtype = aklass->as_instance_type();
7636   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7637   aescrypt_object = _gvn.transform(aescrypt_object);
7638   // we need to get the start of the aescrypt_object's expanded key array
7639   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7640   if (k_start == nullptr) return false;
7641   // similarly, get the start address of the r vector
7642   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
7643   Node* state_start = array_element_address(state, intcon(0), T_LONG);
7644   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
7645 
7646 
7647   // Call the stub, passing params
7648   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7649                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
7650                                stubAddr, stubName, TypePtr::BOTTOM,
7651                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
7652 
7653   // return cipher length (int)
7654   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
7655   set_result(retvalue);
7656 
7657   return true;
7658 }
7659 
7660 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
7661 // Return node representing slow path of predicate check.
7662 // the pseudo code we want to emulate with this predicate is:
7663 // for encryption:
7664 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7665 // for decryption:
7666 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7667 //    note cipher==plain is more conservative than the original java code but that's OK
7668 //
7669 
7670 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
7671   // The receiver was checked for null already.
7672   Node* objGCTR = argument(7);
7673   // Load embeddedCipher field of GCTR object.
7674   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7675   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
7676 
7677   // get AESCrypt klass for instanceOf check
7678   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7679   // will have same classloader as CipherBlockChaining object
7680   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
7681   assert(tinst != nullptr, "GCTR obj is null");
7682   assert(tinst->is_loaded(), "GCTR obj is not loaded");
7683 
7684   // we want to do an instanceof comparison against the AESCrypt class
7685   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7686   if (!klass_AESCrypt->is_loaded()) {
7687     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7688     Node* ctrl = control();
7689     set_control(top()); // no regular fast path
7690     return ctrl;
7691   }
7692 
7693   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7694   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7695   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7696   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7697   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7698 
7699   return instof_false; // even if it is null
7700 }
7701 
7702 //------------------------------get_state_from_digest_object-----------------------
7703 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
7704   const char* state_type;
7705   switch (elem_type) {
7706     case T_BYTE: state_type = "[B"; break;
7707     case T_INT:  state_type = "[I"; break;
7708     case T_LONG: state_type = "[J"; break;
7709     default: ShouldNotReachHere();
7710   }
7711   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
7712   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
7713   if (digest_state == nullptr) return (Node *) nullptr;
7714 
7715   // now have the array, need to get the start address of the state array
7716   Node* state = array_element_address(digest_state, intcon(0), elem_type);
7717   return state;
7718 }
7719 
7720 //------------------------------get_block_size_from_sha3_object----------------------------------
7721 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
7722   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
7723   assert (block_size != nullptr, "sanity");
7724   return block_size;
7725 }
7726 
7727 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
7728 // Return node representing slow path of predicate check.
7729 // the pseudo code we want to emulate with this predicate is:
7730 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
7731 //
7732 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
7733   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
7734          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
7735   assert((uint)predicate < 5, "sanity");
7736 
7737   // The receiver was checked for null already.
7738   Node* digestBaseObj = argument(0);
7739 
7740   // get DigestBase klass for instanceOf check
7741   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
7742   assert(tinst != nullptr, "digestBaseObj is null");
7743   assert(tinst->is_loaded(), "DigestBase is not loaded");
7744 
7745   const char* klass_name = nullptr;
7746   switch (predicate) {
7747   case 0:
7748     if (UseMD5Intrinsics) {
7749       // we want to do an instanceof comparison against the MD5 class
7750       klass_name = "sun/security/provider/MD5";
7751     }
7752     break;
7753   case 1:
7754     if (UseSHA1Intrinsics) {
7755       // we want to do an instanceof comparison against the SHA class
7756       klass_name = "sun/security/provider/SHA";
7757     }
7758     break;
7759   case 2:
7760     if (UseSHA256Intrinsics) {
7761       // we want to do an instanceof comparison against the SHA2 class
7762       klass_name = "sun/security/provider/SHA2";
7763     }
7764     break;
7765   case 3:
7766     if (UseSHA512Intrinsics) {
7767       // we want to do an instanceof comparison against the SHA5 class
7768       klass_name = "sun/security/provider/SHA5";
7769     }
7770     break;
7771   case 4:
7772     if (UseSHA3Intrinsics) {
7773       // we want to do an instanceof comparison against the SHA3 class
7774       klass_name = "sun/security/provider/SHA3";
7775     }
7776     break;
7777   default:
7778     fatal("unknown SHA intrinsic predicate: %d", predicate);
7779   }
7780 
7781   ciKlass* klass = nullptr;
7782   if (klass_name != nullptr) {
7783     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
7784   }
7785   if ((klass == nullptr) || !klass->is_loaded()) {
7786     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
7787     Node* ctrl = control();
7788     set_control(top()); // no intrinsic path
7789     return ctrl;
7790   }
7791   ciInstanceKlass* instklass = klass->as_instance_klass();
7792 
7793   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
7794   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7795   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7796   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7797 
7798   return instof_false;  // even if it is null
7799 }
7800 
7801 //-------------inline_fma-----------------------------------
7802 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
7803   Node *a = nullptr;
7804   Node *b = nullptr;
7805   Node *c = nullptr;
7806   Node* result = nullptr;
7807   switch (id) {
7808   case vmIntrinsics::_fmaD:
7809     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
7810     // no receiver since it is static method
7811     a = round_double_node(argument(0));
7812     b = round_double_node(argument(2));
7813     c = round_double_node(argument(4));
7814     result = _gvn.transform(new FmaDNode(control(), a, b, c));
7815     break;
7816   case vmIntrinsics::_fmaF:
7817     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
7818     a = argument(0);
7819     b = argument(1);
7820     c = argument(2);
7821     result = _gvn.transform(new FmaFNode(control(), a, b, c));
7822     break;
7823   default:
7824     fatal_unexpected_iid(id);  break;
7825   }
7826   set_result(result);
7827   return true;
7828 }
7829 
7830 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
7831   // argument(0) is receiver
7832   Node* codePoint = argument(1);
7833   Node* n = nullptr;
7834 
7835   switch (id) {
7836     case vmIntrinsics::_isDigit :
7837       n = new DigitNode(control(), codePoint);
7838       break;
7839     case vmIntrinsics::_isLowerCase :
7840       n = new LowerCaseNode(control(), codePoint);
7841       break;
7842     case vmIntrinsics::_isUpperCase :
7843       n = new UpperCaseNode(control(), codePoint);
7844       break;
7845     case vmIntrinsics::_isWhitespace :
7846       n = new WhitespaceNode(control(), codePoint);
7847       break;
7848     default:
7849       fatal_unexpected_iid(id);
7850   }
7851 
7852   set_result(_gvn.transform(n));
7853   return true;
7854 }
7855 
7856 //------------------------------inline_fp_min_max------------------------------
7857 bool LibraryCallKit::inline_fp_min_max(vmIntrinsics::ID id) {
7858 /* DISABLED BECAUSE METHOD DATA ISN'T COLLECTED PER CALL-SITE, SEE JDK-8015416.
7859 
7860   // The intrinsic should be used only when the API branches aren't predictable,
7861   // the last one performing the most important comparison. The following heuristic
7862   // uses the branch statistics to eventually bail out if necessary.
7863 
7864   ciMethodData *md = callee()->method_data();
7865 
7866   if ( md != nullptr && md->is_mature() && md->invocation_count() > 0 ) {
7867     ciCallProfile cp = caller()->call_profile_at_bci(bci());
7868 
7869     if ( ((double)cp.count()) / ((double)md->invocation_count()) < 0.8 ) {
7870       // Bail out if the call-site didn't contribute enough to the statistics.
7871       return false;
7872     }
7873 
7874     uint taken = 0, not_taken = 0;
7875 
7876     for (ciProfileData *p = md->first_data(); md->is_valid(p); p = md->next_data(p)) {
7877       if (p->is_BranchData()) {
7878         taken = ((ciBranchData*)p)->taken();
7879         not_taken = ((ciBranchData*)p)->not_taken();
7880       }
7881     }
7882 
7883     double balance = (((double)taken) - ((double)not_taken)) / ((double)md->invocation_count());
7884     balance = balance < 0 ? -balance : balance;
7885     if ( balance > 0.2 ) {
7886       // Bail out if the most important branch is predictable enough.
7887       return false;
7888     }
7889   }
7890 */
7891 
7892   Node *a = nullptr;
7893   Node *b = nullptr;
7894   Node *n = nullptr;
7895   switch (id) {
7896   case vmIntrinsics::_maxF:
7897   case vmIntrinsics::_minF:
7898   case vmIntrinsics::_maxF_strict:
7899   case vmIntrinsics::_minF_strict:
7900     assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
7901     a = argument(0);
7902     b = argument(1);
7903     break;
7904   case vmIntrinsics::_maxD:
7905   case vmIntrinsics::_minD:
7906   case vmIntrinsics::_maxD_strict:
7907   case vmIntrinsics::_minD_strict:
7908     assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
7909     a = round_double_node(argument(0));
7910     b = round_double_node(argument(2));
7911     break;
7912   default:
7913     fatal_unexpected_iid(id);
7914     break;
7915   }
7916   switch (id) {
7917   case vmIntrinsics::_maxF:
7918   case vmIntrinsics::_maxF_strict:
7919     n = new MaxFNode(a, b);
7920     break;
7921   case vmIntrinsics::_minF:
7922   case vmIntrinsics::_minF_strict:
7923     n = new MinFNode(a, b);
7924     break;
7925   case vmIntrinsics::_maxD:
7926   case vmIntrinsics::_maxD_strict:
7927     n = new MaxDNode(a, b);
7928     break;
7929   case vmIntrinsics::_minD:
7930   case vmIntrinsics::_minD_strict:
7931     n = new MinDNode(a, b);
7932     break;
7933   default:
7934     fatal_unexpected_iid(id);
7935     break;
7936   }
7937   set_result(_gvn.transform(n));
7938   return true;
7939 }
7940 
7941 bool LibraryCallKit::inline_profileBoolean() {
7942   Node* counts = argument(1);
7943   const TypeAryPtr* ary = nullptr;
7944   ciArray* aobj = nullptr;
7945   if (counts->is_Con()
7946       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
7947       && (aobj = ary->const_oop()->as_array()) != nullptr
7948       && (aobj->length() == 2)) {
7949     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
7950     jint false_cnt = aobj->element_value(0).as_int();
7951     jint  true_cnt = aobj->element_value(1).as_int();
7952 
7953     if (C->log() != nullptr) {
7954       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
7955                      false_cnt, true_cnt);
7956     }
7957 
7958     if (false_cnt + true_cnt == 0) {
7959       // According to profile, never executed.
7960       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
7961                           Deoptimization::Action_reinterpret);
7962       return true;
7963     }
7964 
7965     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
7966     // is a number of each value occurrences.
7967     Node* result = argument(0);
7968     if (false_cnt == 0 || true_cnt == 0) {
7969       // According to profile, one value has been never seen.
7970       int expected_val = (false_cnt == 0) ? 1 : 0;
7971 
7972       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
7973       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7974 
7975       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
7976       Node* fast_path = _gvn.transform(new IfTrueNode(check));
7977       Node* slow_path = _gvn.transform(new IfFalseNode(check));
7978 
7979       { // Slow path: uncommon trap for never seen value and then reexecute
7980         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
7981         // the value has been seen at least once.
7982         PreserveJVMState pjvms(this);
7983         PreserveReexecuteState preexecs(this);
7984         jvms()->set_should_reexecute(true);
7985 
7986         set_control(slow_path);
7987         set_i_o(i_o());
7988 
7989         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
7990                             Deoptimization::Action_reinterpret);
7991       }
7992       // The guard for never seen value enables sharpening of the result and
7993       // returning a constant. It allows to eliminate branches on the same value
7994       // later on.
7995       set_control(fast_path);
7996       result = intcon(expected_val);
7997     }
7998     // Stop profiling.
7999     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
8000     // By replacing method body with profile data (represented as ProfileBooleanNode
8001     // on IR level) we effectively disable profiling.
8002     // It enables full speed execution once optimized code is generated.
8003     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
8004     C->record_for_igvn(profile);
8005     set_result(profile);
8006     return true;
8007   } else {
8008     // Continue profiling.
8009     // Profile data isn't available at the moment. So, execute method's bytecode version.
8010     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
8011     // is compiled and counters aren't available since corresponding MethodHandle
8012     // isn't a compile-time constant.
8013     return false;
8014   }
8015 }
8016 
8017 bool LibraryCallKit::inline_isCompileConstant() {
8018   Node* n = argument(0);
8019   set_result(n->is_Con() ? intcon(1) : intcon(0));
8020   return true;
8021 }
8022 
8023 //------------------------------- inline_getObjectSize --------------------------------------
8024 //
8025 // Calculate the runtime size of the object/array.
8026 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
8027 //
8028 bool LibraryCallKit::inline_getObjectSize() {
8029   Node* obj = argument(3);
8030   Node* klass_node = load_object_klass(obj);
8031 
8032   jint  layout_con = Klass::_lh_neutral_value;
8033   Node* layout_val = get_layout_helper(klass_node, layout_con);
8034   int   layout_is_con = (layout_val == nullptr);
8035 
8036   if (layout_is_con) {
8037     // Layout helper is constant, can figure out things at compile time.
8038 
8039     if (Klass::layout_helper_is_instance(layout_con)) {
8040       // Instance case:  layout_con contains the size itself.
8041       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
8042       set_result(size);
8043     } else {
8044       // Array case: size is round(header + element_size*arraylength).
8045       // Since arraylength is different for every array instance, we have to
8046       // compute the whole thing at runtime.
8047 
8048       Node* arr_length = load_array_length(obj);
8049 
8050       int round_mask = MinObjAlignmentInBytes - 1;
8051       int hsize  = Klass::layout_helper_header_size(layout_con);
8052       int eshift = Klass::layout_helper_log2_element_size(layout_con);
8053 
8054       if ((round_mask & ~right_n_bits(eshift)) == 0) {
8055         round_mask = 0;  // strength-reduce it if it goes away completely
8056       }
8057       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
8058       Node* header_size = intcon(hsize + round_mask);
8059 
8060       Node* lengthx = ConvI2X(arr_length);
8061       Node* headerx = ConvI2X(header_size);
8062 
8063       Node* abody = lengthx;
8064       if (eshift != 0) {
8065         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
8066       }
8067       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
8068       if (round_mask != 0) {
8069         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
8070       }
8071       size = ConvX2L(size);
8072       set_result(size);
8073     }
8074   } else {
8075     // Layout helper is not constant, need to test for array-ness at runtime.
8076 
8077     enum { _instance_path = 1, _array_path, PATH_LIMIT };
8078     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
8079     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
8080     record_for_igvn(result_reg);
8081 
8082     Node* array_ctl = generate_array_guard(klass_node, nullptr);
8083     if (array_ctl != nullptr) {
8084       // Array case: size is round(header + element_size*arraylength).
8085       // Since arraylength is different for every array instance, we have to
8086       // compute the whole thing at runtime.
8087 
8088       PreserveJVMState pjvms(this);
8089       set_control(array_ctl);
8090       Node* arr_length = load_array_length(obj);
8091 
8092       int round_mask = MinObjAlignmentInBytes - 1;
8093       Node* mask = intcon(round_mask);
8094 
8095       Node* hss = intcon(Klass::_lh_header_size_shift);
8096       Node* hsm = intcon(Klass::_lh_header_size_mask);
8097       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
8098       header_size = _gvn.transform(new AndINode(header_size, hsm));
8099       header_size = _gvn.transform(new AddINode(header_size, mask));
8100 
8101       // There is no need to mask or shift this value.
8102       // The semantics of LShiftINode include an implicit mask to 0x1F.
8103       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
8104       Node* elem_shift = layout_val;
8105 
8106       Node* lengthx = ConvI2X(arr_length);
8107       Node* headerx = ConvI2X(header_size);
8108 
8109       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
8110       Node* size = _gvn.transform(new AddXNode(headerx, abody));
8111       if (round_mask != 0) {
8112         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
8113       }
8114       size = ConvX2L(size);
8115 
8116       result_reg->init_req(_array_path, control());
8117       result_val->init_req(_array_path, size);
8118     }
8119 
8120     if (!stopped()) {
8121       // Instance case: the layout helper gives us instance size almost directly,
8122       // but we need to mask out the _lh_instance_slow_path_bit.
8123       Node* size = ConvI2X(layout_val);
8124       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
8125       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
8126       size = _gvn.transform(new AndXNode(size, mask));
8127       size = ConvX2L(size);
8128 
8129       result_reg->init_req(_instance_path, control());
8130       result_val->init_req(_instance_path, size);
8131     }
8132 
8133     set_result(result_reg, result_val);
8134   }
8135 
8136   return true;
8137 }
8138 
8139 //------------------------------- inline_blackhole --------------------------------------
8140 //
8141 // Make sure all arguments to this node are alive.
8142 // This matches methods that were requested to be blackholed through compile commands.
8143 //
8144 bool LibraryCallKit::inline_blackhole() {
8145   assert(callee()->is_static(), "Should have been checked before: only static methods here");
8146   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
8147   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
8148 
8149   // Blackhole node pinches only the control, not memory. This allows
8150   // the blackhole to be pinned in the loop that computes blackholed
8151   // values, but have no other side effects, like breaking the optimizations
8152   // across the blackhole.
8153 
8154   Node* bh = _gvn.transform(new BlackholeNode(control()));
8155   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
8156 
8157   // Bind call arguments as blackhole arguments to keep them alive
8158   uint nargs = callee()->arg_size();
8159   for (uint i = 0; i < nargs; i++) {
8160     bh->add_req(argument(i));
8161   }
8162 
8163   return true;
8164 }