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