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