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