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