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