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