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