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