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