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