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