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