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