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