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