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