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