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