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