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