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