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