1 /*
   2  * Copyright (c) 1999, 2012, 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 "classfile/systemDictionary.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/compileLog.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/callGenerator.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/idealKit.hpp"
  35 #include "opto/mulnode.hpp"
  36 #include "opto/parse.hpp"
  37 #include "opto/runtime.hpp"
  38 #include "opto/subnode.hpp"
  39 #include "prims/nativeLookup.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 
  42 class LibraryIntrinsic : public InlineCallGenerator {
  43   // Extend the set of intrinsics known to the runtime:
  44  public:
  45  private:
  46   bool             _is_virtual;
  47   vmIntrinsics::ID _intrinsic_id;
  48 
  49  public:
  50   LibraryIntrinsic(ciMethod* m, bool is_virtual, vmIntrinsics::ID id)
  51     : InlineCallGenerator(m),
  52       _is_virtual(is_virtual),
  53       _intrinsic_id(id)
  54   {
  55   }
  56   virtual bool is_intrinsic() const { return true; }
  57   virtual bool is_virtual()   const { return _is_virtual; }
  58   virtual JVMState* generate(JVMState* jvms);
  59   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
  60 };
  61 
  62 
  63 // Local helper class for LibraryIntrinsic:
  64 class LibraryCallKit : public GraphKit {
  65  private:
  66   LibraryIntrinsic* _intrinsic;   // the library intrinsic being called
  67 
  68  public:
  69   LibraryCallKit(JVMState* caller, LibraryIntrinsic* intrinsic)
  70     : GraphKit(caller),
  71       _intrinsic(intrinsic)
  72   {
  73   }
  74 
  75   ciMethod*         caller()    const    { return jvms()->method(); }
  76   int               bci()       const    { return jvms()->bci(); }
  77   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
  78   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
  79   ciMethod*         callee()    const    { return _intrinsic->method(); }
  80   ciSignature*      signature() const    { return callee()->signature(); }
  81   int               arg_size()  const    { return callee()->arg_size(); }
  82 
  83   bool try_to_inline();
  84 
  85   // Helper functions to inline natives
  86   void push_result(RegionNode* region, PhiNode* value);
  87   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
  88   Node* generate_slow_guard(Node* test, RegionNode* region);
  89   Node* generate_fair_guard(Node* test, RegionNode* region);
  90   Node* generate_negative_guard(Node* index, RegionNode* region,
  91                                 // resulting CastII of index:
  92                                 Node* *pos_index = NULL);
  93   Node* generate_limit_guard(Node* offset, Node* subseq_length,
  94                              Node* array_length,
  95                              RegionNode* region);
  96   Node* generate_current_thread(Node* &tls_output);
  97   address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,
  98                               bool disjoint_bases, const char* &name, bool dest_uninitialized);
  99   Node* load_mirror_from_klass(Node* klass);
 100   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
 101                                       int nargs,
 102                                       RegionNode* region, int null_path,
 103                                       int offset);
 104   Node* load_klass_from_mirror(Node* mirror, bool never_see_null, int nargs,
 105                                RegionNode* region, int null_path) {
 106     int offset = java_lang_Class::klass_offset_in_bytes();
 107     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
 108                                          region, null_path,
 109                                          offset);
 110   }
 111   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
 112                                      int nargs,
 113                                      RegionNode* region, int null_path) {
 114     int offset = java_lang_Class::array_klass_offset_in_bytes();
 115     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
 116                                          region, null_path,
 117                                          offset);
 118   }
 119   Node* generate_access_flags_guard(Node* kls,
 120                                     int modifier_mask, int modifier_bits,
 121                                     RegionNode* region);
 122   Node* generate_interface_guard(Node* kls, RegionNode* region);
 123   Node* generate_array_guard(Node* kls, RegionNode* region) {
 124     return generate_array_guard_common(kls, region, false, false);
 125   }
 126   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
 127     return generate_array_guard_common(kls, region, false, true);
 128   }
 129   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
 130     return generate_array_guard_common(kls, region, true, false);
 131   }
 132   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
 133     return generate_array_guard_common(kls, region, true, true);
 134   }
 135   Node* generate_array_guard_common(Node* kls, RegionNode* region,
 136                                     bool obj_array, bool not_array);
 137   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
 138   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
 139                                      bool is_virtual = false, bool is_static = false);
 140   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
 141     return generate_method_call(method_id, false, true);
 142   }
 143   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
 144     return generate_method_call(method_id, true, false);
 145   }
 146 
 147   Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);
 148   Node* make_string_method_node(int opcode, Node* str1, Node* str2);
 149   bool inline_string_compareTo();
 150   bool inline_string_indexOf();
 151   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
 152   bool inline_string_equals();
 153   Node* pop_math_arg();
 154   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
 155   bool inline_math_native(vmIntrinsics::ID id);
 156   bool inline_trig(vmIntrinsics::ID id);
 157   bool inline_trans(vmIntrinsics::ID id);
 158   bool inline_abs(vmIntrinsics::ID id);
 159   bool inline_sqrt(vmIntrinsics::ID id);
 160   bool inline_pow(vmIntrinsics::ID id);
 161   bool inline_exp(vmIntrinsics::ID id);
 162   bool inline_min_max(vmIntrinsics::ID id);
 163   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
 164   // This returns Type::AnyPtr, RawPtr, or OopPtr.
 165   int classify_unsafe_addr(Node* &base, Node* &offset);
 166   Node* make_unsafe_address(Node* base, Node* offset);
 167   // Helper for inline_unsafe_access.
 168   // Generates the guards that check whether the result of
 169   // Unsafe.getObject should be recorded in an SATB log buffer.
 170   void insert_g1_pre_barrier(Node* base_oop, Node* offset, Node* pre_val);
 171   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
 172   bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
 173   bool inline_unsafe_allocate();
 174   bool inline_unsafe_copyMemory();
 175   bool inline_native_currentThread();
 176 #ifdef TRACE_HAVE_INTRINSICS
 177   bool inline_native_classID();
 178   bool inline_native_threadID();
 179 #endif
 180   bool inline_native_time_funcs(address method, const char* funcName);
 181   bool inline_native_isInterrupted();
 182   bool inline_native_Class_query(vmIntrinsics::ID id);
 183   bool inline_native_subtype_check();
 184 
 185   bool inline_native_newArray();
 186   bool inline_native_getLength();
 187   bool inline_array_copyOf(bool is_copyOfRange);
 188   bool inline_array_equals();
 189   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
 190   bool inline_native_clone(bool is_virtual);
 191   bool inline_native_Reflection_getCallerClass();
 192   bool inline_native_AtomicLong_get();
 193   bool inline_native_AtomicLong_attemptUpdate();
 194   bool is_method_invoke_or_aux_frame(JVMState* jvms);
 195   // Helper function for inlining native object hash method
 196   bool inline_native_hashcode(bool is_virtual, bool is_static);
 197   bool inline_native_getClass();
 198 
 199   // Helper functions for inlining arraycopy
 200   bool inline_arraycopy();
 201   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
 202                                                 RegionNode* slow_region);
 203   bool inline_unsafe_CAS(BasicType type);
 204   bool inline_unsafe_ordered_store(BasicType type);
 205   bool inline_fp_conversions(vmIntrinsics::ID id);
 206   bool inline_numberOfLeadingZeros(vmIntrinsics::ID id);
 207   bool inline_numberOfTrailingZeros(vmIntrinsics::ID id);
 208   bool inline_bitCount(vmIntrinsics::ID id);
 209   bool inline_reverseBytes(vmIntrinsics::ID id);
 210 
 211   bool inline_reference_get();
 212 };
 213 
 214 
 215 //---------------------------make_vm_intrinsic----------------------------
 216 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
 217   vmIntrinsics::ID id = m->intrinsic_id();
 218   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 219 
 220   if (DisableIntrinsic[0] != '\0'
 221       && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) {
 222     // disabled by a user request on the command line:
 223     // example: -XX:DisableIntrinsic=_hashCode,_getClass
 224     return NULL;
 225   }
 226 
 227   if (!m->is_loaded()) {
 228     // do not attempt to inline unloaded methods
 229     return NULL;
 230   }
 231 
 232   // Only a few intrinsics implement a virtual dispatch.
 233   // They are expensive calls which are also frequently overridden.
 234   if (is_virtual) {
 235     switch (id) {
 236     case vmIntrinsics::_hashCode:
 237     case vmIntrinsics::_clone:
 238       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
 239       break;
 240     default:
 241       return NULL;
 242     }
 243   }
 244 
 245   // -XX:-InlineNatives disables nearly all intrinsics:
 246   if (!InlineNatives) {
 247     switch (id) {
 248     case vmIntrinsics::_indexOf:
 249     case vmIntrinsics::_compareTo:
 250     case vmIntrinsics::_equals:
 251     case vmIntrinsics::_equalsC:
 252       break;  // InlineNatives does not control String.compareTo
 253     default:
 254       return NULL;
 255     }
 256   }
 257 
 258   switch (id) {
 259   case vmIntrinsics::_compareTo:
 260     if (!SpecialStringCompareTo)  return NULL;
 261     break;
 262   case vmIntrinsics::_indexOf:
 263     if (!SpecialStringIndexOf)  return NULL;
 264     break;
 265   case vmIntrinsics::_equals:
 266     if (!SpecialStringEquals)  return NULL;
 267     break;
 268   case vmIntrinsics::_equalsC:
 269     if (!SpecialArraysEquals)  return NULL;
 270     break;
 271   case vmIntrinsics::_arraycopy:
 272     if (!InlineArrayCopy)  return NULL;
 273     break;
 274   case vmIntrinsics::_copyMemory:
 275     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
 276     if (!InlineArrayCopy)  return NULL;
 277     break;
 278   case vmIntrinsics::_hashCode:
 279     if (!InlineObjectHash)  return NULL;
 280     break;
 281   case vmIntrinsics::_clone:
 282   case vmIntrinsics::_copyOf:
 283   case vmIntrinsics::_copyOfRange:
 284     if (!InlineObjectCopy)  return NULL;
 285     // These also use the arraycopy intrinsic mechanism:
 286     if (!InlineArrayCopy)  return NULL;
 287     break;
 288   case vmIntrinsics::_checkIndex:
 289     // We do not intrinsify this.  The optimizer does fine with it.
 290     return NULL;
 291 
 292   case vmIntrinsics::_get_AtomicLong:
 293   case vmIntrinsics::_attemptUpdate:
 294     if (!InlineAtomicLong)  return NULL;
 295     break;
 296 
 297   case vmIntrinsics::_getCallerClass:
 298     if (!UseNewReflection)  return NULL;
 299     if (!InlineReflectionGetCallerClass)  return NULL;
 300     if (!JDK_Version::is_gte_jdk14x_version())  return NULL;
 301     break;
 302 
 303   case vmIntrinsics::_bitCount_i:
 304     if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
 305     break;
 306 
 307   case vmIntrinsics::_bitCount_l:
 308     if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
 309     break;
 310 
 311   case vmIntrinsics::_numberOfLeadingZeros_i:
 312     if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
 313     break;
 314 
 315   case vmIntrinsics::_numberOfLeadingZeros_l:
 316     if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
 317     break;
 318 
 319   case vmIntrinsics::_numberOfTrailingZeros_i:
 320     if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
 321     break;
 322 
 323   case vmIntrinsics::_numberOfTrailingZeros_l:
 324     if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
 325     break;
 326 
 327   case vmIntrinsics::_Reference_get:
 328     // It is only when G1 is enabled that we absolutely
 329     // need to use the intrinsic version of Reference.get()
 330     // so that the value in the referent field, if necessary,
 331     // can be registered by the pre-barrier code.
 332     if (!UseG1GC) return NULL;
 333     break;
 334 
 335  default:
 336     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 337     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 338     break;
 339   }
 340 
 341   // -XX:-InlineClassNatives disables natives from the Class class.
 342   // The flag applies to all reflective calls, notably Array.newArray
 343   // (visible to Java programmers as Array.newInstance).
 344   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
 345       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
 346     if (!InlineClassNatives)  return NULL;
 347   }
 348 
 349   // -XX:-InlineThreadNatives disables natives from the Thread class.
 350   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
 351     if (!InlineThreadNatives)  return NULL;
 352   }
 353 
 354   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
 355   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
 356       m->holder()->name() == ciSymbol::java_lang_Float() ||
 357       m->holder()->name() == ciSymbol::java_lang_Double()) {
 358     if (!InlineMathNatives)  return NULL;
 359   }
 360 
 361   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
 362   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
 363     if (!InlineUnsafeOps)  return NULL;
 364   }
 365 
 366   return new LibraryIntrinsic(m, is_virtual, (vmIntrinsics::ID) id);
 367 }
 368 
 369 //----------------------register_library_intrinsics-----------------------
 370 // Initialize this file's data structures, for each Compile instance.
 371 void Compile::register_library_intrinsics() {
 372   // Nothing to do here.
 373 }
 374 
 375 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 376   LibraryCallKit kit(jvms, this);
 377   Compile* C = kit.C;
 378   int nodes = C->unique();
 379 #ifndef PRODUCT
 380   if ((PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) && Verbose) {
 381     char buf[1000];
 382     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 383     tty->print_cr("Intrinsic %s", str);
 384   }
 385 #endif
 386 
 387   if (kit.try_to_inline()) {
 388     if (PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) {
 389       CompileTask::print_inlining(kit.callee(), jvms->depth() - 1, kit.bci(), is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
 390     }
 391     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 392     if (C->log()) {
 393       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 394                      vmIntrinsics::name_at(intrinsic_id()),
 395                      (is_virtual() ? " virtual='1'" : ""),
 396                      C->unique() - nodes);
 397     }
 398     return kit.transfer_exceptions_into_jvms();
 399   }
 400 
 401   // The intrinsic bailed out
 402   if (PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) {
 403     if (jvms->has_method()) {
 404       // Not a root compile.
 405       const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 406       CompileTask::print_inlining(kit.callee(), jvms->depth() - 1, kit.bci(), msg);
 407     } else {
 408       // Root compile
 409       tty->print("Did not generate intrinsic %s%s at bci:%d in",
 410                vmIntrinsics::name_at(intrinsic_id()),
 411                (is_virtual() ? " (virtual)" : ""), kit.bci());
 412     }
 413   }
 414   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 415   return NULL;
 416 }
 417 
 418 bool LibraryCallKit::try_to_inline() {
 419   // Handle symbolic names for otherwise undistinguished boolean switches:
 420   const bool is_store       = true;
 421   const bool is_native_ptr  = true;
 422   const bool is_static      = true;
 423 
 424   if (!jvms()->has_method()) {
 425     // Root JVMState has a null method.
 426     assert(map()->memory()->Opcode() == Op_Parm, "");
 427     // Insert the memory aliasing node
 428     set_all_memory(reset_memory());
 429   }
 430   assert(merged_memory(), "");
 431 
 432   switch (intrinsic_id()) {
 433   case vmIntrinsics::_hashCode:
 434     return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 435   case vmIntrinsics::_identityHashCode:
 436     return inline_native_hashcode(/*!virtual*/ false, is_static);
 437   case vmIntrinsics::_getClass:
 438     return inline_native_getClass();
 439 
 440   case vmIntrinsics::_dsin:
 441   case vmIntrinsics::_dcos:
 442   case vmIntrinsics::_dtan:
 443   case vmIntrinsics::_dabs:
 444   case vmIntrinsics::_datan2:
 445   case vmIntrinsics::_dsqrt:
 446   case vmIntrinsics::_dexp:
 447   case vmIntrinsics::_dlog:
 448   case vmIntrinsics::_dlog10:
 449   case vmIntrinsics::_dpow:
 450     return inline_math_native(intrinsic_id());
 451 
 452   case vmIntrinsics::_min:
 453   case vmIntrinsics::_max:
 454     return inline_min_max(intrinsic_id());
 455 
 456   case vmIntrinsics::_arraycopy:
 457     return inline_arraycopy();
 458 
 459   case vmIntrinsics::_compareTo:
 460     return inline_string_compareTo();
 461   case vmIntrinsics::_indexOf:
 462     return inline_string_indexOf();
 463   case vmIntrinsics::_equals:
 464     return inline_string_equals();
 465 
 466   case vmIntrinsics::_getObject:
 467     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, false);
 468   case vmIntrinsics::_getBoolean:
 469     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, false);
 470   case vmIntrinsics::_getByte:
 471     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, false);
 472   case vmIntrinsics::_getShort:
 473     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, false);
 474   case vmIntrinsics::_getChar:
 475     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, false);
 476   case vmIntrinsics::_getInt:
 477     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, false);
 478   case vmIntrinsics::_getLong:
 479     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, false);
 480   case vmIntrinsics::_getFloat:
 481     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, false);
 482   case vmIntrinsics::_getDouble:
 483     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, false);
 484 
 485   case vmIntrinsics::_putObject:
 486     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, false);
 487   case vmIntrinsics::_putBoolean:
 488     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, false);
 489   case vmIntrinsics::_putByte:
 490     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, false);
 491   case vmIntrinsics::_putShort:
 492     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, false);
 493   case vmIntrinsics::_putChar:
 494     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, false);
 495   case vmIntrinsics::_putInt:
 496     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, false);
 497   case vmIntrinsics::_putLong:
 498     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, false);
 499   case vmIntrinsics::_putFloat:
 500     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, false);
 501   case vmIntrinsics::_putDouble:
 502     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, false);
 503 
 504   case vmIntrinsics::_getByte_raw:
 505     return inline_unsafe_access(is_native_ptr, !is_store, T_BYTE, false);
 506   case vmIntrinsics::_getShort_raw:
 507     return inline_unsafe_access(is_native_ptr, !is_store, T_SHORT, false);
 508   case vmIntrinsics::_getChar_raw:
 509     return inline_unsafe_access(is_native_ptr, !is_store, T_CHAR, false);
 510   case vmIntrinsics::_getInt_raw:
 511     return inline_unsafe_access(is_native_ptr, !is_store, T_INT, false);
 512   case vmIntrinsics::_getLong_raw:
 513     return inline_unsafe_access(is_native_ptr, !is_store, T_LONG, false);
 514   case vmIntrinsics::_getFloat_raw:
 515     return inline_unsafe_access(is_native_ptr, !is_store, T_FLOAT, false);
 516   case vmIntrinsics::_getDouble_raw:
 517     return inline_unsafe_access(is_native_ptr, !is_store, T_DOUBLE, false);
 518   case vmIntrinsics::_getAddress_raw:
 519     return inline_unsafe_access(is_native_ptr, !is_store, T_ADDRESS, false);
 520 
 521   case vmIntrinsics::_putByte_raw:
 522     return inline_unsafe_access(is_native_ptr, is_store, T_BYTE, false);
 523   case vmIntrinsics::_putShort_raw:
 524     return inline_unsafe_access(is_native_ptr, is_store, T_SHORT, false);
 525   case vmIntrinsics::_putChar_raw:
 526     return inline_unsafe_access(is_native_ptr, is_store, T_CHAR, false);
 527   case vmIntrinsics::_putInt_raw:
 528     return inline_unsafe_access(is_native_ptr, is_store, T_INT, false);
 529   case vmIntrinsics::_putLong_raw:
 530     return inline_unsafe_access(is_native_ptr, is_store, T_LONG, false);
 531   case vmIntrinsics::_putFloat_raw:
 532     return inline_unsafe_access(is_native_ptr, is_store, T_FLOAT, false);
 533   case vmIntrinsics::_putDouble_raw:
 534     return inline_unsafe_access(is_native_ptr, is_store, T_DOUBLE, false);
 535   case vmIntrinsics::_putAddress_raw:
 536     return inline_unsafe_access(is_native_ptr, is_store, T_ADDRESS, false);
 537 
 538   case vmIntrinsics::_getObjectVolatile:
 539     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, true);
 540   case vmIntrinsics::_getBooleanVolatile:
 541     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, true);
 542   case vmIntrinsics::_getByteVolatile:
 543     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, true);
 544   case vmIntrinsics::_getShortVolatile:
 545     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, true);
 546   case vmIntrinsics::_getCharVolatile:
 547     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, true);
 548   case vmIntrinsics::_getIntVolatile:
 549     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, true);
 550   case vmIntrinsics::_getLongVolatile:
 551     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, true);
 552   case vmIntrinsics::_getFloatVolatile:
 553     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, true);
 554   case vmIntrinsics::_getDoubleVolatile:
 555     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, true);
 556 
 557   case vmIntrinsics::_putObjectVolatile:
 558     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, true);
 559   case vmIntrinsics::_putBooleanVolatile:
 560     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, true);
 561   case vmIntrinsics::_putByteVolatile:
 562     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, true);
 563   case vmIntrinsics::_putShortVolatile:
 564     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, true);
 565   case vmIntrinsics::_putCharVolatile:
 566     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, true);
 567   case vmIntrinsics::_putIntVolatile:
 568     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, true);
 569   case vmIntrinsics::_putLongVolatile:
 570     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, true);
 571   case vmIntrinsics::_putFloatVolatile:
 572     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, true);
 573   case vmIntrinsics::_putDoubleVolatile:
 574     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, true);
 575 
 576   case vmIntrinsics::_prefetchRead:
 577     return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
 578   case vmIntrinsics::_prefetchWrite:
 579     return inline_unsafe_prefetch(!is_native_ptr, is_store, !is_static);
 580   case vmIntrinsics::_prefetchReadStatic:
 581     return inline_unsafe_prefetch(!is_native_ptr, !is_store, is_static);
 582   case vmIntrinsics::_prefetchWriteStatic:
 583     return inline_unsafe_prefetch(!is_native_ptr, is_store, is_static);
 584 
 585   case vmIntrinsics::_compareAndSwapObject:
 586     return inline_unsafe_CAS(T_OBJECT);
 587   case vmIntrinsics::_compareAndSwapInt:
 588     return inline_unsafe_CAS(T_INT);
 589   case vmIntrinsics::_compareAndSwapLong:
 590     return inline_unsafe_CAS(T_LONG);
 591 
 592   case vmIntrinsics::_putOrderedObject:
 593     return inline_unsafe_ordered_store(T_OBJECT);
 594   case vmIntrinsics::_putOrderedInt:
 595     return inline_unsafe_ordered_store(T_INT);
 596   case vmIntrinsics::_putOrderedLong:
 597     return inline_unsafe_ordered_store(T_LONG);
 598 
 599   case vmIntrinsics::_currentThread:
 600     return inline_native_currentThread();
 601   case vmIntrinsics::_isInterrupted:
 602     return inline_native_isInterrupted();
 603 
 604 #ifdef TRACE_HAVE_INTRINSICS
 605   case vmIntrinsics::_classID:
 606     return inline_native_classID();
 607   case vmIntrinsics::_threadID:
 608     return inline_native_threadID();
 609   case vmIntrinsics::_counterTime:
 610     return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
 611 #endif
 612   case vmIntrinsics::_currentTimeMillis:
 613     return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 614   case vmIntrinsics::_nanoTime:
 615     return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 616   case vmIntrinsics::_allocateInstance:
 617     return inline_unsafe_allocate();
 618   case vmIntrinsics::_copyMemory:
 619     return inline_unsafe_copyMemory();
 620   case vmIntrinsics::_newArray:
 621     return inline_native_newArray();
 622   case vmIntrinsics::_getLength:
 623     return inline_native_getLength();
 624   case vmIntrinsics::_copyOf:
 625     return inline_array_copyOf(false);
 626   case vmIntrinsics::_copyOfRange:
 627     return inline_array_copyOf(true);
 628   case vmIntrinsics::_equalsC:
 629     return inline_array_equals();
 630   case vmIntrinsics::_clone:
 631     return inline_native_clone(intrinsic()->is_virtual());
 632 
 633   case vmIntrinsics::_isAssignableFrom:
 634     return inline_native_subtype_check();
 635 
 636   case vmIntrinsics::_isInstance:
 637   case vmIntrinsics::_getModifiers:
 638   case vmIntrinsics::_isInterface:
 639   case vmIntrinsics::_isArray:
 640   case vmIntrinsics::_isPrimitive:
 641   case vmIntrinsics::_getSuperclass:
 642   case vmIntrinsics::_getComponentType:
 643   case vmIntrinsics::_getClassAccessFlags:
 644     return inline_native_Class_query(intrinsic_id());
 645 
 646   case vmIntrinsics::_floatToRawIntBits:
 647   case vmIntrinsics::_floatToIntBits:
 648   case vmIntrinsics::_intBitsToFloat:
 649   case vmIntrinsics::_doubleToRawLongBits:
 650   case vmIntrinsics::_doubleToLongBits:
 651   case vmIntrinsics::_longBitsToDouble:
 652     return inline_fp_conversions(intrinsic_id());
 653 
 654   case vmIntrinsics::_numberOfLeadingZeros_i:
 655   case vmIntrinsics::_numberOfLeadingZeros_l:
 656     return inline_numberOfLeadingZeros(intrinsic_id());
 657 
 658   case vmIntrinsics::_numberOfTrailingZeros_i:
 659   case vmIntrinsics::_numberOfTrailingZeros_l:
 660     return inline_numberOfTrailingZeros(intrinsic_id());
 661 
 662   case vmIntrinsics::_bitCount_i:
 663   case vmIntrinsics::_bitCount_l:
 664     return inline_bitCount(intrinsic_id());
 665 
 666   case vmIntrinsics::_reverseBytes_i:
 667   case vmIntrinsics::_reverseBytes_l:
 668   case vmIntrinsics::_reverseBytes_s:
 669   case vmIntrinsics::_reverseBytes_c:
 670     return inline_reverseBytes((vmIntrinsics::ID) intrinsic_id());
 671 
 672   case vmIntrinsics::_get_AtomicLong:
 673     return inline_native_AtomicLong_get();
 674   case vmIntrinsics::_attemptUpdate:
 675     return inline_native_AtomicLong_attemptUpdate();
 676 
 677   case vmIntrinsics::_getCallerClass:
 678     return inline_native_Reflection_getCallerClass();
 679 
 680   case vmIntrinsics::_Reference_get:
 681     return inline_reference_get();
 682 
 683   default:
 684     // If you get here, it may be that someone has added a new intrinsic
 685     // to the list in vmSymbols.hpp without implementing it here.
 686 #ifndef PRODUCT
 687     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 688       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 689                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
 690     }
 691 #endif
 692     return false;
 693   }
 694 }
 695 
 696 //------------------------------push_result------------------------------
 697 // Helper function for finishing intrinsics.
 698 void LibraryCallKit::push_result(RegionNode* region, PhiNode* value) {
 699   record_for_igvn(region);
 700   set_control(_gvn.transform(region));
 701   BasicType value_type = value->type()->basic_type();
 702   push_node(value_type, _gvn.transform(value));
 703 }
 704 
 705 //------------------------------generate_guard---------------------------
 706 // Helper function for generating guarded fast-slow graph structures.
 707 // The given 'test', if true, guards a slow path.  If the test fails
 708 // then a fast path can be taken.  (We generally hope it fails.)
 709 // In all cases, GraphKit::control() is updated to the fast path.
 710 // The returned value represents the control for the slow path.
 711 // The return value is never 'top'; it is either a valid control
 712 // or NULL if it is obvious that the slow path can never be taken.
 713 // Also, if region and the slow control are not NULL, the slow edge
 714 // is appended to the region.
 715 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 716   if (stopped()) {
 717     // Already short circuited.
 718     return NULL;
 719   }
 720 
 721   // Build an if node and its projections.
 722   // If test is true we take the slow path, which we assume is uncommon.
 723   if (_gvn.type(test) == TypeInt::ZERO) {
 724     // The slow branch is never taken.  No need to build this guard.
 725     return NULL;
 726   }
 727 
 728   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 729 
 730   Node* if_slow = _gvn.transform( new (C, 1) IfTrueNode(iff) );
 731   if (if_slow == top()) {
 732     // The slow branch is never taken.  No need to build this guard.
 733     return NULL;
 734   }
 735 
 736   if (region != NULL)
 737     region->add_req(if_slow);
 738 
 739   Node* if_fast = _gvn.transform( new (C, 1) IfFalseNode(iff) );
 740   set_control(if_fast);
 741 
 742   return if_slow;
 743 }
 744 
 745 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 746   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 747 }
 748 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 749   return generate_guard(test, region, PROB_FAIR);
 750 }
 751 
 752 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 753                                                      Node* *pos_index) {
 754   if (stopped())
 755     return NULL;                // already stopped
 756   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 757     return NULL;                // index is already adequately typed
 758   Node* cmp_lt = _gvn.transform( new (C, 3) CmpINode(index, intcon(0)) );
 759   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
 760   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 761   if (is_neg != NULL && pos_index != NULL) {
 762     // Emulate effect of Parse::adjust_map_after_if.
 763     Node* ccast = new (C, 2) CastIINode(index, TypeInt::POS);
 764     ccast->set_req(0, control());
 765     (*pos_index) = _gvn.transform(ccast);
 766   }
 767   return is_neg;
 768 }
 769 
 770 // Make sure that 'position' is a valid limit index, in [0..length].
 771 // There are two equivalent plans for checking this:
 772 //   A. (offset + copyLength)  unsigned<=  arrayLength
 773 //   B. offset  <=  (arrayLength - copyLength)
 774 // We require that all of the values above, except for the sum and
 775 // difference, are already known to be non-negative.
 776 // Plan A is robust in the face of overflow, if offset and copyLength
 777 // are both hugely positive.
 778 //
 779 // Plan B is less direct and intuitive, but it does not overflow at
 780 // all, since the difference of two non-negatives is always
 781 // representable.  Whenever Java methods must perform the equivalent
 782 // check they generally use Plan B instead of Plan A.
 783 // For the moment we use Plan A.
 784 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 785                                                   Node* subseq_length,
 786                                                   Node* array_length,
 787                                                   RegionNode* region) {
 788   if (stopped())
 789     return NULL;                // already stopped
 790   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 791   if (zero_offset && subseq_length->eqv_uncast(array_length))
 792     return NULL;                // common case of whole-array copy
 793   Node* last = subseq_length;
 794   if (!zero_offset)             // last += offset
 795     last = _gvn.transform( new (C, 3) AddINode(last, offset));
 796   Node* cmp_lt = _gvn.transform( new (C, 3) CmpUNode(array_length, last) );
 797   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
 798   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 799   return is_over;
 800 }
 801 
 802 
 803 //--------------------------generate_current_thread--------------------
 804 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
 805   ciKlass*    thread_klass = env()->Thread_klass();
 806   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 807   Node* thread = _gvn.transform(new (C, 1) ThreadLocalNode());
 808   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
 809   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT);
 810   tls_output = thread;
 811   return threadObj;
 812 }
 813 
 814 
 815 //------------------------------make_string_method_node------------------------
 816 // Helper method for String intrinsic functions. This version is called
 817 // with str1 and str2 pointing to String object nodes.
 818 //
 819 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
 820   Node* no_ctrl = NULL;
 821 
 822   // Get start addr of string
 823   Node* str1_value   = load_String_value(no_ctrl, str1);
 824   Node* str1_offset  = load_String_offset(no_ctrl, str1);
 825   Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
 826 
 827   // Get length of string 1
 828   Node* str1_len  = load_String_length(no_ctrl, str1);
 829 
 830   Node* str2_value   = load_String_value(no_ctrl, str2);
 831   Node* str2_offset  = load_String_offset(no_ctrl, str2);
 832   Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
 833 
 834   Node* str2_len = NULL;
 835   Node* result = NULL;
 836 
 837   switch (opcode) {
 838   case Op_StrIndexOf:
 839     // Get length of string 2
 840     str2_len = load_String_length(no_ctrl, str2);
 841 
 842     result = new (C, 6) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
 843                                  str1_start, str1_len, str2_start, str2_len);
 844     break;
 845   case Op_StrComp:
 846     // Get length of string 2
 847     str2_len = load_String_length(no_ctrl, str2);
 848 
 849     result = new (C, 6) StrCompNode(control(), memory(TypeAryPtr::CHARS),
 850                                  str1_start, str1_len, str2_start, str2_len);
 851     break;
 852   case Op_StrEquals:
 853     result = new (C, 5) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
 854                                str1_start, str2_start, str1_len);
 855     break;
 856   default:
 857     ShouldNotReachHere();
 858     return NULL;
 859   }
 860 
 861   // All these intrinsics have checks.
 862   C->set_has_split_ifs(true); // Has chance for split-if optimization
 863 
 864   return _gvn.transform(result);
 865 }
 866 
 867 // Helper method for String intrinsic functions. This version is called
 868 // with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
 869 // to Int nodes containing the lenghts of str1 and str2.
 870 //
 871 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
 872 
 873   Node* result = NULL;
 874   switch (opcode) {
 875   case Op_StrIndexOf:
 876     result = new (C, 6) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
 877                                  str1_start, cnt1, str2_start, cnt2);
 878     break;
 879   case Op_StrComp:
 880     result = new (C, 6) StrCompNode(control(), memory(TypeAryPtr::CHARS),
 881                                  str1_start, cnt1, str2_start, cnt2);
 882     break;
 883   case Op_StrEquals:
 884     result = new (C, 5) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
 885                                  str1_start, str2_start, cnt1);
 886     break;
 887   default:
 888     ShouldNotReachHere();
 889     return NULL;
 890   }
 891 
 892   // All these intrinsics have checks.
 893   C->set_has_split_ifs(true); // Has chance for split-if optimization
 894 
 895   return _gvn.transform(result);
 896 }
 897 
 898 //------------------------------inline_string_compareTo------------------------
 899 bool LibraryCallKit::inline_string_compareTo() {
 900 
 901   if (!Matcher::has_match_rule(Op_StrComp)) return false;
 902 
 903   _sp += 2;
 904   Node *argument = pop();  // pop non-receiver first:  it was pushed second
 905   Node *receiver = pop();
 906 
 907   // Null check on self without removing any arguments.  The argument
 908   // null check technically happens in the wrong place, which can lead to
 909   // invalid stack traces when string compare is inlined into a method
 910   // which handles NullPointerExceptions.
 911   _sp += 2;
 912   receiver = do_null_check(receiver, T_OBJECT);
 913   argument = do_null_check(argument, T_OBJECT);
 914   _sp -= 2;
 915   if (stopped()) {
 916     return true;
 917   }
 918 
 919   Node* compare = make_string_method_node(Op_StrComp, receiver, argument);
 920   push(compare);
 921   return true;
 922 }
 923 
 924 //------------------------------inline_string_equals------------------------
 925 bool LibraryCallKit::inline_string_equals() {
 926 
 927   if (!Matcher::has_match_rule(Op_StrEquals)) return false;
 928 
 929   int nargs = 2;
 930   _sp += nargs;
 931   Node* argument = pop();  // pop non-receiver first:  it was pushed second
 932   Node* receiver = pop();
 933 
 934   // Null check on self without removing any arguments.  The argument
 935   // null check technically happens in the wrong place, which can lead to
 936   // invalid stack traces when string compare is inlined into a method
 937   // which handles NullPointerExceptions.
 938   _sp += nargs;
 939   receiver = do_null_check(receiver, T_OBJECT);
 940   //should not do null check for argument for String.equals(), because spec
 941   //allows to specify NULL as argument.
 942   _sp -= nargs;
 943 
 944   if (stopped()) {
 945     return true;
 946   }
 947 
 948   // paths (plus control) merge
 949   RegionNode* region = new (C, 5) RegionNode(5);
 950   Node* phi = new (C, 5) PhiNode(region, TypeInt::BOOL);
 951 
 952   // does source == target string?
 953   Node* cmp = _gvn.transform(new (C, 3) CmpPNode(receiver, argument));
 954   Node* bol = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::eq));
 955 
 956   Node* if_eq = generate_slow_guard(bol, NULL);
 957   if (if_eq != NULL) {
 958     // receiver == argument
 959     phi->init_req(2, intcon(1));
 960     region->init_req(2, if_eq);
 961   }
 962 
 963   // get String klass for instanceOf
 964   ciInstanceKlass* klass = env()->String_klass();
 965 
 966   if (!stopped()) {
 967     _sp += nargs;          // gen_instanceof might do an uncommon trap
 968     Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
 969     _sp -= nargs;
 970     Node* cmp  = _gvn.transform(new (C, 3) CmpINode(inst, intcon(1)));
 971     Node* bol  = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::ne));
 972 
 973     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
 974     //instanceOf == true, fallthrough
 975 
 976     if (inst_false != NULL) {
 977       phi->init_req(3, intcon(0));
 978       region->init_req(3, inst_false);
 979     }
 980   }
 981 
 982   if (!stopped()) {
 983     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
 984 
 985     // Properly cast the argument to String
 986     argument = _gvn.transform(new (C, 2) CheckCastPPNode(control(), argument, string_type));
 987     // This path is taken only when argument's type is String:NotNull.
 988     argument = cast_not_null(argument, false);
 989 
 990     Node* no_ctrl = NULL;
 991 
 992     // Get start addr of receiver
 993     Node* receiver_val    = load_String_value(no_ctrl, receiver);
 994     Node* receiver_offset = load_String_offset(no_ctrl, receiver);
 995     Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
 996 
 997     // Get length of receiver
 998     Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
 999 
1000     // Get start addr of argument
1001     Node* argument_val   = load_String_value(no_ctrl, argument);
1002     Node* argument_offset = load_String_offset(no_ctrl, argument);
1003     Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
1004 
1005     // Get length of argument
1006     Node* argument_cnt  = load_String_length(no_ctrl, argument);
1007 
1008     // Check for receiver count != argument count
1009     Node* cmp = _gvn.transform( new(C, 3) CmpINode(receiver_cnt, argument_cnt) );
1010     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::ne) );
1011     Node* if_ne = generate_slow_guard(bol, NULL);
1012     if (if_ne != NULL) {
1013       phi->init_req(4, intcon(0));
1014       region->init_req(4, if_ne);
1015     }
1016 
1017     // Check for count == 0 is done by assembler code for StrEquals.
1018 
1019     if (!stopped()) {
1020       Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
1021       phi->init_req(1, equals);
1022       region->init_req(1, control());
1023     }
1024   }
1025 
1026   // post merge
1027   set_control(_gvn.transform(region));
1028   record_for_igvn(region);
1029 
1030   push(_gvn.transform(phi));
1031 
1032   return true;
1033 }
1034 
1035 //------------------------------inline_array_equals----------------------------
1036 bool LibraryCallKit::inline_array_equals() {
1037 
1038   if (!Matcher::has_match_rule(Op_AryEq)) return false;
1039 
1040   _sp += 2;
1041   Node *argument2 = pop();
1042   Node *argument1 = pop();
1043 
1044   Node* equals =
1045     _gvn.transform(new (C, 4) AryEqNode(control(), memory(TypeAryPtr::CHARS),
1046                                         argument1, argument2) );
1047   push(equals);
1048   return true;
1049 }
1050 
1051 // Java version of String.indexOf(constant string)
1052 // class StringDecl {
1053 //   StringDecl(char[] ca) {
1054 //     offset = 0;
1055 //     count = ca.length;
1056 //     value = ca;
1057 //   }
1058 //   int offset;
1059 //   int count;
1060 //   char[] value;
1061 // }
1062 //
1063 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
1064 //                             int targetOffset, int cache_i, int md2) {
1065 //   int cache = cache_i;
1066 //   int sourceOffset = string_object.offset;
1067 //   int sourceCount = string_object.count;
1068 //   int targetCount = target_object.length;
1069 //
1070 //   int targetCountLess1 = targetCount - 1;
1071 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
1072 //
1073 //   char[] source = string_object.value;
1074 //   char[] target = target_object;
1075 //   int lastChar = target[targetCountLess1];
1076 //
1077 //  outer_loop:
1078 //   for (int i = sourceOffset; i < sourceEnd; ) {
1079 //     int src = source[i + targetCountLess1];
1080 //     if (src == lastChar) {
1081 //       // With random strings and a 4-character alphabet,
1082 //       // reverse matching at this point sets up 0.8% fewer
1083 //       // frames, but (paradoxically) makes 0.3% more probes.
1084 //       // Since those probes are nearer the lastChar probe,
1085 //       // there is may be a net D$ win with reverse matching.
1086 //       // But, reversing loop inhibits unroll of inner loop
1087 //       // for unknown reason.  So, does running outer loop from
1088 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
1089 //       for (int j = 0; j < targetCountLess1; j++) {
1090 //         if (target[targetOffset + j] != source[i+j]) {
1091 //           if ((cache & (1 << source[i+j])) == 0) {
1092 //             if (md2 < j+1) {
1093 //               i += j+1;
1094 //               continue outer_loop;
1095 //             }
1096 //           }
1097 //           i += md2;
1098 //           continue outer_loop;
1099 //         }
1100 //       }
1101 //       return i - sourceOffset;
1102 //     }
1103 //     if ((cache & (1 << src)) == 0) {
1104 //       i += targetCountLess1;
1105 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
1106 //     i++;
1107 //   }
1108 //   return -1;
1109 // }
1110 
1111 //------------------------------string_indexOf------------------------
1112 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1113                                      jint cache_i, jint md2_i) {
1114 
1115   Node* no_ctrl  = NULL;
1116   float likely   = PROB_LIKELY(0.9);
1117   float unlikely = PROB_UNLIKELY(0.9);
1118 
1119   const int nargs = 2; // number of arguments to push back for uncommon trap in predicate
1120 
1121   Node* source        = load_String_value(no_ctrl, string_object);
1122   Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
1123   Node* sourceCount   = load_String_length(no_ctrl, string_object);
1124 
1125   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)) );
1126   jint target_length = target_array->length();
1127   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1128   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1129 
1130   IdealKit kit(this, false, true);
1131 #define __ kit.
1132   Node* zero             = __ ConI(0);
1133   Node* one              = __ ConI(1);
1134   Node* cache            = __ ConI(cache_i);
1135   Node* md2              = __ ConI(md2_i);
1136   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1137   Node* targetCount      = __ ConI(target_length);
1138   Node* targetCountLess1 = __ ConI(target_length - 1);
1139   Node* targetOffset     = __ ConI(targetOffset_i);
1140   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1141 
1142   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1143   Node* outer_loop = __ make_label(2 /* goto */);
1144   Node* return_    = __ make_label(1);
1145 
1146   __ set(rtn,__ ConI(-1));
1147   __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
1148        Node* i2  = __ AddI(__ value(i), targetCountLess1);
1149        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1150        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1151        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1152          __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
1153               Node* tpj = __ AddI(targetOffset, __ value(j));
1154               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1155               Node* ipj  = __ AddI(__ value(i), __ value(j));
1156               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1157               __ if_then(targ, BoolTest::ne, src2); {
1158                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1159                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1160                     __ increment(i, __ AddI(__ value(j), one));
1161                     __ goto_(outer_loop);
1162                   } __ end_if(); __ dead(j);
1163                 }__ end_if(); __ dead(j);
1164                 __ increment(i, md2);
1165                 __ goto_(outer_loop);
1166               }__ end_if();
1167               __ increment(j, one);
1168          }__ end_loop(); __ dead(j);
1169          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1170          __ goto_(return_);
1171        }__ end_if();
1172        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1173          __ increment(i, targetCountLess1);
1174        }__ end_if();
1175        __ increment(i, one);
1176        __ bind(outer_loop);
1177   }__ end_loop(); __ dead(i);
1178   __ bind(return_);
1179 
1180   // Final sync IdealKit and GraphKit.
1181   final_sync(kit);
1182   Node* result = __ value(rtn);
1183 #undef __
1184   C->set_has_loops(true);
1185   return result;
1186 }
1187 
1188 //------------------------------inline_string_indexOf------------------------
1189 bool LibraryCallKit::inline_string_indexOf() {
1190 
1191   _sp += 2;
1192   Node *argument = pop();  // pop non-receiver first:  it was pushed second
1193   Node *receiver = pop();
1194 
1195   Node* result;
1196   // Disable the use of pcmpestri until it can be guaranteed that
1197   // the load doesn't cross into the uncommited space.
1198   if (Matcher::has_match_rule(Op_StrIndexOf) &&
1199       UseSSE42Intrinsics) {
1200     // Generate SSE4.2 version of indexOf
1201     // We currently only have match rules that use SSE4.2
1202 
1203     // Null check on self without removing any arguments.  The argument
1204     // null check technically happens in the wrong place, which can lead to
1205     // invalid stack traces when string compare is inlined into a method
1206     // which handles NullPointerExceptions.
1207     _sp += 2;
1208     receiver = do_null_check(receiver, T_OBJECT);
1209     argument = do_null_check(argument, T_OBJECT);
1210     _sp -= 2;
1211 
1212     if (stopped()) {
1213       return true;
1214     }
1215 
1216     ciInstanceKlass* str_klass = env()->String_klass();
1217     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);
1218 
1219     // Make the merge point
1220     RegionNode* result_rgn = new (C, 4) RegionNode(4);
1221     Node*       result_phi = new (C, 4) PhiNode(result_rgn, TypeInt::INT);
1222     Node* no_ctrl  = NULL;
1223 
1224     // Get start addr of source string
1225     Node* source = load_String_value(no_ctrl, receiver);
1226     Node* source_offset = load_String_offset(no_ctrl, receiver);
1227     Node* source_start = array_element_address(source, source_offset, T_CHAR);
1228 
1229     // Get length of source string
1230     Node* source_cnt  = load_String_length(no_ctrl, receiver);
1231 
1232     // Get start addr of substring
1233     Node* substr = load_String_value(no_ctrl, argument);
1234     Node* substr_offset = load_String_offset(no_ctrl, argument);
1235     Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
1236 
1237     // Get length of source string
1238     Node* substr_cnt  = load_String_length(no_ctrl, argument);
1239 
1240     // Check for substr count > string count
1241     Node* cmp = _gvn.transform( new(C, 3) CmpINode(substr_cnt, source_cnt) );
1242     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::gt) );
1243     Node* if_gt = generate_slow_guard(bol, NULL);
1244     if (if_gt != NULL) {
1245       result_phi->init_req(2, intcon(-1));
1246       result_rgn->init_req(2, if_gt);
1247     }
1248 
1249     if (!stopped()) {
1250       // Check for substr count == 0
1251       cmp = _gvn.transform( new(C, 3) CmpINode(substr_cnt, intcon(0)) );
1252       bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::eq) );
1253       Node* if_zero = generate_slow_guard(bol, NULL);
1254       if (if_zero != NULL) {
1255         result_phi->init_req(3, intcon(0));
1256         result_rgn->init_req(3, if_zero);
1257       }
1258     }
1259 
1260     if (!stopped()) {
1261       result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
1262       result_phi->init_req(1, result);
1263       result_rgn->init_req(1, control());
1264     }
1265     set_control(_gvn.transform(result_rgn));
1266     record_for_igvn(result_rgn);
1267     result = _gvn.transform(result_phi);
1268 
1269   } else { // Use LibraryCallKit::string_indexOf
1270     // don't intrinsify if argument isn't a constant string.
1271     if (!argument->is_Con()) {
1272      return false;
1273     }
1274     const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
1275     if (str_type == NULL) {
1276       return false;
1277     }
1278     ciInstanceKlass* klass = env()->String_klass();
1279     ciObject* str_const = str_type->const_oop();
1280     if (str_const == NULL || str_const->klass() != klass) {
1281       return false;
1282     }
1283     ciInstance* str = str_const->as_instance();
1284     assert(str != NULL, "must be instance");
1285 
1286     ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1287     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1288 
1289     int o;
1290     int c;
1291     if (java_lang_String::has_offset_field()) {
1292       o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
1293       c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
1294     } else {
1295       o = 0;
1296       c = pat->length();
1297     }
1298 
1299     // constant strings have no offset and count == length which
1300     // simplifies the resulting code somewhat so lets optimize for that.
1301     if (o != 0 || c != pat->length()) {
1302      return false;
1303     }
1304 
1305     // Null check on self without removing any arguments.  The argument
1306     // null check technically happens in the wrong place, which can lead to
1307     // invalid stack traces when string compare is inlined into a method
1308     // which handles NullPointerExceptions.
1309     _sp += 2;
1310     receiver = do_null_check(receiver, T_OBJECT);
1311     // No null check on the argument is needed since it's a constant String oop.
1312     _sp -= 2;
1313     if (stopped()) {
1314       return true;
1315     }
1316 
1317     // The null string as a pattern always returns 0 (match at beginning of string)
1318     if (c == 0) {
1319       push(intcon(0));
1320       return true;
1321     }
1322 
1323     // Generate default indexOf
1324     jchar lastChar = pat->char_at(o + (c - 1));
1325     int cache = 0;
1326     int i;
1327     for (i = 0; i < c - 1; i++) {
1328       assert(i < pat->length(), "out of range");
1329       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1330     }
1331 
1332     int md2 = c;
1333     for (i = 0; i < c - 1; i++) {
1334       assert(i < pat->length(), "out of range");
1335       if (pat->char_at(o + i) == lastChar) {
1336         md2 = (c - 1) - i;
1337       }
1338     }
1339 
1340     result = string_indexOf(receiver, pat, o, cache, md2);
1341   }
1342 
1343   push(result);
1344   return true;
1345 }
1346 
1347 //--------------------------pop_math_arg--------------------------------
1348 // Pop a double argument to a math function from the stack
1349 // rounding it if necessary.
1350 Node * LibraryCallKit::pop_math_arg() {
1351   Node *arg = pop_pair();
1352   if( Matcher::strict_fp_requires_explicit_rounding && UseSSE<=1 )
1353     arg = _gvn.transform( new (C, 2) RoundDoubleNode(0, arg) );
1354   return arg;
1355 }
1356 
1357 //------------------------------inline_trig----------------------------------
1358 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1359 // argument reduction which will turn into a fast/slow diamond.
1360 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1361   _sp += arg_size();            // restore stack pointer
1362   Node* arg = pop_math_arg();
1363   Node* trig = NULL;
1364 
1365   switch (id) {
1366   case vmIntrinsics::_dsin:
1367     trig = _gvn.transform((Node*)new (C, 2) SinDNode(arg));
1368     break;
1369   case vmIntrinsics::_dcos:
1370     trig = _gvn.transform((Node*)new (C, 2) CosDNode(arg));
1371     break;
1372   case vmIntrinsics::_dtan:
1373     trig = _gvn.transform((Node*)new (C, 2) TanDNode(arg));
1374     break;
1375   default:
1376     assert(false, "bad intrinsic was passed in");
1377     return false;
1378   }
1379 
1380   // Rounding required?  Check for argument reduction!
1381   if( Matcher::strict_fp_requires_explicit_rounding ) {
1382 
1383     static const double     pi_4 =  0.7853981633974483;
1384     static const double neg_pi_4 = -0.7853981633974483;
1385     // pi/2 in 80-bit extended precision
1386     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1387     // -pi/2 in 80-bit extended precision
1388     // 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};
1389     // Cutoff value for using this argument reduction technique
1390     //static const double    pi_2_minus_epsilon =  1.564660403643354;
1391     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1392 
1393     // Pseudocode for sin:
1394     // if (x <= Math.PI / 4.0) {
1395     //   if (x >= -Math.PI / 4.0) return  fsin(x);
1396     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1397     // } else {
1398     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1399     // }
1400     // return StrictMath.sin(x);
1401 
1402     // Pseudocode for cos:
1403     // if (x <= Math.PI / 4.0) {
1404     //   if (x >= -Math.PI / 4.0) return  fcos(x);
1405     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1406     // } else {
1407     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1408     // }
1409     // return StrictMath.cos(x);
1410 
1411     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1412     // requires a special machine instruction to load it.  Instead we'll try
1413     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1414     // probably do the math inside the SIN encoding.
1415 
1416     // Make the merge point
1417     RegionNode *r = new (C, 3) RegionNode(3);
1418     Node *phi = new (C, 3) PhiNode(r,Type::DOUBLE);
1419 
1420     // Flatten arg so we need only 1 test
1421     Node *abs = _gvn.transform(new (C, 2) AbsDNode(arg));
1422     // Node for PI/4 constant
1423     Node *pi4 = makecon(TypeD::make(pi_4));
1424     // Check PI/4 : abs(arg)
1425     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(pi4,abs));
1426     // Check: If PI/4 < abs(arg) then go slow
1427     Node *bol = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::lt ) );
1428     // Branch either way
1429     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1430     set_control(opt_iff(r,iff));
1431 
1432     // Set fast path result
1433     phi->init_req(2,trig);
1434 
1435     // Slow path - non-blocking leaf call
1436     Node* call = NULL;
1437     switch (id) {
1438     case vmIntrinsics::_dsin:
1439       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1440                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1441                                "Sin", NULL, arg, top());
1442       break;
1443     case vmIntrinsics::_dcos:
1444       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1445                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1446                                "Cos", NULL, arg, top());
1447       break;
1448     case vmIntrinsics::_dtan:
1449       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1450                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1451                                "Tan", NULL, arg, top());
1452       break;
1453     }
1454     assert(control()->in(0) == call, "");
1455     Node* slow_result = _gvn.transform(new (C, 1) ProjNode(call,TypeFunc::Parms));
1456     r->init_req(1,control());
1457     phi->init_req(1,slow_result);
1458 
1459     // Post-merge
1460     set_control(_gvn.transform(r));
1461     record_for_igvn(r);
1462     trig = _gvn.transform(phi);
1463 
1464     C->set_has_split_ifs(true); // Has chance for split-if optimization
1465   }
1466   // Push result back on JVM stack
1467   push_pair(trig);
1468   return true;
1469 }
1470 
1471 //------------------------------inline_sqrt-------------------------------------
1472 // Inline square root instruction, if possible.
1473 bool LibraryCallKit::inline_sqrt(vmIntrinsics::ID id) {
1474   assert(id == vmIntrinsics::_dsqrt, "Not square root");
1475   _sp += arg_size();        // restore stack pointer
1476   push_pair(_gvn.transform(new (C, 2) SqrtDNode(0, pop_math_arg())));
1477   return true;
1478 }
1479 
1480 //------------------------------inline_abs-------------------------------------
1481 // Inline absolute value instruction, if possible.
1482 bool LibraryCallKit::inline_abs(vmIntrinsics::ID id) {
1483   assert(id == vmIntrinsics::_dabs, "Not absolute value");
1484   _sp += arg_size();        // restore stack pointer
1485   push_pair(_gvn.transform(new (C, 2) AbsDNode(pop_math_arg())));
1486   return true;
1487 }
1488 
1489 //------------------------------inline_exp-------------------------------------
1490 // Inline exp instructions, if possible.  The Intel hardware only misses
1491 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1492 bool LibraryCallKit::inline_exp(vmIntrinsics::ID id) {
1493   assert(id == vmIntrinsics::_dexp, "Not exp");
1494 
1495   // If this inlining ever returned NaN in the past, we do not intrinsify it
1496   // every again.  NaN results requires StrictMath.exp handling.
1497   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
1498 
1499   _sp += arg_size();        // restore stack pointer
1500   Node *x = pop_math_arg();
1501   Node *result = _gvn.transform(new (C, 2) ExpDNode(0,x));
1502 
1503   //-------------------
1504   //result=(result.isNaN())? StrictMath::exp():result;
1505   // Check: If isNaN() by checking result!=result? then go to Strict Math
1506   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
1507   // Build the boolean node
1508   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
1509 
1510   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1511     // End the current control-flow path
1512     push_pair(x);
1513     // Math.exp intrinsic returned a NaN, which requires StrictMath.exp
1514     // to handle.  Recompile without intrinsifying Math.exp
1515     uncommon_trap(Deoptimization::Reason_intrinsic,
1516                   Deoptimization::Action_make_not_entrant);
1517   }
1518 
1519   C->set_has_split_ifs(true); // Has chance for split-if optimization
1520 
1521   push_pair(result);
1522 
1523   return true;
1524 }
1525 
1526 //------------------------------inline_pow-------------------------------------
1527 // Inline power instructions, if possible.
1528 bool LibraryCallKit::inline_pow(vmIntrinsics::ID id) {
1529   assert(id == vmIntrinsics::_dpow, "Not pow");
1530 
1531   // If this inlining ever returned NaN in the past, we do not intrinsify it
1532   // every again.  NaN results requires StrictMath.pow handling.
1533   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
1534 
1535   // Do not intrinsify on older platforms which lack cmove.
1536   if (ConditionalMoveLimit == 0)  return false;
1537 
1538   // Pseudocode for pow
1539   // if (x <= 0.0) {
1540   //   if ((double)((int)y)==y) { // if y is int
1541   //     result = ((1&(int)y)==0)?-DPow(abs(x), y):DPow(abs(x), y)
1542   //   } else {
1543   //     result = NaN;
1544   //   }
1545   // } else {
1546   //   result = DPow(x,y);
1547   // }
1548   // if (result != result)?  {
1549   //   uncommon_trap();
1550   // }
1551   // return result;
1552 
1553   _sp += arg_size();        // restore stack pointer
1554   Node* y = pop_math_arg();
1555   Node* x = pop_math_arg();
1556 
1557   Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, x, y) );
1558 
1559   // Short form: if not top-level (i.e., Math.pow but inlining Math.pow
1560   // inside of something) then skip the fancy tests and just check for
1561   // NaN result.
1562   Node *result = NULL;
1563   if( jvms()->depth() >= 1 ) {
1564     result = fast_result;
1565   } else {
1566 
1567     // Set the merge point for If node with condition of (x <= 0.0)
1568     // There are four possible paths to region node and phi node
1569     RegionNode *r = new (C, 4) RegionNode(4);
1570     Node *phi = new (C, 4) PhiNode(r, Type::DOUBLE);
1571 
1572     // Build the first if node: if (x <= 0.0)
1573     // Node for 0 constant
1574     Node *zeronode = makecon(TypeD::ZERO);
1575     // Check x:0
1576     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(x, zeronode));
1577     // Check: If (x<=0) then go complex path
1578     Node *bol1 = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::le ) );
1579     // Branch either way
1580     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1581     Node *opt_test = _gvn.transform(if1);
1582     //assert( opt_test->is_If(), "Expect an IfNode");
1583     IfNode *opt_if1 = (IfNode*)opt_test;
1584     // Fast path taken; set region slot 3
1585     Node *fast_taken = _gvn.transform( new (C, 1) IfFalseNode(opt_if1) );
1586     r->init_req(3,fast_taken); // Capture fast-control
1587 
1588     // Fast path not-taken, i.e. slow path
1589     Node *complex_path = _gvn.transform( new (C, 1) IfTrueNode(opt_if1) );
1590 
1591     // Set fast path result
1592     Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, y, x) );
1593     phi->init_req(3, fast_result);
1594 
1595     // Complex path
1596     // Build the second if node (if y is int)
1597     // Node for (int)y
1598     Node *inty = _gvn.transform( new (C, 2) ConvD2INode(y));
1599     // Node for (double)((int) y)
1600     Node *doubleinty= _gvn.transform( new (C, 2) ConvI2DNode(inty));
1601     // Check (double)((int) y) : y
1602     Node *cmpinty= _gvn.transform(new (C, 3) CmpDNode(doubleinty, y));
1603     // Check if (y isn't int) then go to slow path
1604 
1605     Node *bol2 = _gvn.transform( new (C, 2) BoolNode( cmpinty, BoolTest::ne ) );
1606     // Branch either way
1607     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1608     Node *slow_path = opt_iff(r,if2); // Set region path 2
1609 
1610     // Calculate DPow(abs(x), y)*(1 & (int)y)
1611     // Node for constant 1
1612     Node *conone = intcon(1);
1613     // 1& (int)y
1614     Node *signnode= _gvn.transform( new (C, 3) AndINode(conone, inty) );
1615     // zero node
1616     Node *conzero = intcon(0);
1617     // Check (1&(int)y)==0?
1618     Node *cmpeq1 = _gvn.transform(new (C, 3) CmpINode(signnode, conzero));
1619     // Check if (1&(int)y)!=0?, if so the result is negative
1620     Node *bol3 = _gvn.transform( new (C, 2) BoolNode( cmpeq1, BoolTest::ne ) );
1621     // abs(x)
1622     Node *absx=_gvn.transform( new (C, 2) AbsDNode(x));
1623     // abs(x)^y
1624     Node *absxpowy = _gvn.transform( new (C, 3) PowDNode(0, y, absx) );
1625     // -abs(x)^y
1626     Node *negabsxpowy = _gvn.transform(new (C, 2) NegDNode (absxpowy));
1627     // (1&(int)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1628     Node *signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1629     // Set complex path fast result
1630     phi->init_req(2, signresult);
1631 
1632     static const jlong nan_bits = CONST64(0x7ff8000000000000);
1633     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
1634     r->init_req(1,slow_path);
1635     phi->init_req(1,slow_result);
1636 
1637     // Post merge
1638     set_control(_gvn.transform(r));
1639     record_for_igvn(r);
1640     result=_gvn.transform(phi);
1641   }
1642 
1643   //-------------------
1644   //result=(result.isNaN())? uncommon_trap():result;
1645   // Check: If isNaN() by checking result!=result? then go to Strict Math
1646   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
1647   // Build the boolean node
1648   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
1649 
1650   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1651     // End the current control-flow path
1652     push_pair(x);
1653     push_pair(y);
1654     // Math.pow intrinsic returned a NaN, which requires StrictMath.pow
1655     // to handle.  Recompile without intrinsifying Math.pow.
1656     uncommon_trap(Deoptimization::Reason_intrinsic,
1657                   Deoptimization::Action_make_not_entrant);
1658   }
1659 
1660   C->set_has_split_ifs(true); // Has chance for split-if optimization
1661 
1662   push_pair(result);
1663 
1664   return true;
1665 }
1666 
1667 //------------------------------inline_trans-------------------------------------
1668 // Inline transcendental instructions, if possible.  The Intel hardware gets
1669 // these right, no funny corner cases missed.
1670 bool LibraryCallKit::inline_trans(vmIntrinsics::ID id) {
1671   _sp += arg_size();        // restore stack pointer
1672   Node* arg = pop_math_arg();
1673   Node* trans = NULL;
1674 
1675   switch (id) {
1676   case vmIntrinsics::_dlog:
1677     trans = _gvn.transform((Node*)new (C, 2) LogDNode(arg));
1678     break;
1679   case vmIntrinsics::_dlog10:
1680     trans = _gvn.transform((Node*)new (C, 2) Log10DNode(arg));
1681     break;
1682   default:
1683     assert(false, "bad intrinsic was passed in");
1684     return false;
1685   }
1686 
1687   // Push result back on JVM stack
1688   push_pair(trans);
1689   return true;
1690 }
1691 
1692 //------------------------------runtime_math-----------------------------
1693 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1694   Node* a = NULL;
1695   Node* b = NULL;
1696 
1697   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1698          "must be (DD)D or (D)D type");
1699 
1700   // Inputs
1701   _sp += arg_size();        // restore stack pointer
1702   if (call_type == OptoRuntime::Math_DD_D_Type()) {
1703     b = pop_math_arg();
1704   }
1705   a = pop_math_arg();
1706 
1707   const TypePtr* no_memory_effects = NULL;
1708   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1709                                  no_memory_effects,
1710                                  a, top(), b, b ? top() : NULL);
1711   Node* value = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+0));
1712 #ifdef ASSERT
1713   Node* value_top = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+1));
1714   assert(value_top == top(), "second value must be top");
1715 #endif
1716 
1717   push_pair(value);
1718   return true;
1719 }
1720 
1721 //------------------------------inline_math_native-----------------------------
1722 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1723   switch (id) {
1724     // These intrinsics are not properly supported on all hardware
1725   case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :
1726     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1727   case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :
1728     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1729   case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :
1730     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1731 
1732   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD) ? inline_trans(id) :
1733     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1734   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_trans(id) :
1735     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1736 
1737     // These intrinsics are supported on all hardware
1738   case vmIntrinsics::_dsqrt: return Matcher::has_match_rule(Op_SqrtD) ? inline_sqrt(id) : false;
1739   case vmIntrinsics::_dabs:  return Matcher::has_match_rule(Op_AbsD)  ? inline_abs(id)  : false;
1740 
1741   case vmIntrinsics::_dexp:  return
1742     Matcher::has_match_rule(Op_ExpD) ? inline_exp(id) :
1743     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1744   case vmIntrinsics::_dpow:  return
1745     Matcher::has_match_rule(Op_PowD) ? inline_pow(id) :
1746     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
1747 
1748    // These intrinsics are not yet correctly implemented
1749   case vmIntrinsics::_datan2:
1750     return false;
1751 
1752   default:
1753     ShouldNotReachHere();
1754     return false;
1755   }
1756 }
1757 
1758 static bool is_simple_name(Node* n) {
1759   return (n->req() == 1         // constant
1760           || (n->is_Type() && n->as_Type()->type()->singleton())
1761           || n->is_Proj()       // parameter or return value
1762           || n->is_Phi()        // local of some sort
1763           );
1764 }
1765 
1766 //----------------------------inline_min_max-----------------------------------
1767 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1768   push(generate_min_max(id, argument(0), argument(1)));
1769 
1770   return true;
1771 }
1772 
1773 Node*
1774 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1775   // These are the candidate return value:
1776   Node* xvalue = x0;
1777   Node* yvalue = y0;
1778 
1779   if (xvalue == yvalue) {
1780     return xvalue;
1781   }
1782 
1783   bool want_max = (id == vmIntrinsics::_max);
1784 
1785   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1786   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1787   if (txvalue == NULL || tyvalue == NULL)  return top();
1788   // This is not really necessary, but it is consistent with a
1789   // hypothetical MaxINode::Value method:
1790   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1791 
1792   // %%% This folding logic should (ideally) be in a different place.
1793   // Some should be inside IfNode, and there to be a more reliable
1794   // transformation of ?: style patterns into cmoves.  We also want
1795   // more powerful optimizations around cmove and min/max.
1796 
1797   // Try to find a dominating comparison of these guys.
1798   // It can simplify the index computation for Arrays.copyOf
1799   // and similar uses of System.arraycopy.
1800   // First, compute the normalized version of CmpI(x, y).
1801   int   cmp_op = Op_CmpI;
1802   Node* xkey = xvalue;
1803   Node* ykey = yvalue;
1804   Node* ideal_cmpxy = _gvn.transform( new(C, 3) CmpINode(xkey, ykey) );
1805   if (ideal_cmpxy->is_Cmp()) {
1806     // E.g., if we have CmpI(length - offset, count),
1807     // it might idealize to CmpI(length, count + offset)
1808     cmp_op = ideal_cmpxy->Opcode();
1809     xkey = ideal_cmpxy->in(1);
1810     ykey = ideal_cmpxy->in(2);
1811   }
1812 
1813   // Start by locating any relevant comparisons.
1814   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
1815   Node* cmpxy = NULL;
1816   Node* cmpyx = NULL;
1817   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
1818     Node* cmp = start_from->fast_out(k);
1819     if (cmp->outcnt() > 0 &&            // must have prior uses
1820         cmp->in(0) == NULL &&           // must be context-independent
1821         cmp->Opcode() == cmp_op) {      // right kind of compare
1822       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
1823       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
1824     }
1825   }
1826 
1827   const int NCMPS = 2;
1828   Node* cmps[NCMPS] = { cmpxy, cmpyx };
1829   int cmpn;
1830   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1831     if (cmps[cmpn] != NULL)  break;     // find a result
1832   }
1833   if (cmpn < NCMPS) {
1834     // Look for a dominating test that tells us the min and max.
1835     int depth = 0;                // Limit search depth for speed
1836     Node* dom = control();
1837     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
1838       if (++depth >= 100)  break;
1839       Node* ifproj = dom;
1840       if (!ifproj->is_Proj())  continue;
1841       Node* iff = ifproj->in(0);
1842       if (!iff->is_If())  continue;
1843       Node* bol = iff->in(1);
1844       if (!bol->is_Bool())  continue;
1845       Node* cmp = bol->in(1);
1846       if (cmp == NULL)  continue;
1847       for (cmpn = 0; cmpn < NCMPS; cmpn++)
1848         if (cmps[cmpn] == cmp)  break;
1849       if (cmpn == NCMPS)  continue;
1850       BoolTest::mask btest = bol->as_Bool()->_test._test;
1851       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
1852       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
1853       // At this point, we know that 'x btest y' is true.
1854       switch (btest) {
1855       case BoolTest::eq:
1856         // They are proven equal, so we can collapse the min/max.
1857         // Either value is the answer.  Choose the simpler.
1858         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
1859           return yvalue;
1860         return xvalue;
1861       case BoolTest::lt:          // x < y
1862       case BoolTest::le:          // x <= y
1863         return (want_max ? yvalue : xvalue);
1864       case BoolTest::gt:          // x > y
1865       case BoolTest::ge:          // x >= y
1866         return (want_max ? xvalue : yvalue);
1867       }
1868     }
1869   }
1870 
1871   // We failed to find a dominating test.
1872   // Let's pick a test that might GVN with prior tests.
1873   Node*          best_bol   = NULL;
1874   BoolTest::mask best_btest = BoolTest::illegal;
1875   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1876     Node* cmp = cmps[cmpn];
1877     if (cmp == NULL)  continue;
1878     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
1879       Node* bol = cmp->fast_out(j);
1880       if (!bol->is_Bool())  continue;
1881       BoolTest::mask btest = bol->as_Bool()->_test._test;
1882       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
1883       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
1884       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
1885         best_bol   = bol->as_Bool();
1886         best_btest = btest;
1887       }
1888     }
1889   }
1890 
1891   Node* answer_if_true  = NULL;
1892   Node* answer_if_false = NULL;
1893   switch (best_btest) {
1894   default:
1895     if (cmpxy == NULL)
1896       cmpxy = ideal_cmpxy;
1897     best_bol = _gvn.transform( new(C, 2) BoolNode(cmpxy, BoolTest::lt) );
1898     // and fall through:
1899   case BoolTest::lt:          // x < y
1900   case BoolTest::le:          // x <= y
1901     answer_if_true  = (want_max ? yvalue : xvalue);
1902     answer_if_false = (want_max ? xvalue : yvalue);
1903     break;
1904   case BoolTest::gt:          // x > y
1905   case BoolTest::ge:          // x >= y
1906     answer_if_true  = (want_max ? xvalue : yvalue);
1907     answer_if_false = (want_max ? yvalue : xvalue);
1908     break;
1909   }
1910 
1911   jint hi, lo;
1912   if (want_max) {
1913     // We can sharpen the minimum.
1914     hi = MAX2(txvalue->_hi, tyvalue->_hi);
1915     lo = MAX2(txvalue->_lo, tyvalue->_lo);
1916   } else {
1917     // We can sharpen the maximum.
1918     hi = MIN2(txvalue->_hi, tyvalue->_hi);
1919     lo = MIN2(txvalue->_lo, tyvalue->_lo);
1920   }
1921 
1922   // Use a flow-free graph structure, to avoid creating excess control edges
1923   // which could hinder other optimizations.
1924   // Since Math.min/max is often used with arraycopy, we want
1925   // tightly_coupled_allocation to be able to see beyond min/max expressions.
1926   Node* cmov = CMoveNode::make(C, NULL, best_bol,
1927                                answer_if_false, answer_if_true,
1928                                TypeInt::make(lo, hi, widen));
1929 
1930   return _gvn.transform(cmov);
1931 
1932   /*
1933   // This is not as desirable as it may seem, since Min and Max
1934   // nodes do not have a full set of optimizations.
1935   // And they would interfere, anyway, with 'if' optimizations
1936   // and with CMoveI canonical forms.
1937   switch (id) {
1938   case vmIntrinsics::_min:
1939     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
1940   case vmIntrinsics::_max:
1941     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
1942   default:
1943     ShouldNotReachHere();
1944   }
1945   */
1946 }
1947 
1948 inline int
1949 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
1950   const TypePtr* base_type = TypePtr::NULL_PTR;
1951   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
1952   if (base_type == NULL) {
1953     // Unknown type.
1954     return Type::AnyPtr;
1955   } else if (base_type == TypePtr::NULL_PTR) {
1956     // Since this is a NULL+long form, we have to switch to a rawptr.
1957     base   = _gvn.transform( new (C, 2) CastX2PNode(offset) );
1958     offset = MakeConX(0);
1959     return Type::RawPtr;
1960   } else if (base_type->base() == Type::RawPtr) {
1961     return Type::RawPtr;
1962   } else if (base_type->isa_oopptr()) {
1963     // Base is never null => always a heap address.
1964     if (base_type->ptr() == TypePtr::NotNull) {
1965       return Type::OopPtr;
1966     }
1967     // Offset is small => always a heap address.
1968     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
1969     if (offset_type != NULL &&
1970         base_type->offset() == 0 &&     // (should always be?)
1971         offset_type->_lo >= 0 &&
1972         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
1973       return Type::OopPtr;
1974     }
1975     // Otherwise, it might either be oop+off or NULL+addr.
1976     return Type::AnyPtr;
1977   } else {
1978     // No information:
1979     return Type::AnyPtr;
1980   }
1981 }
1982 
1983 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
1984   int kind = classify_unsafe_addr(base, offset);
1985   if (kind == Type::RawPtr) {
1986     return basic_plus_adr(top(), base, offset);
1987   } else {
1988     return basic_plus_adr(base, offset);
1989   }
1990 }
1991 
1992 //-------------------inline_numberOfLeadingZeros_int/long-----------------------
1993 // inline int Integer.numberOfLeadingZeros(int)
1994 // inline int Long.numberOfLeadingZeros(long)
1995 bool LibraryCallKit::inline_numberOfLeadingZeros(vmIntrinsics::ID id) {
1996   assert(id == vmIntrinsics::_numberOfLeadingZeros_i || id == vmIntrinsics::_numberOfLeadingZeros_l, "not numberOfLeadingZeros");
1997   if (id == vmIntrinsics::_numberOfLeadingZeros_i && !Matcher::match_rule_supported(Op_CountLeadingZerosI)) return false;
1998   if (id == vmIntrinsics::_numberOfLeadingZeros_l && !Matcher::match_rule_supported(Op_CountLeadingZerosL)) return false;
1999   _sp += arg_size();  // restore stack pointer
2000   switch (id) {
2001   case vmIntrinsics::_numberOfLeadingZeros_i:
2002     push(_gvn.transform(new (C, 2) CountLeadingZerosINode(pop())));
2003     break;
2004   case vmIntrinsics::_numberOfLeadingZeros_l:
2005     push(_gvn.transform(new (C, 2) CountLeadingZerosLNode(pop_pair())));
2006     break;
2007   default:
2008     ShouldNotReachHere();
2009   }
2010   return true;
2011 }
2012 
2013 //-------------------inline_numberOfTrailingZeros_int/long----------------------
2014 // inline int Integer.numberOfTrailingZeros(int)
2015 // inline int Long.numberOfTrailingZeros(long)
2016 bool LibraryCallKit::inline_numberOfTrailingZeros(vmIntrinsics::ID id) {
2017   assert(id == vmIntrinsics::_numberOfTrailingZeros_i || id == vmIntrinsics::_numberOfTrailingZeros_l, "not numberOfTrailingZeros");
2018   if (id == vmIntrinsics::_numberOfTrailingZeros_i && !Matcher::match_rule_supported(Op_CountTrailingZerosI)) return false;
2019   if (id == vmIntrinsics::_numberOfTrailingZeros_l && !Matcher::match_rule_supported(Op_CountTrailingZerosL)) return false;
2020   _sp += arg_size();  // restore stack pointer
2021   switch (id) {
2022   case vmIntrinsics::_numberOfTrailingZeros_i:
2023     push(_gvn.transform(new (C, 2) CountTrailingZerosINode(pop())));
2024     break;
2025   case vmIntrinsics::_numberOfTrailingZeros_l:
2026     push(_gvn.transform(new (C, 2) CountTrailingZerosLNode(pop_pair())));
2027     break;
2028   default:
2029     ShouldNotReachHere();
2030   }
2031   return true;
2032 }
2033 
2034 //----------------------------inline_bitCount_int/long-----------------------
2035 // inline int Integer.bitCount(int)
2036 // inline int Long.bitCount(long)
2037 bool LibraryCallKit::inline_bitCount(vmIntrinsics::ID id) {
2038   assert(id == vmIntrinsics::_bitCount_i || id == vmIntrinsics::_bitCount_l, "not bitCount");
2039   if (id == vmIntrinsics::_bitCount_i && !Matcher::has_match_rule(Op_PopCountI)) return false;
2040   if (id == vmIntrinsics::_bitCount_l && !Matcher::has_match_rule(Op_PopCountL)) return false;
2041   _sp += arg_size();  // restore stack pointer
2042   switch (id) {
2043   case vmIntrinsics::_bitCount_i:
2044     push(_gvn.transform(new (C, 2) PopCountINode(pop())));
2045     break;
2046   case vmIntrinsics::_bitCount_l:
2047     push(_gvn.transform(new (C, 2) PopCountLNode(pop_pair())));
2048     break;
2049   default:
2050     ShouldNotReachHere();
2051   }
2052   return true;
2053 }
2054 
2055 //----------------------------inline_reverseBytes_int/long/char/short-------------------
2056 // inline Integer.reverseBytes(int)
2057 // inline Long.reverseBytes(long)
2058 // inline Character.reverseBytes(char)
2059 // inline Short.reverseBytes(short)
2060 bool LibraryCallKit::inline_reverseBytes(vmIntrinsics::ID id) {
2061   assert(id == vmIntrinsics::_reverseBytes_i || id == vmIntrinsics::_reverseBytes_l ||
2062          id == vmIntrinsics::_reverseBytes_c || id == vmIntrinsics::_reverseBytes_s,
2063          "not reverse Bytes");
2064   if (id == vmIntrinsics::_reverseBytes_i && !Matcher::has_match_rule(Op_ReverseBytesI))  return false;
2065   if (id == vmIntrinsics::_reverseBytes_l && !Matcher::has_match_rule(Op_ReverseBytesL))  return false;
2066   if (id == vmIntrinsics::_reverseBytes_c && !Matcher::has_match_rule(Op_ReverseBytesUS)) return false;
2067   if (id == vmIntrinsics::_reverseBytes_s && !Matcher::has_match_rule(Op_ReverseBytesS))  return false;
2068   _sp += arg_size();        // restore stack pointer
2069   switch (id) {
2070   case vmIntrinsics::_reverseBytes_i:
2071     push(_gvn.transform(new (C, 2) ReverseBytesINode(0, pop())));
2072     break;
2073   case vmIntrinsics::_reverseBytes_l:
2074     push_pair(_gvn.transform(new (C, 2) ReverseBytesLNode(0, pop_pair())));
2075     break;
2076   case vmIntrinsics::_reverseBytes_c:
2077     push(_gvn.transform(new (C, 2) ReverseBytesUSNode(0, pop())));
2078     break;
2079   case vmIntrinsics::_reverseBytes_s:
2080     push(_gvn.transform(new (C, 2) ReverseBytesSNode(0, pop())));
2081     break;
2082   default:
2083     ;
2084   }
2085   return true;
2086 }
2087 
2088 //----------------------------inline_unsafe_access----------------------------
2089 
2090 const static BasicType T_ADDRESS_HOLDER = T_LONG;
2091 
2092 // Helper that guards and inserts a G1 pre-barrier.
2093 void LibraryCallKit::insert_g1_pre_barrier(Node* base_oop, Node* offset, Node* pre_val) {
2094   assert(UseG1GC, "should not call this otherwise");
2095 
2096   // We could be accessing the referent field of a reference object. If so, when G1
2097   // is enabled, we need to log the value in the referent field in an SATB buffer.
2098   // This routine performs some compile time filters and generates suitable
2099   // runtime filters that guard the pre-barrier code.
2100 
2101   // Some compile time checks.
2102 
2103   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2104   const TypeX* otype = offset->find_intptr_t_type();
2105   if (otype != NULL && otype->is_con() &&
2106       otype->get_con() != java_lang_ref_Reference::referent_offset) {
2107     // Constant offset but not the reference_offset so just return
2108     return;
2109   }
2110 
2111   // We only need to generate the runtime guards for instances.
2112   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2113   if (btype != NULL) {
2114     if (btype->isa_aryptr()) {
2115       // Array type so nothing to do
2116       return;
2117     }
2118 
2119     const TypeInstPtr* itype = btype->isa_instptr();
2120     if (itype != NULL) {
2121       // Can the klass of base_oop be statically determined
2122       // to be _not_ a sub-class of Reference?
2123       ciKlass* klass = itype->klass();
2124       if (klass->is_subtype_of(env()->Reference_klass()) &&
2125           !env()->Reference_klass()->is_subtype_of(klass)) {
2126         return;
2127       }
2128     }
2129   }
2130 
2131   // The compile time filters did not reject base_oop/offset so
2132   // we need to generate the following runtime filters
2133   //
2134   // if (offset == java_lang_ref_Reference::_reference_offset) {
2135   //   if (base != null) {
2136   //     if (instance_of(base, java.lang.ref.Reference)) {
2137   //       pre_barrier(_, pre_val, ...);
2138   //     }
2139   //   }
2140   // }
2141 
2142   float likely  = PROB_LIKELY(0.999);
2143   float unlikely  = PROB_UNLIKELY(0.999);
2144 
2145   IdealKit ideal(this);
2146 #define __ ideal.
2147 
2148   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2149 
2150   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2151     __ if_then(base_oop, BoolTest::ne, null(), likely); {
2152 
2153       // Update graphKit memory and control from IdealKit.
2154       sync_kit(ideal);
2155 
2156       Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2157       Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2158 
2159       // Update IdealKit memory and control from graphKit.
2160       __ sync_kit(this);
2161 
2162       Node* one = __ ConI(1);
2163 
2164       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2165 
2166         // Update graphKit from IdeakKit.
2167         sync_kit(ideal);
2168 
2169         // Use the pre-barrier to record the value in the referent field
2170         pre_barrier(false /* do_load */,
2171                     __ ctrl(),
2172                     NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2173                     pre_val /* pre_val */,
2174                     T_OBJECT);
2175 
2176         // Update IdealKit from graphKit.
2177         __ sync_kit(this);
2178 
2179       } __ end_if(); // _ref_type != ref_none
2180     } __ end_if(); // base  != NULL
2181   } __ end_if(); // offset == referent_offset
2182 
2183   // Final sync IdealKit and GraphKit.
2184   final_sync(ideal);
2185 #undef __
2186 }
2187 
2188 
2189 // Interpret Unsafe.fieldOffset cookies correctly:
2190 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2191 
2192 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2193   if (callee()->is_static())  return false;  // caller must have the capability!
2194 
2195 #ifndef PRODUCT
2196   {
2197     ResourceMark rm;
2198     // Check the signatures.
2199     ciSignature* sig = signature();
2200 #ifdef ASSERT
2201     if (!is_store) {
2202       // Object getObject(Object base, int/long offset), etc.
2203       BasicType rtype = sig->return_type()->basic_type();
2204       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2205           rtype = T_ADDRESS;  // it is really a C void*
2206       assert(rtype == type, "getter must return the expected value");
2207       if (!is_native_ptr) {
2208         assert(sig->count() == 2, "oop getter has 2 arguments");
2209         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2210         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2211       } else {
2212         assert(sig->count() == 1, "native getter has 1 argument");
2213         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2214       }
2215     } else {
2216       // void putObject(Object base, int/long offset, Object x), etc.
2217       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2218       if (!is_native_ptr) {
2219         assert(sig->count() == 3, "oop putter has 3 arguments");
2220         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2221         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2222       } else {
2223         assert(sig->count() == 2, "native putter has 2 arguments");
2224         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2225       }
2226       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2227       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2228         vtype = T_ADDRESS;  // it is really a C void*
2229       assert(vtype == type, "putter must accept the expected value");
2230     }
2231 #endif // ASSERT
2232  }
2233 #endif //PRODUCT
2234 
2235   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2236 
2237   int type_words = type2size[ (type == T_ADDRESS) ? T_LONG : type ];
2238 
2239   // Argument words:  "this" plus (oop/offset) or (lo/hi) args plus maybe 1 or 2 value words
2240   int nargs = 1 + (is_native_ptr ? 2 : 3) + (is_store ? type_words : 0);
2241 
2242   debug_only(int saved_sp = _sp);
2243   _sp += nargs;
2244 
2245   Node* val;
2246   debug_only(val = (Node*)(uintptr_t)-1);
2247 
2248 
2249   if (is_store) {
2250     // Get the value being stored.  (Pop it first; it was pushed last.)
2251     switch (type) {
2252     case T_DOUBLE:
2253     case T_LONG:
2254     case T_ADDRESS:
2255       val = pop_pair();
2256       break;
2257     default:
2258       val = pop();
2259     }
2260   }
2261 
2262   // Build address expression.  See the code in inline_unsafe_prefetch.
2263   Node *adr;
2264   Node *heap_base_oop = top();
2265   Node* offset = top();
2266 
2267   if (!is_native_ptr) {
2268     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2269     offset = pop_pair();
2270     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2271     Node* base   = pop();
2272     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2273     // to be plain byte offsets, which are also the same as those accepted
2274     // by oopDesc::field_base.
2275     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2276            "fieldOffset must be byte-scaled");
2277     // 32-bit machines ignore the high half!
2278     offset = ConvL2X(offset);
2279     adr = make_unsafe_address(base, offset);
2280     heap_base_oop = base;
2281   } else {
2282     Node* ptr = pop_pair();
2283     // Adjust Java long to machine word:
2284     ptr = ConvL2X(ptr);
2285     adr = make_unsafe_address(NULL, ptr);
2286   }
2287 
2288   // Pop receiver last:  it was pushed first.
2289   Node *receiver = pop();
2290 
2291   assert(saved_sp == _sp, "must have correct argument count");
2292 
2293   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2294 
2295   // First guess at the value type.
2296   const Type *value_type = Type::get_const_basic_type(type);
2297 
2298   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2299   // there was not enough information to nail it down.
2300   Compile::AliasType* alias_type = C->alias_type(adr_type);
2301   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2302 
2303   // We will need memory barriers unless we can determine a unique
2304   // alias category for this reference.  (Note:  If for some reason
2305   // the barriers get omitted and the unsafe reference begins to "pollute"
2306   // the alias analysis of the rest of the graph, either Compile::can_alias
2307   // or Compile::must_alias will throw a diagnostic assert.)
2308   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2309 
2310   // If we are reading the value of the referent field of a Reference
2311   // object (either by using Unsafe directly or through reflection)
2312   // then, if G1 is enabled, we need to record the referent in an
2313   // SATB log buffer using the pre-barrier mechanism.
2314   bool need_read_barrier = UseG1GC && !is_native_ptr && !is_store &&
2315                            offset != top() && heap_base_oop != top();
2316 
2317   if (!is_store && type == T_OBJECT) {
2318     // Attempt to infer a sharper value type from the offset and base type.
2319     ciKlass* sharpened_klass = NULL;
2320 
2321     // See if it is an instance field, with an object type.
2322     if (alias_type->field() != NULL) {
2323       assert(!is_native_ptr, "native pointer op cannot use a java address");
2324       if (alias_type->field()->type()->is_klass()) {
2325         sharpened_klass = alias_type->field()->type()->as_klass();
2326       }
2327     }
2328 
2329     // See if it is a narrow oop array.
2330     if (adr_type->isa_aryptr()) {
2331       if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2332         const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2333         if (elem_type != NULL) {
2334           sharpened_klass = elem_type->klass();
2335         }
2336       }
2337     }
2338 
2339     if (sharpened_klass != NULL) {
2340       const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2341 
2342       // Sharpen the value type.
2343       value_type = tjp;
2344 
2345 #ifndef PRODUCT
2346       if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
2347         tty->print("  from base type:  ");   adr_type->dump();
2348         tty->print("  sharpened value: "); value_type->dump();
2349       }
2350 #endif
2351     }
2352   }
2353 
2354   // Null check on self without removing any arguments.  The argument
2355   // null check technically happens in the wrong place, which can lead to
2356   // invalid stack traces when the primitive is inlined into a method
2357   // which handles NullPointerExceptions.
2358   _sp += nargs;
2359   do_null_check(receiver, T_OBJECT);
2360   _sp -= nargs;
2361   if (stopped()) {
2362     return true;
2363   }
2364   // Heap pointers get a null-check from the interpreter,
2365   // as a courtesy.  However, this is not guaranteed by Unsafe,
2366   // and it is not possible to fully distinguish unintended nulls
2367   // from intended ones in this API.
2368 
2369   if (is_volatile) {
2370     // We need to emit leading and trailing CPU membars (see below) in
2371     // addition to memory membars when is_volatile. This is a little
2372     // too strong, but avoids the need to insert per-alias-type
2373     // volatile membars (for stores; compare Parse::do_put_xxx), which
2374     // we cannot do effectively here because we probably only have a
2375     // rough approximation of type.
2376     need_mem_bar = true;
2377     // For Stores, place a memory ordering barrier now.
2378     if (is_store)
2379       insert_mem_bar(Op_MemBarRelease);
2380   }
2381 
2382   // Memory barrier to prevent normal and 'unsafe' accesses from
2383   // bypassing each other.  Happens after null checks, so the
2384   // exception paths do not take memory state from the memory barrier,
2385   // so there's no problems making a strong assert about mixing users
2386   // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
2387   // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
2388   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2389 
2390   if (!is_store) {
2391     Node* p = make_load(control(), adr, value_type, type, adr_type, is_volatile);
2392     // load value and push onto stack
2393     switch (type) {
2394     case T_BOOLEAN:
2395     case T_CHAR:
2396     case T_BYTE:
2397     case T_SHORT:
2398     case T_INT:
2399     case T_FLOAT:
2400       push(p);
2401       break;
2402     case T_OBJECT:
2403       if (need_read_barrier) {
2404         insert_g1_pre_barrier(heap_base_oop, offset, p);
2405       }
2406       push(p);
2407       break;
2408     case T_ADDRESS:
2409       // Cast to an int type.
2410       p = _gvn.transform( new (C, 2) CastP2XNode(NULL,p) );
2411       p = ConvX2L(p);
2412       push_pair(p);
2413       break;
2414     case T_DOUBLE:
2415     case T_LONG:
2416       push_pair( p );
2417       break;
2418     default: ShouldNotReachHere();
2419     }
2420   } else {
2421     // place effect of store into memory
2422     switch (type) {
2423     case T_DOUBLE:
2424       val = dstore_rounding(val);
2425       break;
2426     case T_ADDRESS:
2427       // Repackage the long as a pointer.
2428       val = ConvL2X(val);
2429       val = _gvn.transform( new (C, 2) CastX2PNode(val) );
2430       break;
2431     }
2432 
2433     if (type != T_OBJECT ) {
2434       (void) store_to_memory(control(), adr, val, type, adr_type, is_volatile);
2435     } else {
2436       // Possibly an oop being stored to Java heap or native memory
2437       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2438         // oop to Java heap.
2439         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2440       } else {
2441         // We can't tell at compile time if we are storing in the Java heap or outside
2442         // of it. So we need to emit code to conditionally do the proper type of
2443         // store.
2444 
2445         IdealKit ideal(this);
2446 #define __ ideal.
2447         // QQQ who knows what probability is here??
2448         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2449           // Sync IdealKit and graphKit.
2450           sync_kit(ideal);
2451           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2452           // Update IdealKit memory.
2453           __ sync_kit(this);
2454         } __ else_(); {
2455           __ store(__ ctrl(), adr, val, type, alias_type->index(), is_volatile);
2456         } __ end_if();
2457         // Final sync IdealKit and GraphKit.
2458         final_sync(ideal);
2459 #undef __
2460       }
2461     }
2462   }
2463 
2464   if (is_volatile) {
2465     if (!is_store)
2466       insert_mem_bar(Op_MemBarAcquire);
2467     else
2468       insert_mem_bar(Op_MemBarVolatile);
2469   }
2470 
2471   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2472 
2473   return true;
2474 }
2475 
2476 //----------------------------inline_unsafe_prefetch----------------------------
2477 
2478 bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
2479 #ifndef PRODUCT
2480   {
2481     ResourceMark rm;
2482     // Check the signatures.
2483     ciSignature* sig = signature();
2484 #ifdef ASSERT
2485     // Object getObject(Object base, int/long offset), etc.
2486     BasicType rtype = sig->return_type()->basic_type();
2487     if (!is_native_ptr) {
2488       assert(sig->count() == 2, "oop prefetch has 2 arguments");
2489       assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
2490       assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
2491     } else {
2492       assert(sig->count() == 1, "native prefetch has 1 argument");
2493       assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
2494     }
2495 #endif // ASSERT
2496   }
2497 #endif // !PRODUCT
2498 
2499   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2500 
2501   // Argument words:  "this" if not static, plus (oop/offset) or (lo/hi) args
2502   int nargs = (is_static ? 0 : 1) + (is_native_ptr ? 2 : 3);
2503 
2504   debug_only(int saved_sp = _sp);
2505   _sp += nargs;
2506 
2507   // Build address expression.  See the code in inline_unsafe_access.
2508   Node *adr;
2509   if (!is_native_ptr) {
2510     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2511     Node* offset = pop_pair();
2512     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2513     Node* base   = pop();
2514     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2515     // to be plain byte offsets, which are also the same as those accepted
2516     // by oopDesc::field_base.
2517     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2518            "fieldOffset must be byte-scaled");
2519     // 32-bit machines ignore the high half!
2520     offset = ConvL2X(offset);
2521     adr = make_unsafe_address(base, offset);
2522   } else {
2523     Node* ptr = pop_pair();
2524     // Adjust Java long to machine word:
2525     ptr = ConvL2X(ptr);
2526     adr = make_unsafe_address(NULL, ptr);
2527   }
2528 
2529   if (is_static) {
2530     assert(saved_sp == _sp, "must have correct argument count");
2531   } else {
2532     // Pop receiver last:  it was pushed first.
2533     Node *receiver = pop();
2534     assert(saved_sp == _sp, "must have correct argument count");
2535 
2536     // Null check on self without removing any arguments.  The argument
2537     // null check technically happens in the wrong place, which can lead to
2538     // invalid stack traces when the primitive is inlined into a method
2539     // which handles NullPointerExceptions.
2540     _sp += nargs;
2541     do_null_check(receiver, T_OBJECT);
2542     _sp -= nargs;
2543     if (stopped()) {
2544       return true;
2545     }
2546   }
2547 
2548   // Generate the read or write prefetch
2549   Node *prefetch;
2550   if (is_store) {
2551     prefetch = new (C, 3) PrefetchWriteNode(i_o(), adr);
2552   } else {
2553     prefetch = new (C, 3) PrefetchReadNode(i_o(), adr);
2554   }
2555   prefetch->init_req(0, control());
2556   set_i_o(_gvn.transform(prefetch));
2557 
2558   return true;
2559 }
2560 
2561 //----------------------------inline_unsafe_CAS----------------------------
2562 
2563 bool LibraryCallKit::inline_unsafe_CAS(BasicType type) {
2564   // This basic scheme here is the same as inline_unsafe_access, but
2565   // differs in enough details that combining them would make the code
2566   // overly confusing.  (This is a true fact! I originally combined
2567   // them, but even I was confused by it!) As much code/comments as
2568   // possible are retained from inline_unsafe_access though to make
2569   // the correspondences clearer. - dl
2570 
2571   if (callee()->is_static())  return false;  // caller must have the capability!
2572 
2573 #ifndef PRODUCT
2574   {
2575     ResourceMark rm;
2576     // Check the signatures.
2577     ciSignature* sig = signature();
2578 #ifdef ASSERT
2579     BasicType rtype = sig->return_type()->basic_type();
2580     assert(rtype == T_BOOLEAN, "CAS must return boolean");
2581     assert(sig->count() == 4, "CAS has 4 arguments");
2582     assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2583     assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2584 #endif // ASSERT
2585   }
2586 #endif //PRODUCT
2587 
2588   // number of stack slots per value argument (1 or 2)
2589   int type_words = type2size[type];
2590 
2591   // Cannot inline wide CAS on machines that don't support it natively
2592   if (type2aelembytes(type) > BytesPerInt && !VM_Version::supports_cx8())
2593     return false;
2594 
2595   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2596 
2597   // Argument words:  "this" plus oop plus offset plus oldvalue plus newvalue;
2598   int nargs = 1 + 1 + 2  + type_words + type_words;
2599 
2600   // pop arguments: newval, oldval, offset, base, and receiver
2601   debug_only(int saved_sp = _sp);
2602   _sp += nargs;
2603   Node* newval   = (type_words == 1) ? pop() : pop_pair();
2604   Node* oldval   = (type_words == 1) ? pop() : pop_pair();
2605   Node *offset   = pop_pair();
2606   Node *base     = pop();
2607   Node *receiver = pop();
2608   assert(saved_sp == _sp, "must have correct argument count");
2609 
2610   //  Null check receiver.
2611   _sp += nargs;
2612   do_null_check(receiver, T_OBJECT);
2613   _sp -= nargs;
2614   if (stopped()) {
2615     return true;
2616   }
2617 
2618   // Build field offset expression.
2619   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2620   // to be plain byte offsets, which are also the same as those accepted
2621   // by oopDesc::field_base.
2622   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2623   // 32-bit machines ignore the high half of long offsets
2624   offset = ConvL2X(offset);
2625   Node* adr = make_unsafe_address(base, offset);
2626   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2627 
2628   // (Unlike inline_unsafe_access, there seems no point in trying
2629   // to refine types. Just use the coarse types here.
2630   const Type *value_type = Type::get_const_basic_type(type);
2631   Compile::AliasType* alias_type = C->alias_type(adr_type);
2632   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2633   int alias_idx = C->get_alias_index(adr_type);
2634 
2635   // Memory-model-wise, a CAS acts like a little synchronized block,
2636   // so needs barriers on each side.  These don't translate into
2637   // actual barriers on most machines, but we still need rest of
2638   // compiler to respect ordering.
2639 
2640   insert_mem_bar(Op_MemBarRelease);
2641   insert_mem_bar(Op_MemBarCPUOrder);
2642 
2643   // 4984716: MemBars must be inserted before this
2644   //          memory node in order to avoid a false
2645   //          dependency which will confuse the scheduler.
2646   Node *mem = memory(alias_idx);
2647 
2648   // For now, we handle only those cases that actually exist: ints,
2649   // longs, and Object. Adding others should be straightforward.
2650   Node* cas;
2651   switch(type) {
2652   case T_INT:
2653     cas = _gvn.transform(new (C, 5) CompareAndSwapINode(control(), mem, adr, newval, oldval));
2654     break;
2655   case T_LONG:
2656     cas = _gvn.transform(new (C, 5) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2657     break;
2658   case T_OBJECT:
2659     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2660     // could be delayed during Parse (for example, in adjust_map_after_if()).
2661     // Execute transformation here to avoid barrier generation in such case.
2662     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2663       newval = _gvn.makecon(TypePtr::NULL_PTR);
2664 
2665     // Reference stores need a store barrier.
2666     // (They don't if CAS fails, but it isn't worth checking.)
2667     pre_barrier(true /* do_load*/,
2668                 control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2669                 NULL /* pre_val*/,
2670                 T_OBJECT);
2671 #ifdef _LP64
2672     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2673       Node *newval_enc = _gvn.transform(new (C, 2) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2674       Node *oldval_enc = _gvn.transform(new (C, 2) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2675       cas = _gvn.transform(new (C, 5) CompareAndSwapNNode(control(), mem, adr,
2676                                                           newval_enc, oldval_enc));
2677     } else
2678 #endif
2679     {
2680       cas = _gvn.transform(new (C, 5) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
2681     }
2682     post_barrier(control(), cas, base, adr, alias_idx, newval, T_OBJECT, true);
2683     break;
2684   default:
2685     ShouldNotReachHere();
2686     break;
2687   }
2688 
2689   // SCMemProjNodes represent the memory state of CAS. Their main
2690   // role is to prevent CAS nodes from being optimized away when their
2691   // results aren't used.
2692   Node* proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
2693   set_memory(proj, alias_idx);
2694 
2695   // Add the trailing membar surrounding the access
2696   insert_mem_bar(Op_MemBarCPUOrder);
2697   insert_mem_bar(Op_MemBarAcquire);
2698 
2699   push(cas);
2700   return true;
2701 }
2702 
2703 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
2704   // This is another variant of inline_unsafe_access, differing in
2705   // that it always issues store-store ("release") barrier and ensures
2706   // store-atomicity (which only matters for "long").
2707 
2708   if (callee()->is_static())  return false;  // caller must have the capability!
2709 
2710 #ifndef PRODUCT
2711   {
2712     ResourceMark rm;
2713     // Check the signatures.
2714     ciSignature* sig = signature();
2715 #ifdef ASSERT
2716     BasicType rtype = sig->return_type()->basic_type();
2717     assert(rtype == T_VOID, "must return void");
2718     assert(sig->count() == 3, "has 3 arguments");
2719     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
2720     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
2721 #endif // ASSERT
2722   }
2723 #endif //PRODUCT
2724 
2725   // number of stack slots per value argument (1 or 2)
2726   int type_words = type2size[type];
2727 
2728   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2729 
2730   // Argument words:  "this" plus oop plus offset plus value;
2731   int nargs = 1 + 1 + 2 + type_words;
2732 
2733   // pop arguments: val, offset, base, and receiver
2734   debug_only(int saved_sp = _sp);
2735   _sp += nargs;
2736   Node* val      = (type_words == 1) ? pop() : pop_pair();
2737   Node *offset   = pop_pair();
2738   Node *base     = pop();
2739   Node *receiver = pop();
2740   assert(saved_sp == _sp, "must have correct argument count");
2741 
2742   //  Null check receiver.
2743   _sp += nargs;
2744   do_null_check(receiver, T_OBJECT);
2745   _sp -= nargs;
2746   if (stopped()) {
2747     return true;
2748   }
2749 
2750   // Build field offset expression.
2751   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2752   // 32-bit machines ignore the high half of long offsets
2753   offset = ConvL2X(offset);
2754   Node* adr = make_unsafe_address(base, offset);
2755   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2756   const Type *value_type = Type::get_const_basic_type(type);
2757   Compile::AliasType* alias_type = C->alias_type(adr_type);
2758 
2759   insert_mem_bar(Op_MemBarRelease);
2760   insert_mem_bar(Op_MemBarCPUOrder);
2761   // Ensure that the store is atomic for longs:
2762   bool require_atomic_access = true;
2763   Node* store;
2764   if (type == T_OBJECT) // reference stores need a store barrier.
2765     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type);
2766   else {
2767     store = store_to_memory(control(), adr, val, type, adr_type, require_atomic_access);
2768   }
2769   insert_mem_bar(Op_MemBarCPUOrder);
2770   return true;
2771 }
2772 
2773 bool LibraryCallKit::inline_unsafe_allocate() {
2774   if (callee()->is_static())  return false;  // caller must have the capability!
2775   int nargs = 1 + 1;
2776   assert(signature()->size() == nargs-1, "alloc has 1 argument");
2777   null_check_receiver(callee());  // check then ignore argument(0)
2778   _sp += nargs;  // set original stack for use by uncommon_trap
2779   Node* cls = do_null_check(argument(1), T_OBJECT);
2780   _sp -= nargs;
2781   if (stopped())  return true;
2782 
2783   Node* kls = load_klass_from_mirror(cls, false, nargs, NULL, 0);
2784   _sp += nargs;  // set original stack for use by uncommon_trap
2785   kls = do_null_check(kls, T_OBJECT);
2786   _sp -= nargs;
2787   if (stopped())  return true;  // argument was like int.class
2788 
2789   // Note:  The argument might still be an illegal value like
2790   // Serializable.class or Object[].class.   The runtime will handle it.
2791   // But we must make an explicit check for initialization.
2792   Node* insp = basic_plus_adr(kls, in_bytes(instanceKlass::init_state_offset()));
2793   // Use T_BOOLEAN for instanceKlass::_init_state so the compiler
2794   // can generate code to load it as unsigned byte.
2795   Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN);
2796   Node* bits = intcon(instanceKlass::fully_initialized);
2797   Node* test = _gvn.transform( new (C, 3) SubINode(inst, bits) );
2798   // The 'test' is non-zero if we need to take a slow path.
2799 
2800   Node* obj = new_instance(kls, test);
2801   push(obj);
2802 
2803   return true;
2804 }
2805 
2806 #ifdef TRACE_HAVE_INTRINSICS
2807 /*
2808  * oop -> myklass
2809  * myklass->trace_id |= USED
2810  * return myklass->trace_id & ~0x3
2811  */
2812 bool LibraryCallKit::inline_native_classID() {
2813   int nargs = 1 + 1;
2814   null_check_receiver(callee());  // check then ignore argument(0)
2815   _sp += nargs;
2816   Node* cls = do_null_check(argument(1), T_OBJECT);
2817   _sp -= nargs;
2818   Node* kls = load_klass_from_mirror(cls, false, nargs, NULL, 0);
2819   _sp += nargs;
2820   kls = do_null_check(kls, T_OBJECT);
2821   _sp -= nargs;
2822   ByteSize offset = TRACE_ID_OFFSET;
2823   Node* insp = basic_plus_adr(kls, in_bytes(offset));
2824   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG);
2825   Node* bits = longcon(~0x03l); // ignore bit 0 & 1
2826   Node* andl = _gvn.transform(new (C, 3) AndLNode(tvalue, bits));
2827   Node* clsused = longcon(0x01l); // set the class bit
2828   Node* orl = _gvn.transform(new (C, 3) OrLNode(tvalue, clsused));
2829 
2830   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
2831   store_to_memory(control(), insp, orl, T_LONG, adr_type);
2832   push_pair(andl);
2833   return true;
2834 }
2835 
2836 bool LibraryCallKit::inline_native_threadID() {
2837   Node* tls_ptr = NULL;
2838   Node* cur_thr = generate_current_thread(tls_ptr);
2839   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
2840   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
2841   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
2842 
2843   Node* threadid = NULL;
2844   size_t thread_id_size = OSThread::thread_id_size();
2845   if (thread_id_size == (size_t) BytesPerLong) {
2846     threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG));
2847     push(threadid);
2848   } else if (thread_id_size == (size_t) BytesPerInt) {
2849     threadid = make_load(control(), p, TypeInt::INT, T_INT);
2850     push(threadid);
2851   } else {
2852     ShouldNotReachHere();
2853   }
2854   return true;
2855 }
2856 #endif
2857 
2858 //------------------------inline_native_time_funcs--------------
2859 // inline code for System.currentTimeMillis() and System.nanoTime()
2860 // these have the same type and signature
2861 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2862   const TypeFunc *tf = OptoRuntime::void_long_Type();
2863   const TypePtr* no_memory_effects = NULL;
2864   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2865   Node* value = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms+0));
2866 #ifdef ASSERT
2867   Node* value_top = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms + 1));
2868   assert(value_top == top(), "second value must be top");
2869 #endif
2870   push_pair(value);
2871   return true;
2872 }
2873 
2874 //------------------------inline_native_currentThread------------------
2875 bool LibraryCallKit::inline_native_currentThread() {
2876   Node* junk = NULL;
2877   push(generate_current_thread(junk));
2878   return true;
2879 }
2880 
2881 //------------------------inline_native_isInterrupted------------------
2882 bool LibraryCallKit::inline_native_isInterrupted() {
2883   const int nargs = 1+1;  // receiver + boolean
2884   assert(nargs == arg_size(), "sanity");
2885   // Add a fast path to t.isInterrupted(clear_int):
2886   //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
2887   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
2888   // So, in the common case that the interrupt bit is false,
2889   // we avoid making a call into the VM.  Even if the interrupt bit
2890   // is true, if the clear_int argument is false, we avoid the VM call.
2891   // However, if the receiver is not currentThread, we must call the VM,
2892   // because there must be some locking done around the operation.
2893 
2894   // We only go to the fast case code if we pass two guards.
2895   // Paths which do not pass are accumulated in the slow_region.
2896   RegionNode* slow_region = new (C, 1) RegionNode(1);
2897   record_for_igvn(slow_region);
2898   RegionNode* result_rgn = new (C, 4) RegionNode(1+3); // fast1, fast2, slow
2899   PhiNode*    result_val = new (C, 4) PhiNode(result_rgn, TypeInt::BOOL);
2900   enum { no_int_result_path   = 1,
2901          no_clear_result_path = 2,
2902          slow_result_path     = 3
2903   };
2904 
2905   // (a) Receiving thread must be the current thread.
2906   Node* rec_thr = argument(0);
2907   Node* tls_ptr = NULL;
2908   Node* cur_thr = generate_current_thread(tls_ptr);
2909   Node* cmp_thr = _gvn.transform( new (C, 3) CmpPNode(cur_thr, rec_thr) );
2910   Node* bol_thr = _gvn.transform( new (C, 2) BoolNode(cmp_thr, BoolTest::ne) );
2911 
2912   bool known_current_thread = (_gvn.type(bol_thr) == TypeInt::ZERO);
2913   if (!known_current_thread)
2914     generate_slow_guard(bol_thr, slow_region);
2915 
2916   // (b) Interrupt bit on TLS must be false.
2917   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
2918   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
2919   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
2920   // Set the control input on the field _interrupted read to prevent it floating up.
2921   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT);
2922   Node* cmp_bit = _gvn.transform( new (C, 3) CmpINode(int_bit, intcon(0)) );
2923   Node* bol_bit = _gvn.transform( new (C, 2) BoolNode(cmp_bit, BoolTest::ne) );
2924 
2925   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2926 
2927   // First fast path:  if (!TLS._interrupted) return false;
2928   Node* false_bit = _gvn.transform( new (C, 1) IfFalseNode(iff_bit) );
2929   result_rgn->init_req(no_int_result_path, false_bit);
2930   result_val->init_req(no_int_result_path, intcon(0));
2931 
2932   // drop through to next case
2933   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_bit)) );
2934 
2935   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
2936   Node* clr_arg = argument(1);
2937   Node* cmp_arg = _gvn.transform( new (C, 3) CmpINode(clr_arg, intcon(0)) );
2938   Node* bol_arg = _gvn.transform( new (C, 2) BoolNode(cmp_arg, BoolTest::ne) );
2939   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
2940 
2941   // Second fast path:  ... else if (!clear_int) return true;
2942   Node* false_arg = _gvn.transform( new (C, 1) IfFalseNode(iff_arg) );
2943   result_rgn->init_req(no_clear_result_path, false_arg);
2944   result_val->init_req(no_clear_result_path, intcon(1));
2945 
2946   // drop through to next case
2947   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_arg)) );
2948 
2949   // (d) Otherwise, go to the slow path.
2950   slow_region->add_req(control());
2951   set_control( _gvn.transform(slow_region) );
2952 
2953   if (stopped()) {
2954     // There is no slow path.
2955     result_rgn->init_req(slow_result_path, top());
2956     result_val->init_req(slow_result_path, top());
2957   } else {
2958     // non-virtual because it is a private non-static
2959     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
2960 
2961     Node* slow_val = set_results_for_java_call(slow_call);
2962     // this->control() comes from set_results_for_java_call
2963 
2964     // If we know that the result of the slow call will be true, tell the optimizer!
2965     if (known_current_thread)  slow_val = intcon(1);
2966 
2967     Node* fast_io  = slow_call->in(TypeFunc::I_O);
2968     Node* fast_mem = slow_call->in(TypeFunc::Memory);
2969     // These two phis are pre-filled with copies of of the fast IO and Memory
2970     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
2971     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2972 
2973     result_rgn->init_req(slow_result_path, control());
2974     io_phi    ->init_req(slow_result_path, i_o());
2975     mem_phi   ->init_req(slow_result_path, reset_memory());
2976     result_val->init_req(slow_result_path, slow_val);
2977 
2978     set_all_memory( _gvn.transform(mem_phi) );
2979     set_i_o(        _gvn.transform(io_phi) );
2980   }
2981 
2982   push_result(result_rgn, result_val);
2983   C->set_has_split_ifs(true); // Has chance for split-if optimization
2984 
2985   return true;
2986 }
2987 
2988 //---------------------------load_mirror_from_klass----------------------------
2989 // Given a klass oop, load its java mirror (a java.lang.Class oop).
2990 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
2991   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
2992   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT);
2993 }
2994 
2995 //-----------------------load_klass_from_mirror_common-------------------------
2996 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
2997 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
2998 // and branch to the given path on the region.
2999 // If never_see_null, take an uncommon trap on null, so we can optimistically
3000 // compile for the non-null case.
3001 // If the region is NULL, force never_see_null = true.
3002 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3003                                                     bool never_see_null,
3004                                                     int nargs,
3005                                                     RegionNode* region,
3006                                                     int null_path,
3007                                                     int offset) {
3008   if (region == NULL)  never_see_null = true;
3009   Node* p = basic_plus_adr(mirror, offset);
3010   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3011   Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type) );
3012   _sp += nargs; // any deopt will start just before call to enclosing method
3013   Node* null_ctl = top();
3014   kls = null_check_oop(kls, &null_ctl, never_see_null);
3015   if (region != NULL) {
3016     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3017     region->init_req(null_path, null_ctl);
3018   } else {
3019     assert(null_ctl == top(), "no loose ends");
3020   }
3021   _sp -= nargs;
3022   return kls;
3023 }
3024 
3025 //--------------------(inline_native_Class_query helpers)---------------------
3026 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
3027 // Fall through if (mods & mask) == bits, take the guard otherwise.
3028 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3029   // Branch around if the given klass has the given modifier bit set.
3030   // Like generate_guard, adds a new path onto the region.
3031   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3032   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT);
3033   Node* mask = intcon(modifier_mask);
3034   Node* bits = intcon(modifier_bits);
3035   Node* mbit = _gvn.transform( new (C, 3) AndINode(mods, mask) );
3036   Node* cmp  = _gvn.transform( new (C, 3) CmpINode(mbit, bits) );
3037   Node* bol  = _gvn.transform( new (C, 2) BoolNode(cmp, BoolTest::ne) );
3038   return generate_fair_guard(bol, region);
3039 }
3040 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3041   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3042 }
3043 
3044 //-------------------------inline_native_Class_query-------------------
3045 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3046   int nargs = 1+0;  // just the Class mirror, in most cases
3047   const Type* return_type = TypeInt::BOOL;
3048   Node* prim_return_value = top();  // what happens if it's a primitive class?
3049   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3050   bool expect_prim = false;     // most of these guys expect to work on refs
3051 
3052   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3053 
3054   switch (id) {
3055   case vmIntrinsics::_isInstance:
3056     nargs = 1+1;  // the Class mirror, plus the object getting queried about
3057     // nothing is an instance of a primitive type
3058     prim_return_value = intcon(0);
3059     break;
3060   case vmIntrinsics::_getModifiers:
3061     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3062     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3063     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3064     break;
3065   case vmIntrinsics::_isInterface:
3066     prim_return_value = intcon(0);
3067     break;
3068   case vmIntrinsics::_isArray:
3069     prim_return_value = intcon(0);
3070     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3071     break;
3072   case vmIntrinsics::_isPrimitive:
3073     prim_return_value = intcon(1);
3074     expect_prim = true;  // obviously
3075     break;
3076   case vmIntrinsics::_getSuperclass:
3077     prim_return_value = null();
3078     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3079     break;
3080   case vmIntrinsics::_getComponentType:
3081     prim_return_value = null();
3082     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3083     break;
3084   case vmIntrinsics::_getClassAccessFlags:
3085     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3086     return_type = TypeInt::INT;  // not bool!  6297094
3087     break;
3088   default:
3089     ShouldNotReachHere();
3090   }
3091 
3092   Node* mirror =                      argument(0);
3093   Node* obj    = (nargs <= 1)? top(): argument(1);
3094 
3095   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3096   if (mirror_con == NULL)  return false;  // cannot happen?
3097 
3098 #ifndef PRODUCT
3099   if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
3100     ciType* k = mirror_con->java_mirror_type();
3101     if (k) {
3102       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3103       k->print_name();
3104       tty->cr();
3105     }
3106   }
3107 #endif
3108 
3109   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3110   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3111   record_for_igvn(region);
3112   PhiNode* phi = new (C, PATH_LIMIT) PhiNode(region, return_type);
3113 
3114   // The mirror will never be null of Reflection.getClassAccessFlags, however
3115   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3116   // if it is. See bug 4774291.
3117 
3118   // For Reflection.getClassAccessFlags(), the null check occurs in
3119   // the wrong place; see inline_unsafe_access(), above, for a similar
3120   // situation.
3121   _sp += nargs;  // set original stack for use by uncommon_trap
3122   mirror = do_null_check(mirror, T_OBJECT);
3123   _sp -= nargs;
3124   // If mirror or obj is dead, only null-path is taken.
3125   if (stopped())  return true;
3126 
3127   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3128 
3129   // Now load the mirror's klass metaobject, and null-check it.
3130   // Side-effects region with the control path if the klass is null.
3131   Node* kls = load_klass_from_mirror(mirror, never_see_null, nargs,
3132                                      region, _prim_path);
3133   // If kls is null, we have a primitive mirror.
3134   phi->init_req(_prim_path, prim_return_value);
3135   if (stopped()) { push_result(region, phi); return true; }
3136 
3137   Node* p;  // handy temp
3138   Node* null_ctl;
3139 
3140   // Now that we have the non-null klass, we can perform the real query.
3141   // For constant classes, the query will constant-fold in LoadNode::Value.
3142   Node* query_value = top();
3143   switch (id) {
3144   case vmIntrinsics::_isInstance:
3145     // nothing is an instance of a primitive type
3146     _sp += nargs;          // gen_instanceof might do an uncommon trap
3147     query_value = gen_instanceof(obj, kls);
3148     _sp -= nargs;
3149     break;
3150 
3151   case vmIntrinsics::_getModifiers:
3152     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3153     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
3154     break;
3155 
3156   case vmIntrinsics::_isInterface:
3157     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3158     if (generate_interface_guard(kls, region) != NULL)
3159       // A guard was added.  If the guard is taken, it was an interface.
3160       phi->add_req(intcon(1));
3161     // If we fall through, it's a plain class.
3162     query_value = intcon(0);
3163     break;
3164 
3165   case vmIntrinsics::_isArray:
3166     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3167     if (generate_array_guard(kls, region) != NULL)
3168       // A guard was added.  If the guard is taken, it was an array.
3169       phi->add_req(intcon(1));
3170     // If we fall through, it's a plain class.
3171     query_value = intcon(0);
3172     break;
3173 
3174   case vmIntrinsics::_isPrimitive:
3175     query_value = intcon(0); // "normal" path produces false
3176     break;
3177 
3178   case vmIntrinsics::_getSuperclass:
3179     // The rules here are somewhat unfortunate, but we can still do better
3180     // with random logic than with a JNI call.
3181     // Interfaces store null or Object as _super, but must report null.
3182     // Arrays store an intermediate super as _super, but must report Object.
3183     // Other types can report the actual _super.
3184     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3185     if (generate_interface_guard(kls, region) != NULL)
3186       // A guard was added.  If the guard is taken, it was an interface.
3187       phi->add_req(null());
3188     if (generate_array_guard(kls, region) != NULL)
3189       // A guard was added.  If the guard is taken, it was an array.
3190       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3191     // If we fall through, it's a plain class.  Get its _super.
3192     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3193     kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL) );
3194     null_ctl = top();
3195     kls = null_check_oop(kls, &null_ctl);
3196     if (null_ctl != top()) {
3197       // If the guard is taken, Object.superClass is null (both klass and mirror).
3198       region->add_req(null_ctl);
3199       phi   ->add_req(null());
3200     }
3201     if (!stopped()) {
3202       query_value = load_mirror_from_klass(kls);
3203     }
3204     break;
3205 
3206   case vmIntrinsics::_getComponentType:
3207     if (generate_array_guard(kls, region) != NULL) {
3208       // Be sure to pin the oop load to the guard edge just created:
3209       Node* is_array_ctrl = region->in(region->req()-1);
3210       Node* cma = basic_plus_adr(kls, in_bytes(arrayKlass::component_mirror_offset()));
3211       Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT);
3212       phi->add_req(cmo);
3213     }
3214     query_value = null();  // non-array case is null
3215     break;
3216 
3217   case vmIntrinsics::_getClassAccessFlags:
3218     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3219     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
3220     break;
3221 
3222   default:
3223     ShouldNotReachHere();
3224   }
3225 
3226   // Fall-through is the normal case of a query to a real class.
3227   phi->init_req(1, query_value);
3228   region->init_req(1, control());
3229 
3230   push_result(region, phi);
3231   C->set_has_split_ifs(true); // Has chance for split-if optimization
3232 
3233   return true;
3234 }
3235 
3236 //--------------------------inline_native_subtype_check------------------------
3237 // This intrinsic takes the JNI calls out of the heart of
3238 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3239 bool LibraryCallKit::inline_native_subtype_check() {
3240   int nargs = 1+1;  // the Class mirror, plus the other class getting examined
3241 
3242   // Pull both arguments off the stack.
3243   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3244   args[0] = argument(0);
3245   args[1] = argument(1);
3246   Node* klasses[2];             // corresponding Klasses: superk, subk
3247   klasses[0] = klasses[1] = top();
3248 
3249   enum {
3250     // A full decision tree on {superc is prim, subc is prim}:
3251     _prim_0_path = 1,           // {P,N} => false
3252                                 // {P,P} & superc!=subc => false
3253     _prim_same_path,            // {P,P} & superc==subc => true
3254     _prim_1_path,               // {N,P} => false
3255     _ref_subtype_path,          // {N,N} & subtype check wins => true
3256     _both_ref_path,             // {N,N} & subtype check loses => false
3257     PATH_LIMIT
3258   };
3259 
3260   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3261   Node*       phi    = new (C, PATH_LIMIT) PhiNode(region, TypeInt::BOOL);
3262   record_for_igvn(region);
3263 
3264   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3265   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3266   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3267 
3268   // First null-check both mirrors and load each mirror's klass metaobject.
3269   int which_arg;
3270   for (which_arg = 0; which_arg <= 1; which_arg++) {
3271     Node* arg = args[which_arg];
3272     _sp += nargs;  // set original stack for use by uncommon_trap
3273     arg = do_null_check(arg, T_OBJECT);
3274     _sp -= nargs;
3275     if (stopped())  break;
3276     args[which_arg] = _gvn.transform(arg);
3277 
3278     Node* p = basic_plus_adr(arg, class_klass_offset);
3279     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
3280     klasses[which_arg] = _gvn.transform(kls);
3281   }
3282 
3283   // Having loaded both klasses, test each for null.
3284   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3285   for (which_arg = 0; which_arg <= 1; which_arg++) {
3286     Node* kls = klasses[which_arg];
3287     Node* null_ctl = top();
3288     _sp += nargs;  // set original stack for use by uncommon_trap
3289     kls = null_check_oop(kls, &null_ctl, never_see_null);
3290     _sp -= nargs;
3291     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3292     region->init_req(prim_path, null_ctl);
3293     if (stopped())  break;
3294     klasses[which_arg] = kls;
3295   }
3296 
3297   if (!stopped()) {
3298     // now we have two reference types, in klasses[0..1]
3299     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3300     Node* superk = klasses[0];  // the receiver
3301     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3302     // now we have a successful reference subtype check
3303     region->set_req(_ref_subtype_path, control());
3304   }
3305 
3306   // If both operands are primitive (both klasses null), then
3307   // we must return true when they are identical primitives.
3308   // It is convenient to test this after the first null klass check.
3309   set_control(region->in(_prim_0_path)); // go back to first null check
3310   if (!stopped()) {
3311     // Since superc is primitive, make a guard for the superc==subc case.
3312     Node* cmp_eq = _gvn.transform( new (C, 3) CmpPNode(args[0], args[1]) );
3313     Node* bol_eq = _gvn.transform( new (C, 2) BoolNode(cmp_eq, BoolTest::eq) );
3314     generate_guard(bol_eq, region, PROB_FAIR);
3315     if (region->req() == PATH_LIMIT+1) {
3316       // A guard was added.  If the added guard is taken, superc==subc.
3317       region->swap_edges(PATH_LIMIT, _prim_same_path);
3318       region->del_req(PATH_LIMIT);
3319     }
3320     region->set_req(_prim_0_path, control()); // Not equal after all.
3321   }
3322 
3323   // these are the only paths that produce 'true':
3324   phi->set_req(_prim_same_path,   intcon(1));
3325   phi->set_req(_ref_subtype_path, intcon(1));
3326 
3327   // pull together the cases:
3328   assert(region->req() == PATH_LIMIT, "sane region");
3329   for (uint i = 1; i < region->req(); i++) {
3330     Node* ctl = region->in(i);
3331     if (ctl == NULL || ctl == top()) {
3332       region->set_req(i, top());
3333       phi   ->set_req(i, top());
3334     } else if (phi->in(i) == NULL) {
3335       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3336     }
3337   }
3338 
3339   set_control(_gvn.transform(region));
3340   push(_gvn.transform(phi));
3341 
3342   return true;
3343 }
3344 
3345 //---------------------generate_array_guard_common------------------------
3346 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3347                                                   bool obj_array, bool not_array) {
3348   // If obj_array/non_array==false/false:
3349   // Branch around if the given klass is in fact an array (either obj or prim).
3350   // If obj_array/non_array==false/true:
3351   // Branch around if the given klass is not an array klass of any kind.
3352   // If obj_array/non_array==true/true:
3353   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3354   // If obj_array/non_array==true/false:
3355   // Branch around if the kls is an oop array (Object[] or subtype)
3356   //
3357   // Like generate_guard, adds a new path onto the region.
3358   jint  layout_con = 0;
3359   Node* layout_val = get_layout_helper(kls, layout_con);
3360   if (layout_val == NULL) {
3361     bool query = (obj_array
3362                   ? Klass::layout_helper_is_objArray(layout_con)
3363                   : Klass::layout_helper_is_javaArray(layout_con));
3364     if (query == not_array) {
3365       return NULL;                       // never a branch
3366     } else {                             // always a branch
3367       Node* always_branch = control();
3368       if (region != NULL)
3369         region->add_req(always_branch);
3370       set_control(top());
3371       return always_branch;
3372     }
3373   }
3374   // Now test the correct condition.
3375   jint  nval = (obj_array
3376                 ? ((jint)Klass::_lh_array_tag_type_value
3377                    <<    Klass::_lh_array_tag_shift)
3378                 : Klass::_lh_neutral_value);
3379   Node* cmp = _gvn.transform( new(C, 3) CmpINode(layout_val, intcon(nval)) );
3380   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3381   // invert the test if we are looking for a non-array
3382   if (not_array)  btest = BoolTest(btest).negate();
3383   Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, btest) );
3384   return generate_fair_guard(bol, region);
3385 }
3386 
3387 
3388 //-----------------------inline_native_newArray--------------------------
3389 bool LibraryCallKit::inline_native_newArray() {
3390   int nargs = 2;
3391   Node* mirror    = argument(0);
3392   Node* count_val = argument(1);
3393 
3394   _sp += nargs;  // set original stack for use by uncommon_trap
3395   mirror = do_null_check(mirror, T_OBJECT);
3396   _sp -= nargs;
3397   // If mirror or obj is dead, only null-path is taken.
3398   if (stopped())  return true;
3399 
3400   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3401   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3402   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
3403                                                       TypeInstPtr::NOTNULL);
3404   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
3405   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
3406                                                       TypePtr::BOTTOM);
3407 
3408   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3409   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3410                                                   nargs,
3411                                                   result_reg, _slow_path);
3412   Node* normal_ctl   = control();
3413   Node* no_array_ctl = result_reg->in(_slow_path);
3414 
3415   // Generate code for the slow case.  We make a call to newArray().
3416   set_control(no_array_ctl);
3417   if (!stopped()) {
3418     // Either the input type is void.class, or else the
3419     // array klass has not yet been cached.  Either the
3420     // ensuing call will throw an exception, or else it
3421     // will cache the array klass for next time.
3422     PreserveJVMState pjvms(this);
3423     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3424     Node* slow_result = set_results_for_java_call(slow_call);
3425     // this->control() comes from set_results_for_java_call
3426     result_reg->set_req(_slow_path, control());
3427     result_val->set_req(_slow_path, slow_result);
3428     result_io ->set_req(_slow_path, i_o());
3429     result_mem->set_req(_slow_path, reset_memory());
3430   }
3431 
3432   set_control(normal_ctl);
3433   if (!stopped()) {
3434     // Normal case:  The array type has been cached in the java.lang.Class.
3435     // The following call works fine even if the array type is polymorphic.
3436     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3437     Node* obj = new_array(klass_node, count_val, nargs);
3438     result_reg->init_req(_normal_path, control());
3439     result_val->init_req(_normal_path, obj);
3440     result_io ->init_req(_normal_path, i_o());
3441     result_mem->init_req(_normal_path, reset_memory());
3442   }
3443 
3444   // Return the combined state.
3445   set_i_o(        _gvn.transform(result_io)  );
3446   set_all_memory( _gvn.transform(result_mem) );
3447   push_result(result_reg, result_val);
3448   C->set_has_split_ifs(true); // Has chance for split-if optimization
3449 
3450   return true;
3451 }
3452 
3453 //----------------------inline_native_getLength--------------------------
3454 bool LibraryCallKit::inline_native_getLength() {
3455   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3456 
3457   int nargs = 1;
3458   Node* array = argument(0);
3459 
3460   _sp += nargs;  // set original stack for use by uncommon_trap
3461   array = do_null_check(array, T_OBJECT);
3462   _sp -= nargs;
3463 
3464   // If array is dead, only null-path is taken.
3465   if (stopped())  return true;
3466 
3467   // Deoptimize if it is a non-array.
3468   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3469 
3470   if (non_array != NULL) {
3471     PreserveJVMState pjvms(this);
3472     set_control(non_array);
3473     _sp += nargs;  // push the arguments back on the stack
3474     uncommon_trap(Deoptimization::Reason_intrinsic,
3475                   Deoptimization::Action_maybe_recompile);
3476   }
3477 
3478   // If control is dead, only non-array-path is taken.
3479   if (stopped())  return true;
3480 
3481   // The works fine even if the array type is polymorphic.
3482   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3483   push( load_array_length(array) );
3484 
3485   C->set_has_split_ifs(true); // Has chance for split-if optimization
3486 
3487   return true;
3488 }
3489 
3490 //------------------------inline_array_copyOf----------------------------
3491 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3492   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3493 
3494   // Restore the stack and pop off the arguments.
3495   int nargs = 3 + (is_copyOfRange? 1: 0);
3496   Node* original          = argument(0);
3497   Node* start             = is_copyOfRange? argument(1): intcon(0);
3498   Node* end               = is_copyOfRange? argument(2): argument(1);
3499   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3500 
3501   Node* newcopy;
3502 
3503   //set the original stack and the reexecute bit for the interpreter to reexecute
3504   //the bytecode that invokes Arrays.copyOf if deoptimization happens
3505   { PreserveReexecuteState preexecs(this);
3506     _sp += nargs;
3507     jvms()->set_should_reexecute(true);
3508 
3509     array_type_mirror = do_null_check(array_type_mirror, T_OBJECT);
3510     original          = do_null_check(original, T_OBJECT);
3511 
3512     // Check if a null path was taken unconditionally.
3513     if (stopped())  return true;
3514 
3515     Node* orig_length = load_array_length(original);
3516 
3517     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, 0,
3518                                               NULL, 0);
3519     klass_node = do_null_check(klass_node, T_OBJECT);
3520 
3521     RegionNode* bailout = new (C, 1) RegionNode(1);
3522     record_for_igvn(bailout);
3523 
3524     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3525     // Bail out if that is so.
3526     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3527     if (not_objArray != NULL) {
3528       // Improve the klass node's type from the new optimistic assumption:
3529       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3530       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3531       Node* cast = new (C, 2) CastPPNode(klass_node, akls);
3532       cast->init_req(0, control());
3533       klass_node = _gvn.transform(cast);
3534     }
3535 
3536     // Bail out if either start or end is negative.
3537     generate_negative_guard(start, bailout, &start);
3538     generate_negative_guard(end,   bailout, &end);
3539 
3540     Node* length = end;
3541     if (_gvn.type(start) != TypeInt::ZERO) {
3542       length = _gvn.transform( new (C, 3) SubINode(end, start) );
3543     }
3544 
3545     // Bail out if length is negative.
3546     // ...Not needed, since the new_array will throw the right exception.
3547     //generate_negative_guard(length, bailout, &length);
3548 
3549     if (bailout->req() > 1) {
3550       PreserveJVMState pjvms(this);
3551       set_control( _gvn.transform(bailout) );
3552       uncommon_trap(Deoptimization::Reason_intrinsic,
3553                     Deoptimization::Action_maybe_recompile);
3554     }
3555 
3556     if (!stopped()) {
3557 
3558       // How many elements will we copy from the original?
3559       // The answer is MinI(orig_length - start, length).
3560       Node* orig_tail = _gvn.transform( new(C, 3) SubINode(orig_length, start) );
3561       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3562 
3563       newcopy = new_array(klass_node, length, 0);
3564 
3565       // Generate a direct call to the right arraycopy function(s).
3566       // We know the copy is disjoint but we might not know if the
3567       // oop stores need checking.
3568       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3569       // This will fail a store-check if x contains any non-nulls.
3570 
3571       Node* alloc = tightly_coupled_allocation(newcopy, NULL);
3572 
3573       ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, alloc != NULL);
3574       ac->set_copyof();
3575       Node* n = _gvn.transform(ac);
3576       assert(n == ac, "cannot disappear");
3577       ac->connect_outputs(this);
3578     }
3579   } //original reexecute and sp are set back here
3580 
3581   if(!stopped()) {
3582     push(newcopy);
3583   }
3584 
3585   C->set_has_split_ifs(true); // Has chance for split-if optimization
3586 
3587   return true;
3588 }
3589 
3590 
3591 //----------------------generate_virtual_guard---------------------------
3592 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
3593 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
3594                                              RegionNode* slow_region) {
3595   ciMethod* method = callee();
3596   int vtable_index = method->vtable_index();
3597   // Get the methodOop out of the appropriate vtable entry.
3598   int entry_offset  = (instanceKlass::vtable_start_offset() +
3599                      vtable_index*vtableEntry::size()) * wordSize +
3600                      vtableEntry::method_offset_in_bytes();
3601   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
3602   Node* target_call = make_load(NULL, entry_addr, TypeInstPtr::NOTNULL, T_OBJECT);
3603 
3604   // Compare the target method with the expected method (e.g., Object.hashCode).
3605   const TypeInstPtr* native_call_addr = TypeInstPtr::make(method);
3606 
3607   Node* native_call = makecon(native_call_addr);
3608   Node* chk_native  = _gvn.transform( new(C, 3) CmpPNode(target_call, native_call) );
3609   Node* test_native = _gvn.transform( new(C, 2) BoolNode(chk_native, BoolTest::ne) );
3610 
3611   return generate_slow_guard(test_native, slow_region);
3612 }
3613 
3614 //-----------------------generate_method_call----------------------------
3615 // Use generate_method_call to make a slow-call to the real
3616 // method if the fast path fails.  An alternative would be to
3617 // use a stub like OptoRuntime::slow_arraycopy_Java.
3618 // This only works for expanding the current library call,
3619 // not another intrinsic.  (E.g., don't use this for making an
3620 // arraycopy call inside of the copyOf intrinsic.)
3621 CallJavaNode*
3622 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
3623   // When compiling the intrinsic method itself, do not use this technique.
3624   guarantee(callee() != C->method(), "cannot make slow-call to self");
3625 
3626   ciMethod* method = callee();
3627   // ensure the JVMS we have will be correct for this call
3628   guarantee(method_id == method->intrinsic_id(), "must match");
3629 
3630   const TypeFunc* tf = TypeFunc::make(method);
3631   int tfdc = tf->domain()->cnt();
3632   CallJavaNode* slow_call;
3633   if (is_static) {
3634     assert(!is_virtual, "");
3635     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
3636                                 SharedRuntime::get_resolve_static_call_stub(),
3637                                 method, bci());
3638   } else if (is_virtual) {
3639     null_check_receiver(method);
3640     int vtable_index = methodOopDesc::invalid_vtable_index;
3641     if (UseInlineCaches) {
3642       // Suppress the vtable call
3643     } else {
3644       // hashCode and clone are not a miranda methods,
3645       // so the vtable index is fixed.
3646       // No need to use the linkResolver to get it.
3647        vtable_index = method->vtable_index();
3648     }
3649     slow_call = new(C, tfdc) CallDynamicJavaNode(tf,
3650                                 SharedRuntime::get_resolve_virtual_call_stub(),
3651                                 method, vtable_index, bci());
3652   } else {  // neither virtual nor static:  opt_virtual
3653     null_check_receiver(method);
3654     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
3655                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
3656                                 method, bci());
3657     slow_call->set_optimized_virtual(true);
3658   }
3659   set_arguments_for_java_call(slow_call);
3660   set_edges_for_java_call(slow_call);
3661   return slow_call;
3662 }
3663 
3664 
3665 //------------------------------inline_native_hashcode--------------------
3666 // Build special case code for calls to hashCode on an object.
3667 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
3668   assert(is_static == callee()->is_static(), "correct intrinsic selection");
3669   assert(!(is_virtual && is_static), "either virtual, special, or static");
3670 
3671   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
3672 
3673   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3674   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
3675                                                       TypeInt::INT);
3676   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
3677   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
3678                                                       TypePtr::BOTTOM);
3679   Node* obj = NULL;
3680   if (!is_static) {
3681     // Check for hashing null object
3682     obj = null_check_receiver(callee());
3683     if (stopped())  return true;        // unconditionally null
3684     result_reg->init_req(_null_path, top());
3685     result_val->init_req(_null_path, top());
3686   } else {
3687     // Do a null check, and return zero if null.
3688     // System.identityHashCode(null) == 0
3689     obj = argument(0);
3690     Node* null_ctl = top();
3691     obj = null_check_oop(obj, &null_ctl);
3692     result_reg->init_req(_null_path, null_ctl);
3693     result_val->init_req(_null_path, _gvn.intcon(0));
3694   }
3695 
3696   // Unconditionally null?  Then return right away.
3697   if (stopped()) {
3698     set_control( result_reg->in(_null_path) );
3699     if (!stopped())
3700       push(      result_val ->in(_null_path) );
3701     return true;
3702   }
3703 
3704   // After null check, get the object's klass.
3705   Node* obj_klass = load_object_klass(obj);
3706 
3707   // This call may be virtual (invokevirtual) or bound (invokespecial).
3708   // For each case we generate slightly different code.
3709 
3710   // We only go to the fast case code if we pass a number of guards.  The
3711   // paths which do not pass are accumulated in the slow_region.
3712   RegionNode* slow_region = new (C, 1) RegionNode(1);
3713   record_for_igvn(slow_region);
3714 
3715   // If this is a virtual call, we generate a funny guard.  We pull out
3716   // the vtable entry corresponding to hashCode() from the target object.
3717   // If the target method which we are calling happens to be the native
3718   // Object hashCode() method, we pass the guard.  We do not need this
3719   // guard for non-virtual calls -- the caller is known to be the native
3720   // Object hashCode().
3721   if (is_virtual) {
3722     generate_virtual_guard(obj_klass, slow_region);
3723   }
3724 
3725   // Get the header out of the object, use LoadMarkNode when available
3726   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3727   Node* header = make_load(control(), header_addr, TypeX_X, TypeX_X->basic_type());
3728 
3729   // Test the header to see if it is unlocked.
3730   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
3731   Node *lmasked_header = _gvn.transform( new (C, 3) AndXNode(header, lock_mask) );
3732   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
3733   Node *chk_unlocked   = _gvn.transform( new (C, 3) CmpXNode( lmasked_header, unlocked_val));
3734   Node *test_unlocked  = _gvn.transform( new (C, 2) BoolNode( chk_unlocked, BoolTest::ne) );
3735 
3736   generate_slow_guard(test_unlocked, slow_region);
3737 
3738   // Get the hash value and check to see that it has been properly assigned.
3739   // We depend on hash_mask being at most 32 bits and avoid the use of
3740   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
3741   // vm: see markOop.hpp.
3742   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
3743   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
3744   Node *hshifted_header= _gvn.transform( new (C, 3) URShiftXNode(header, hash_shift) );
3745   // This hack lets the hash bits live anywhere in the mark object now, as long
3746   // as the shift drops the relevant bits into the low 32 bits.  Note that
3747   // Java spec says that HashCode is an int so there's no point in capturing
3748   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
3749   hshifted_header      = ConvX2I(hshifted_header);
3750   Node *hash_val       = _gvn.transform( new (C, 3) AndINode(hshifted_header, hash_mask) );
3751 
3752   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
3753   Node *chk_assigned   = _gvn.transform( new (C, 3) CmpINode( hash_val, no_hash_val));
3754   Node *test_assigned  = _gvn.transform( new (C, 2) BoolNode( chk_assigned, BoolTest::eq) );
3755 
3756   generate_slow_guard(test_assigned, slow_region);
3757 
3758   Node* init_mem = reset_memory();
3759   // fill in the rest of the null path:
3760   result_io ->init_req(_null_path, i_o());
3761   result_mem->init_req(_null_path, init_mem);
3762 
3763   result_val->init_req(_fast_path, hash_val);
3764   result_reg->init_req(_fast_path, control());
3765   result_io ->init_req(_fast_path, i_o());
3766   result_mem->init_req(_fast_path, init_mem);
3767 
3768   // Generate code for the slow case.  We make a call to hashCode().
3769   set_control(_gvn.transform(slow_region));
3770   if (!stopped()) {
3771     // No need for PreserveJVMState, because we're using up the present state.
3772     set_all_memory(init_mem);
3773     vmIntrinsics::ID hashCode_id = vmIntrinsics::_hashCode;
3774     if (is_static)   hashCode_id = vmIntrinsics::_identityHashCode;
3775     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
3776     Node* slow_result = set_results_for_java_call(slow_call);
3777     // this->control() comes from set_results_for_java_call
3778     result_reg->init_req(_slow_path, control());
3779     result_val->init_req(_slow_path, slow_result);
3780     result_io  ->set_req(_slow_path, i_o());
3781     result_mem ->set_req(_slow_path, reset_memory());
3782   }
3783 
3784   // Return the combined state.
3785   set_i_o(        _gvn.transform(result_io)  );
3786   set_all_memory( _gvn.transform(result_mem) );
3787   push_result(result_reg, result_val);
3788 
3789   return true;
3790 }
3791 
3792 //---------------------------inline_native_getClass----------------------------
3793 // Build special case code for calls to getClass on an object.
3794 bool LibraryCallKit::inline_native_getClass() {
3795   Node* obj = null_check_receiver(callee());
3796   if (stopped())  return true;
3797   push( load_mirror_from_klass(load_object_klass(obj)) );
3798   return true;
3799 }
3800 
3801 //-----------------inline_native_Reflection_getCallerClass---------------------
3802 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
3803 //
3804 // NOTE that this code must perform the same logic as
3805 // vframeStream::security_get_caller_frame in that it must skip
3806 // Method.invoke() and auxiliary frames.
3807 
3808 
3809 
3810 
3811 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
3812   ciMethod*       method = callee();
3813 
3814 #ifndef PRODUCT
3815   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3816     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
3817   }
3818 #endif
3819 
3820   debug_only(int saved_sp = _sp);
3821 
3822   // Argument words:  (int depth)
3823   int nargs = 1;
3824 
3825   _sp += nargs;
3826   Node* caller_depth_node = pop();
3827 
3828   assert(saved_sp == _sp, "must have correct argument count");
3829 
3830   // The depth value must be a constant in order for the runtime call
3831   // to be eliminated.
3832   const TypeInt* caller_depth_type = _gvn.type(caller_depth_node)->isa_int();
3833   if (caller_depth_type == NULL || !caller_depth_type->is_con()) {
3834 #ifndef PRODUCT
3835     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3836       tty->print_cr("  Bailing out because caller depth was not a constant");
3837     }
3838 #endif
3839     return false;
3840   }
3841   // Note that the JVM state at this point does not include the
3842   // getCallerClass() frame which we are trying to inline. The
3843   // semantics of getCallerClass(), however, are that the "first"
3844   // frame is the getCallerClass() frame, so we subtract one from the
3845   // requested depth before continuing. We don't inline requests of
3846   // getCallerClass(0).
3847   int caller_depth = caller_depth_type->get_con() - 1;
3848   if (caller_depth < 0) {
3849 #ifndef PRODUCT
3850     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3851       tty->print_cr("  Bailing out because caller depth was %d", caller_depth);
3852     }
3853 #endif
3854     return false;
3855   }
3856 
3857   if (!jvms()->has_method()) {
3858 #ifndef PRODUCT
3859     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3860       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
3861     }
3862 #endif
3863     return false;
3864   }
3865   int _depth = jvms()->depth();  // cache call chain depth
3866 
3867   // Walk back up the JVM state to find the caller at the required
3868   // depth. NOTE that this code must perform the same logic as
3869   // vframeStream::security_get_caller_frame in that it must skip
3870   // Method.invoke() and auxiliary frames. Note also that depth is
3871   // 1-based (1 is the bottom of the inlining).
3872   int inlining_depth = _depth;
3873   JVMState* caller_jvms = NULL;
3874 
3875   if (inlining_depth > 0) {
3876     caller_jvms = jvms();
3877     assert(caller_jvms = jvms()->of_depth(inlining_depth), "inlining_depth == our depth");
3878     do {
3879       // The following if-tests should be performed in this order
3880       if (is_method_invoke_or_aux_frame(caller_jvms)) {
3881         // Skip a Method.invoke() or auxiliary frame
3882       } else if (caller_depth > 0) {
3883         // Skip real frame
3884         --caller_depth;
3885       } else {
3886         // We're done: reached desired caller after skipping.
3887         break;
3888       }
3889       caller_jvms = caller_jvms->caller();
3890       --inlining_depth;
3891     } while (inlining_depth > 0);
3892   }
3893 
3894   if (inlining_depth == 0) {
3895 #ifndef PRODUCT
3896     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3897       tty->print_cr("  Bailing out because caller depth (%d) exceeded inlining depth (%d)", caller_depth_type->get_con(), _depth);
3898       tty->print_cr("  JVM state at this point:");
3899       for (int i = _depth; i >= 1; i--) {
3900         tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
3901       }
3902     }
3903 #endif
3904     return false; // Reached end of inlining
3905   }
3906 
3907   // Acquire method holder as java.lang.Class
3908   ciInstanceKlass* caller_klass  = caller_jvms->method()->holder();
3909   ciInstance*      caller_mirror = caller_klass->java_mirror();
3910   // Push this as a constant
3911   push(makecon(TypeInstPtr::make(caller_mirror)));
3912 #ifndef PRODUCT
3913   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3914     tty->print_cr("  Succeeded: caller = %s.%s, caller depth = %d, depth = %d", caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), caller_depth_type->get_con(), _depth);
3915     tty->print_cr("  JVM state at this point:");
3916     for (int i = _depth; i >= 1; i--) {
3917       tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
3918     }
3919   }
3920 #endif
3921   return true;
3922 }
3923 
3924 // Helper routine for above
3925 bool LibraryCallKit::is_method_invoke_or_aux_frame(JVMState* jvms) {
3926   ciMethod* method = jvms->method();
3927 
3928   // Is this the Method.invoke method itself?
3929   if (method->intrinsic_id() == vmIntrinsics::_invoke)
3930     return true;
3931 
3932   // Is this a helper, defined somewhere underneath MethodAccessorImpl.
3933   ciKlass* k = method->holder();
3934   if (k->is_instance_klass()) {
3935     ciInstanceKlass* ik = k->as_instance_klass();
3936     for (; ik != NULL; ik = ik->super()) {
3937       if (ik->name() == ciSymbol::sun_reflect_MethodAccessorImpl() &&
3938           ik == env()->find_system_klass(ik->name())) {
3939         return true;
3940       }
3941     }
3942   }
3943   else if (method->is_method_handle_adapter()) {
3944     // This is an internal adapter frame from the MethodHandleCompiler -- skip it
3945     return true;
3946   }
3947 
3948   return false;
3949 }
3950 
3951 static int value_field_offset = -1;  // offset of the "value" field of AtomicLongCSImpl.  This is needed by
3952                                      // inline_native_AtomicLong_attemptUpdate() but it has no way of
3953                                      // computing it since there is no lookup field by name function in the
3954                                      // CI interface.  This is computed and set by inline_native_AtomicLong_get().
3955                                      // Using a static variable here is safe even if we have multiple compilation
3956                                      // threads because the offset is constant.  At worst the same offset will be
3957                                      // computed and  stored multiple
3958 
3959 bool LibraryCallKit::inline_native_AtomicLong_get() {
3960   // Restore the stack and pop off the argument
3961   _sp+=1;
3962   Node *obj = pop();
3963 
3964   // get the offset of the "value" field. Since the CI interfaces
3965   // does not provide a way to look up a field by name, we scan the bytecodes
3966   // to get the field index.  We expect the first 2 instructions of the method
3967   // to be:
3968   //    0 aload_0
3969   //    1 getfield "value"
3970   ciMethod* method = callee();
3971   if (value_field_offset == -1)
3972   {
3973     ciField* value_field;
3974     ciBytecodeStream iter(method);
3975     Bytecodes::Code bc = iter.next();
3976 
3977     if ((bc != Bytecodes::_aload_0) &&
3978               ((bc != Bytecodes::_aload) || (iter.get_index() != 0)))
3979       return false;
3980     bc = iter.next();
3981     if (bc != Bytecodes::_getfield)
3982       return false;
3983     bool ignore;
3984     value_field = iter.get_field(ignore);
3985     value_field_offset = value_field->offset_in_bytes();
3986   }
3987 
3988   // Null check without removing any arguments.
3989   _sp++;
3990   obj = do_null_check(obj, T_OBJECT);
3991   _sp--;
3992   // Check for locking null object
3993   if (stopped()) return true;
3994 
3995   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
3996   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
3997   int alias_idx = C->get_alias_index(adr_type);
3998 
3999   Node *result = _gvn.transform(new (C, 3) LoadLLockedNode(control(), memory(alias_idx), adr));
4000 
4001   push_pair(result);
4002 
4003   return true;
4004 }
4005 
4006 bool LibraryCallKit::inline_native_AtomicLong_attemptUpdate() {
4007   // Restore the stack and pop off the arguments
4008   _sp+=5;
4009   Node *newVal = pop_pair();
4010   Node *oldVal = pop_pair();
4011   Node *obj = pop();
4012 
4013   // we need the offset of the "value" field which was computed when
4014   // inlining the get() method.  Give up if we don't have it.
4015   if (value_field_offset == -1)
4016     return false;
4017 
4018   // Null check without removing any arguments.
4019   _sp+=5;
4020   obj = do_null_check(obj, T_OBJECT);
4021   _sp-=5;
4022   // Check for locking null object
4023   if (stopped()) return true;
4024 
4025   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
4026   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
4027   int alias_idx = C->get_alias_index(adr_type);
4028 
4029   Node *cas = _gvn.transform(new (C, 5) StoreLConditionalNode(control(), memory(alias_idx), adr, newVal, oldVal));
4030   Node *store_proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
4031   set_memory(store_proj, alias_idx);
4032   Node *bol = _gvn.transform( new (C, 2) BoolNode( cas, BoolTest::eq ) );
4033 
4034   Node *result;
4035   // CMove node is not used to be able fold a possible check code
4036   // after attemptUpdate() call. This code could be transformed
4037   // into CMove node by loop optimizations.
4038   {
4039     RegionNode *r = new (C, 3) RegionNode(3);
4040     result = new (C, 3) PhiNode(r, TypeInt::BOOL);
4041 
4042     Node *iff = create_and_xform_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4043     Node *iftrue = opt_iff(r, iff);
4044     r->init_req(1, iftrue);
4045     result->init_req(1, intcon(1));
4046     result->init_req(2, intcon(0));
4047 
4048     set_control(_gvn.transform(r));
4049     record_for_igvn(r);
4050 
4051     C->set_has_split_ifs(true); // Has chance for split-if optimization
4052   }
4053 
4054   push(_gvn.transform(result));
4055   return true;
4056 }
4057 
4058 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4059   // restore the arguments
4060   _sp += arg_size();
4061 
4062   switch (id) {
4063   case vmIntrinsics::_floatToRawIntBits:
4064     push(_gvn.transform( new (C, 2) MoveF2INode(pop())));
4065     break;
4066 
4067   case vmIntrinsics::_intBitsToFloat:
4068     push(_gvn.transform( new (C, 2) MoveI2FNode(pop())));
4069     break;
4070 
4071   case vmIntrinsics::_doubleToRawLongBits:
4072     push_pair(_gvn.transform( new (C, 2) MoveD2LNode(pop_pair())));
4073     break;
4074 
4075   case vmIntrinsics::_longBitsToDouble:
4076     push_pair(_gvn.transform( new (C, 2) MoveL2DNode(pop_pair())));
4077     break;
4078 
4079   case vmIntrinsics::_doubleToLongBits: {
4080     Node* value = pop_pair();
4081 
4082     // two paths (plus control) merge in a wood
4083     RegionNode *r = new (C, 3) RegionNode(3);
4084     Node *phi = new (C, 3) PhiNode(r, TypeLong::LONG);
4085 
4086     Node *cmpisnan = _gvn.transform( new (C, 3) CmpDNode(value, value));
4087     // Build the boolean node
4088     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
4089 
4090     // Branch either way.
4091     // NaN case is less traveled, which makes all the difference.
4092     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4093     Node *opt_isnan = _gvn.transform(ifisnan);
4094     assert( opt_isnan->is_If(), "Expect an IfNode");
4095     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4096     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
4097 
4098     set_control(iftrue);
4099 
4100     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4101     Node *slow_result = longcon(nan_bits); // return NaN
4102     phi->init_req(1, _gvn.transform( slow_result ));
4103     r->init_req(1, iftrue);
4104 
4105     // Else fall through
4106     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
4107     set_control(iffalse);
4108 
4109     phi->init_req(2, _gvn.transform( new (C, 2) MoveD2LNode(value)));
4110     r->init_req(2, iffalse);
4111 
4112     // Post merge
4113     set_control(_gvn.transform(r));
4114     record_for_igvn(r);
4115 
4116     Node* result = _gvn.transform(phi);
4117     assert(result->bottom_type()->isa_long(), "must be");
4118     push_pair(result);
4119 
4120     C->set_has_split_ifs(true); // Has chance for split-if optimization
4121 
4122     break;
4123   }
4124 
4125   case vmIntrinsics::_floatToIntBits: {
4126     Node* value = pop();
4127 
4128     // two paths (plus control) merge in a wood
4129     RegionNode *r = new (C, 3) RegionNode(3);
4130     Node *phi = new (C, 3) PhiNode(r, TypeInt::INT);
4131 
4132     Node *cmpisnan = _gvn.transform( new (C, 3) CmpFNode(value, value));
4133     // Build the boolean node
4134     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
4135 
4136     // Branch either way.
4137     // NaN case is less traveled, which makes all the difference.
4138     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4139     Node *opt_isnan = _gvn.transform(ifisnan);
4140     assert( opt_isnan->is_If(), "Expect an IfNode");
4141     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4142     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
4143 
4144     set_control(iftrue);
4145 
4146     static const jint nan_bits = 0x7fc00000;
4147     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4148     phi->init_req(1, _gvn.transform( slow_result ));
4149     r->init_req(1, iftrue);
4150 
4151     // Else fall through
4152     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
4153     set_control(iffalse);
4154 
4155     phi->init_req(2, _gvn.transform( new (C, 2) MoveF2INode(value)));
4156     r->init_req(2, iffalse);
4157 
4158     // Post merge
4159     set_control(_gvn.transform(r));
4160     record_for_igvn(r);
4161 
4162     Node* result = _gvn.transform(phi);
4163     assert(result->bottom_type()->isa_int(), "must be");
4164     push(result);
4165 
4166     C->set_has_split_ifs(true); // Has chance for split-if optimization
4167 
4168     break;
4169   }
4170 
4171   default:
4172     ShouldNotReachHere();
4173   }
4174 
4175   return true;
4176 }
4177 
4178 #ifdef _LP64
4179 #define XTOP ,top() /*additional argument*/
4180 #else  //_LP64
4181 #define XTOP        /*no additional argument*/
4182 #endif //_LP64
4183 
4184 //----------------------inline_unsafe_copyMemory-------------------------
4185 bool LibraryCallKit::inline_unsafe_copyMemory() {
4186   if (callee()->is_static())  return false;  // caller must have the capability!
4187   int nargs = 1 + 5 + 3;  // 5 args:  (src: ptr,off, dst: ptr,off, size)
4188   assert(signature()->size() == nargs-1, "copy has 5 arguments");
4189   null_check_receiver(callee());  // check then ignore argument(0)
4190   if (stopped())  return true;
4191 
4192   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4193 
4194   Node* src_ptr = argument(1);
4195   Node* src_off = ConvL2X(argument(2));
4196   assert(argument(3)->is_top(), "2nd half of long");
4197   Node* dst_ptr = argument(4);
4198   Node* dst_off = ConvL2X(argument(5));
4199   assert(argument(6)->is_top(), "2nd half of long");
4200   Node* size    = ConvL2X(argument(7));
4201   assert(argument(8)->is_top(), "2nd half of long");
4202 
4203   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4204          "fieldOffset must be byte-scaled");
4205 
4206   Node* src = make_unsafe_address(src_ptr, src_off);
4207   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4208 
4209   // Conservatively insert a memory barrier on all memory slices.
4210   // Do not let writes of the copy source or destination float below the copy.
4211   insert_mem_bar(Op_MemBarCPUOrder);
4212 
4213   // Call it.  Note that the length argument is not scaled.
4214   make_runtime_call(RC_LEAF|RC_NO_FP,
4215                     OptoRuntime::fast_arraycopy_Type(),
4216                     StubRoutines::unsafe_arraycopy(),
4217                     "unsafe_arraycopy",
4218                     TypeRawPtr::BOTTOM,
4219                     src, dst, size XTOP);
4220 
4221   // Do not let reads of the copy destination float above the copy.
4222   insert_mem_bar(Op_MemBarCPUOrder);
4223 
4224   return true;
4225 }
4226 
4227 //------------------------clone_coping-----------------------------------
4228 // Helper function for inline_native_clone.
4229 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4230   assert(obj_size != NULL, "");
4231   Node* raw_obj = alloc_obj->in(1);
4232   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4233 
4234   AllocateNode* alloc = NULL;
4235   if (ReduceBulkZeroing) {
4236     // We will be completely responsible for initializing this object -
4237     // mark Initialize node as complete.
4238     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4239     // The object was just allocated - there should be no any stores!
4240     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4241     // Mark as complete_with_arraycopy so that on AllocateNode
4242     // expansion, we know this AllocateNode is initialized by an array
4243     // copy and a StoreStore barrier exists after the array copy.
4244     alloc->initialization()->set_complete_with_arraycopy();
4245   }
4246 
4247   // Copy the fastest available way.
4248   // TODO: generate fields copies for small objects instead.
4249   Node* src  = obj;
4250   Node* dest = alloc_obj;
4251   Node* size = _gvn.transform(obj_size);
4252 
4253   // Exclude the header but include array length to copy by 8 bytes words.
4254   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4255   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4256                             instanceOopDesc::base_offset_in_bytes();
4257   // base_off:
4258   // 8  - 32-bit VM
4259   // 12 - 64-bit VM, compressed oops
4260   // 16 - 64-bit VM, normal oops
4261   if (base_off % BytesPerLong != 0) {
4262     assert(UseCompressedOops, "");
4263     if (is_array) {
4264       // Exclude length to copy by 8 bytes words.
4265       base_off += sizeof(int);
4266     } else {
4267       // Include klass to copy by 8 bytes words.
4268       base_off = instanceOopDesc::klass_offset_in_bytes();
4269     }
4270     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4271   }
4272   src  = basic_plus_adr(src,  base_off);
4273   dest = basic_plus_adr(dest, base_off);
4274 
4275   // Compute the length also, if needed:
4276   Node* countx = size;
4277   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(base_off)) );
4278   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong) ));
4279 
4280   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4281 
4282   ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false);
4283   ac->set_clonebasic();
4284   Node* n = _gvn.transform(ac);
4285   assert(n == ac, "cannot disappear");
4286   set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4287 
4288   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4289   if (card_mark) {
4290     assert(!is_array, "");
4291     // Put in store barrier for any and all oops we are sticking
4292     // into this object.  (We could avoid this if we could prove
4293     // that the object type contains no oop fields at all.)
4294     Node* no_particular_value = NULL;
4295     Node* no_particular_field = NULL;
4296     int raw_adr_idx = Compile::AliasIdxRaw;
4297     post_barrier(control(),
4298                  memory(raw_adr_type),
4299                  alloc_obj,
4300                  no_particular_field,
4301                  raw_adr_idx,
4302                  no_particular_value,
4303                  T_OBJECT,
4304                  false);
4305   }
4306 
4307   // Do not let reads from the cloned object float above the arraycopy.
4308   if (alloc != NULL) {
4309     // Do not let stores that initialize this object be reordered with
4310     // a subsequent store that would make this object accessible by
4311     // other threads.
4312     // Record what AllocateNode this StoreStore protects so that
4313     // escape analysis can go from the MemBarStoreStoreNode to the
4314     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4315     // based on the escape status of the AllocateNode.
4316     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4317   } else {
4318     insert_mem_bar(Op_MemBarCPUOrder);
4319   }
4320 }
4321 
4322 //------------------------inline_native_clone----------------------------
4323 // Here are the simple edge cases:
4324 //  null receiver => normal trap
4325 //  virtual and clone was overridden => slow path to out-of-line clone
4326 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4327 //
4328 // The general case has two steps, allocation and copying.
4329 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4330 //
4331 // Copying also has two cases, oop arrays and everything else.
4332 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4333 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4334 //
4335 // These steps fold up nicely if and when the cloned object's klass
4336 // can be sharply typed as an object array, a type array, or an instance.
4337 //
4338 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4339   int nargs = 1;
4340   PhiNode* result_val;
4341 
4342   //set the original stack and the reexecute bit for the interpreter to reexecute
4343   //the bytecode that invokes Object.clone if deoptimization happens
4344   { PreserveReexecuteState preexecs(this);
4345     jvms()->set_should_reexecute(true);
4346 
4347     //null_check_receiver will adjust _sp (push and pop)
4348     Node* obj = null_check_receiver(callee());
4349     if (stopped())  return true;
4350 
4351     _sp += nargs;
4352 
4353     Node* obj_klass = load_object_klass(obj);
4354     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4355     const TypeOopPtr*   toop   = ((tklass != NULL)
4356                                 ? tklass->as_instance_type()
4357                                 : TypeInstPtr::NOTNULL);
4358 
4359     // Conservatively insert a memory barrier on all memory slices.
4360     // Do not let writes into the original float below the clone.
4361     insert_mem_bar(Op_MemBarCPUOrder);
4362 
4363     // paths into result_reg:
4364     enum {
4365       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4366       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4367       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4368       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4369       PATH_LIMIT
4370     };
4371     RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
4372     result_val             = new(C, PATH_LIMIT) PhiNode(result_reg,
4373                                                         TypeInstPtr::NOTNULL);
4374     PhiNode*    result_i_o = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
4375     PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
4376                                                         TypePtr::BOTTOM);
4377     record_for_igvn(result_reg);
4378 
4379     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4380     int raw_adr_idx = Compile::AliasIdxRaw;
4381 
4382     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4383     if (array_ctl != NULL) {
4384       // It's an array.
4385       PreserveJVMState pjvms(this);
4386       set_control(array_ctl);
4387       Node* obj_length = load_array_length(obj);
4388       Node* obj_size  = NULL;
4389       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);
4390 
4391       if (!use_ReduceInitialCardMarks()) {
4392         // If it is an oop array, it requires very special treatment,
4393         // because card marking is required on each card of the array.
4394         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4395         if (is_obja != NULL) {
4396           PreserveJVMState pjvms2(this);
4397           set_control(is_obja);
4398           // Generate a direct call to the right arraycopy function(s).
4399           Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4400           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL);
4401           ac->set_cloneoop();
4402           Node* n = _gvn.transform(ac);
4403           assert(n == ac, "cannot disappear");
4404           ac->connect_outputs(this);
4405 
4406           result_reg->init_req(_objArray_path, control());
4407           result_val->init_req(_objArray_path, alloc_obj);
4408           result_i_o ->set_req(_objArray_path, i_o());
4409           result_mem ->set_req(_objArray_path, reset_memory());
4410         }
4411       }
4412       // Otherwise, there are no card marks to worry about.
4413       // (We can dispense with card marks if we know the allocation
4414       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4415       //  causes the non-eden paths to take compensating steps to
4416       //  simulate a fresh allocation, so that no further
4417       //  card marks are required in compiled code to initialize
4418       //  the object.)
4419 
4420       if (!stopped()) {
4421         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4422 
4423         // Present the results of the copy.
4424         result_reg->init_req(_array_path, control());
4425         result_val->init_req(_array_path, alloc_obj);
4426         result_i_o ->set_req(_array_path, i_o());
4427         result_mem ->set_req(_array_path, reset_memory());
4428       }
4429     }
4430 
4431     // We only go to the instance fast case code if we pass a number of guards.
4432     // The paths which do not pass are accumulated in the slow_region.
4433     RegionNode* slow_region = new (C, 1) RegionNode(1);
4434     record_for_igvn(slow_region);
4435     if (!stopped()) {
4436       // It's an instance (we did array above).  Make the slow-path tests.
4437       // If this is a virtual call, we generate a funny guard.  We grab
4438       // the vtable entry corresponding to clone() from the target object.
4439       // If the target method which we are calling happens to be the
4440       // Object clone() method, we pass the guard.  We do not need this
4441       // guard for non-virtual calls; the caller is known to be the native
4442       // Object clone().
4443       if (is_virtual) {
4444         generate_virtual_guard(obj_klass, slow_region);
4445       }
4446 
4447       // The object must be cloneable and must not have a finalizer.
4448       // Both of these conditions may be checked in a single test.
4449       // We could optimize the cloneable test further, but we don't care.
4450       generate_access_flags_guard(obj_klass,
4451                                   // Test both conditions:
4452                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4453                                   // Must be cloneable but not finalizer:
4454                                   JVM_ACC_IS_CLONEABLE,
4455                                   slow_region);
4456     }
4457 
4458     if (!stopped()) {
4459       // It's an instance, and it passed the slow-path tests.
4460       PreserveJVMState pjvms(this);
4461       Node* obj_size  = NULL;
4462       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size);
4463 
4464       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4465 
4466       // Present the results of the slow call.
4467       result_reg->init_req(_instance_path, control());
4468       result_val->init_req(_instance_path, alloc_obj);
4469       result_i_o ->set_req(_instance_path, i_o());
4470       result_mem ->set_req(_instance_path, reset_memory());
4471     }
4472 
4473     // Generate code for the slow case.  We make a call to clone().
4474     set_control(_gvn.transform(slow_region));
4475     if (!stopped()) {
4476       PreserveJVMState pjvms(this);
4477       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4478       Node* slow_result = set_results_for_java_call(slow_call);
4479       // this->control() comes from set_results_for_java_call
4480       result_reg->init_req(_slow_path, control());
4481       result_val->init_req(_slow_path, slow_result);
4482       result_i_o ->set_req(_slow_path, i_o());
4483       result_mem ->set_req(_slow_path, reset_memory());
4484     }
4485 
4486     // Return the combined state.
4487     set_control(    _gvn.transform(result_reg) );
4488     set_i_o(        _gvn.transform(result_i_o) );
4489     set_all_memory( _gvn.transform(result_mem) );
4490   } //original reexecute and sp are set back here
4491 
4492   push(_gvn.transform(result_val));
4493 
4494   return true;
4495 }
4496 
4497 //------------------------------basictype2arraycopy----------------------------
4498 address LibraryCallKit::basictype2arraycopy(BasicType t,
4499                                             Node* src_offset,
4500                                             Node* dest_offset,
4501                                             bool disjoint_bases,
4502                                             const char* &name,
4503                                             bool dest_uninitialized) {
4504   const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
4505   const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
4506 
4507   bool aligned = false;
4508   bool disjoint = disjoint_bases;
4509 
4510   // if the offsets are the same, we can treat the memory regions as
4511   // disjoint, because either the memory regions are in different arrays,
4512   // or they are identical (which we can treat as disjoint.)  We can also
4513   // treat a copy with a destination index  less that the source index
4514   // as disjoint since a low->high copy will work correctly in this case.
4515   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
4516       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
4517     // both indices are constants
4518     int s_offs = src_offset_inttype->get_con();
4519     int d_offs = dest_offset_inttype->get_con();
4520     int element_size = type2aelembytes(t);
4521     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
4522               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
4523     if (s_offs >= d_offs)  disjoint = true;
4524   } else if (src_offset == dest_offset && src_offset != NULL) {
4525     // This can occur if the offsets are identical non-constants.
4526     disjoint = true;
4527   }
4528 
4529   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
4530 }
4531 
4532 
4533 //------------------------------inline_arraycopy-----------------------
4534 bool LibraryCallKit::inline_arraycopy() {
4535   // Restore the stack and pop off the arguments.
4536   int nargs = 5;  // 2 oops, 3 ints, no size_t or long
4537   assert(callee()->signature()->size() == nargs, "copy has 5 arguments");
4538 
4539   Node *src         = argument(0);
4540   Node *src_offset  = argument(1);
4541   Node *dest        = argument(2);
4542   Node *dest_offset = argument(3);
4543   Node *length      = argument(4);
4544 
4545   // The following tests must be performed
4546   // (1) src and dest are arrays.
4547   // (2) src and dest arrays must have elements of the same BasicType
4548   // (3) src and dest must not be null.
4549   // (4) src_offset must not be negative.
4550   // (5) dest_offset must not be negative.
4551   // (6) length must not be negative.
4552   // (7) src_offset + length must not exceed length of src.
4553   // (8) dest_offset + length must not exceed length of dest.
4554   // (9) each element of an oop array must be assignable
4555 
4556   // (3) src and dest must not be null.
4557   // always do this here because we need the JVM state for uncommon traps
4558   _sp += nargs;
4559   src  = do_null_check(src,  T_ARRAY);
4560   dest = do_null_check(dest, T_ARRAY);
4561   _sp -= nargs;
4562 
4563   bool notest = false;
4564 
4565   if (!too_many_traps(Deoptimization::Reason_intrinsic) && !src->is_top() && !dest->is_top()) {
4566     // validate arguments: enables transformation the ArrayCopyNode
4567     notest = true;
4568 
4569     RegionNode* slow_region = new (C, 1) RegionNode(1);
4570     record_for_igvn(slow_region);
4571 
4572     // (1) src and dest are arrays.
4573     generate_non_array_guard(load_object_klass(src), slow_region);
4574     generate_non_array_guard(load_object_klass(dest), slow_region);
4575 
4576     // (2) src and dest arrays must have elements of the same BasicType
4577     // done at macro expansion or at Ideal transformation time
4578 
4579     // (4) src_offset must not be negative.
4580     generate_negative_guard(src_offset, slow_region);
4581 
4582     // (5) dest_offset must not be negative.
4583     generate_negative_guard(dest_offset, slow_region);
4584 
4585     // (7) src_offset + length must not exceed length of src.
4586     generate_limit_guard(src_offset, length,
4587                          load_array_length(src),
4588                          slow_region);
4589 
4590     // (8) dest_offset + length must not exceed length of dest.
4591     generate_limit_guard(dest_offset, length,
4592                          load_array_length(dest),
4593                          slow_region);
4594 
4595     // (9) each element of an oop array must be assignable
4596     Node* src_klass  = load_object_klass(src);
4597     Node* dest_klass = load_object_klass(dest);
4598     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
4599 
4600     if (not_subtype_ctrl != top()) {
4601       PreserveJVMState pjvms(this);
4602       set_control(not_subtype_ctrl);
4603       _sp += nargs;
4604       uncommon_trap(Deoptimization::Reason_intrinsic,
4605                     Deoptimization::Action_make_not_entrant);
4606       _sp -= nargs;
4607       assert(stopped(), "Should be stopped");
4608     }
4609     {
4610       PreserveJVMState pjvms(this);
4611       set_control(_gvn.transform(slow_region));
4612       _sp += nargs;
4613       uncommon_trap(Deoptimization::Reason_intrinsic,
4614                     Deoptimization::Action_make_not_entrant);
4615       _sp -= nargs;
4616       assert(stopped(), "Should be stopped");
4617     }
4618   }
4619 
4620   if (stopped()) {
4621     return true;
4622   }
4623 
4624   AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4625   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL);
4626 
4627   if (notest) {
4628     ac->set_arraycopy_notest();
4629   }
4630 
4631   Node* n = _gvn.transform(ac);
4632   assert(n == ac, "cannot disappear");
4633   ac->connect_outputs(this);
4634 
4635   return true;
4636 }
4637 
4638 
4639 // Helper function which determines if an arraycopy immediately follows
4640 // an allocation, with no intervening tests or other escapes for the object.
4641 AllocateArrayNode*
4642 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
4643                                            RegionNode* slow_region) {
4644   if (stopped())             return NULL;  // no fast path
4645   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
4646 
4647   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
4648   if (alloc == NULL)  return NULL;
4649 
4650   Node* rawmem = memory(Compile::AliasIdxRaw);
4651   // Is the allocation's memory state untouched?
4652   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
4653     // Bail out if there have been raw-memory effects since the allocation.
4654     // (Example:  There might have been a call or safepoint.)
4655     return NULL;
4656   }
4657   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
4658   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
4659     return NULL;
4660   }
4661 
4662   // There must be no unexpected observers of this allocation.
4663   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
4664     Node* obs = ptr->fast_out(i);
4665     if (obs != this->map()) {
4666       return NULL;
4667     }
4668   }
4669 
4670   // This arraycopy must unconditionally follow the allocation of the ptr.
4671   Node* alloc_ctl = ptr->in(0);
4672   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
4673 
4674   Node* ctl = control();
4675   while (ctl != alloc_ctl) {
4676     // There may be guards which feed into the slow_region.
4677     // Any other control flow means that we might not get a chance
4678     // to finish initializing the allocated object.
4679     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
4680       IfNode* iff = ctl->in(0)->as_If();
4681       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
4682       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
4683       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
4684         ctl = iff->in(0);       // This test feeds the known slow_region.
4685         continue;
4686       }
4687       // One more try:  Various low-level checks bottom out in
4688       // uncommon traps.  If the debug-info of the trap omits
4689       // any reference to the allocation, as we've already
4690       // observed, then there can be no objection to the trap.
4691       bool found_trap = false;
4692       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
4693         Node* obs = not_ctl->fast_out(j);
4694         if (obs->in(0) == not_ctl && obs->is_Call() &&
4695             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
4696           found_trap = true; break;
4697         }
4698       }
4699       if (found_trap) {
4700         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
4701         continue;
4702       }
4703     }
4704     return NULL;
4705   }
4706 
4707   // If we get this far, we have an allocation which immediately
4708   // precedes the arraycopy, and we can take over zeroing the new object.
4709   // The arraycopy will finish the initialization, and provide
4710   // a new control state to which we will anchor the destination pointer.
4711 
4712   return alloc;
4713 }
4714 
4715 //----------------------------inline_reference_get----------------------------
4716 
4717 bool LibraryCallKit::inline_reference_get() {
4718   const int nargs = 1; // self
4719 
4720   guarantee(java_lang_ref_Reference::referent_offset > 0,
4721             "should have already been set");
4722 
4723   int referent_offset = java_lang_ref_Reference::referent_offset;
4724 
4725   // Restore the stack and pop off the argument
4726   _sp += nargs;
4727   Node *reference_obj = pop();
4728 
4729   // Null check on self without removing any arguments.
4730   _sp += nargs;
4731   reference_obj = do_null_check(reference_obj, T_OBJECT);
4732   _sp -= nargs;;
4733 
4734   if (stopped()) return true;
4735 
4736   Node *adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
4737 
4738   ciInstanceKlass* klass = env()->Object_klass();
4739   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
4740 
4741   Node* no_ctrl = NULL;
4742   Node *result = make_load(no_ctrl, adr, object_type, T_OBJECT);
4743 
4744   // Use the pre-barrier to record the value in the referent field
4745   pre_barrier(false /* do_load */,
4746               control(),
4747               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
4748               result /* pre_val */,
4749               T_OBJECT);
4750 
4751   push(result);
4752   return true;
4753 }