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