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