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