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