< prev index next >

src/hotspot/share/opto/library_call.cpp

Print this page

   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 "asm/macroAssembler.hpp"



  26 #include "ci/ciSymbols.hpp"
  27 #include "ci/ciUtilities.inline.hpp"
  28 #include "classfile/vmIntrinsics.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "gc/shared/barrierSet.hpp"

  32 #include "jfr/support/jfrIntrinsics.hpp"
  33 #include "memory/resourceArea.hpp"

  34 #include "oops/klass.inline.hpp"

  35 #include "oops/objArrayKlass.hpp"
  36 #include "opto/addnode.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/c2compiler.hpp"
  39 #include "opto/castnode.hpp"
  40 #include "opto/cfgnode.hpp"
  41 #include "opto/convertnode.hpp"
  42 #include "opto/countbitsnode.hpp"

  43 #include "opto/idealKit.hpp"

  44 #include "opto/library_call.hpp"
  45 #include "opto/mathexactnode.hpp"
  46 #include "opto/mulnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/opaquenode.hpp"

  49 #include "opto/parse.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"

  53 #include "opto/vectornode.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "prims/jvmtiThreadState.hpp"
  56 #include "prims/unsafe.hpp"
  57 #include "runtime/jniHandles.inline.hpp"
  58 #include "runtime/objectMonitor.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/stubRoutines.hpp"

  61 #include "utilities/macros.hpp"
  62 #include "utilities/powerOfTwo.hpp"
  63 
  64 //---------------------------make_vm_intrinsic----------------------------
  65 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  66   vmIntrinsicID id = m->intrinsic_id();
  67   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  68 
  69   if (!m->is_loaded()) {
  70     // Do not attempt to inline unloaded methods.
  71     return nullptr;
  72   }
  73 
  74   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  75   bool is_available = false;
  76 
  77   {
  78     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  79     // the compiler must transition to '_thread_in_vm' state because both
  80     // methods access VM-internal data.

 301   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 302   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 303   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 304   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 305   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 306 
 307   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 308 
 309   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 310 
 311   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 312   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 313   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 314   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 315 
 316   case vmIntrinsics::_compressStringC:
 317   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 318   case vmIntrinsics::_inflateStringC:
 319   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 320 


 321   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 322   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 323   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 324   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 325   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 326   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 327   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 328   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 329   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);

 330 
 331   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 332   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 333   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 334   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 335   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 336   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 337   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 338   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 339   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);

 340 
 341   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 342   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 343   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 344   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 345   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 346   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 347   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 348   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 349   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 350 
 351   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 352   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 353   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 354   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 355   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 356   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 357   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 358   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 359   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);

 391   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 392   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 393   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 394   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 395   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 396   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 397   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 398   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 399   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 400 
 401   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 402   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 403   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 404   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 405   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 406   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 407   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 408   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 409   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 410 



 411   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 412   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 413   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 414   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 415   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 416 
 417   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 418   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 419   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 420   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 421   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 422   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 423   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 424   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 425   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 426   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 427   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 428   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 429   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 430   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);

 450   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 451   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 452   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 453 
 454   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 455   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 456   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 457   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 458 
 459   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 460   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 461   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 462   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 463   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 464 
 465   case vmIntrinsics::_loadFence:
 466   case vmIntrinsics::_storeFence:
 467   case vmIntrinsics::_storeStoreFence:
 468   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 469 




 470   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 471 
 472   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 473   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 474   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 475 
 476   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 477   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 478 
 479   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 480   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 481 
 482 #if INCLUDE_JVMTI
 483   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 484                                                                                          "notifyJvmtiStart", true, false);
 485   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 486                                                                                          "notifyJvmtiEnd", false, true);
 487   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 488                                                                                          "notifyJvmtiMount", false, false);
 489   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),

 498 #endif
 499   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 500   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 501   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 502   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 503   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 504   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 505   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 506   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 507   case vmIntrinsics::_getLength:                return inline_native_getLength();
 508   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 509   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 510   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 511   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 512   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 513   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 514   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 515 
 516   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 517   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);






 518 
 519   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 520 
 521   case vmIntrinsics::_isInstance:
 522   case vmIntrinsics::_isHidden:
 523   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 524 
 525   case vmIntrinsics::_floatToRawIntBits:
 526   case vmIntrinsics::_floatToIntBits:
 527   case vmIntrinsics::_intBitsToFloat:
 528   case vmIntrinsics::_doubleToRawLongBits:
 529   case vmIntrinsics::_doubleToLongBits:
 530   case vmIntrinsics::_longBitsToDouble:
 531   case vmIntrinsics::_floatToFloat16:
 532   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 533   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 534   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 535   case vmIntrinsics::_floatIsFinite:
 536   case vmIntrinsics::_floatIsInfinite:
 537   case vmIntrinsics::_doubleIsFinite:

2315     case vmIntrinsics::_remainderUnsigned_l: {
2316       zero_check_long(argument(2));
2317       // Compile-time detect of null-exception
2318       if (stopped()) {
2319         return true; // keep the graph constructed so far
2320       }
2321       n = new UModLNode(control(), argument(0), argument(2));
2322       break;
2323     }
2324     default:  fatal_unexpected_iid(id);  break;
2325   }
2326   set_result(_gvn.transform(n));
2327   return true;
2328 }
2329 
2330 //----------------------------inline_unsafe_access----------------------------
2331 
2332 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2333   // Attempt to infer a sharper value type from the offset and base type.
2334   ciKlass* sharpened_klass = nullptr;

2335 
2336   // See if it is an instance field, with an object type.
2337   if (alias_type->field() != nullptr) {
2338     if (alias_type->field()->type()->is_klass()) {
2339       sharpened_klass = alias_type->field()->type()->as_klass();

2340     }
2341   }
2342 
2343   const TypeOopPtr* result = nullptr;
2344   // See if it is a narrow oop array.
2345   if (adr_type->isa_aryptr()) {
2346     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2347       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();

2348       if (elem_type != nullptr && elem_type->is_loaded()) {
2349         // Sharpen the value type.
2350         result = elem_type;
2351       }
2352     }
2353   }
2354 
2355   // The sharpened class might be unloaded if there is no class loader
2356   // contraint in place.
2357   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2358     // Sharpen the value type.
2359     result = TypeOopPtr::make_from_klass(sharpened_klass);



2360   }
2361   if (result != nullptr) {
2362 #ifndef PRODUCT
2363     if (C->print_intrinsics() || C->print_inlining()) {
2364       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2365       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2366     }
2367 #endif
2368   }
2369   return result;
2370 }
2371 
2372 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2373   switch (kind) {
2374       case Relaxed:
2375         return MO_UNORDERED;
2376       case Opaque:
2377         return MO_RELAXED;
2378       case Acquire:
2379         return MO_ACQUIRE;

2411   _kit->jvms()->set_sp(_sp);
2412   _map->set_jvms(_kit->jvms());
2413   _kit->set_map(_map);
2414   _kit->set_sp(_sp);
2415   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2416     Node* out = _kit->control()->fast_out(i);
2417     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2418       _kit->_gvn.hash_delete(out);
2419       out->set_req(0, _kit->C->top());
2420       _kit->C->record_for_igvn(out);
2421       --i; --imax;
2422       _kit->_gvn.hash_find_insert(out);
2423     }
2424   }
2425 }
2426 
2427 void LibraryCallKit::SavedState::discard() {
2428   _discarded = true;
2429 }
2430 
2431 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2432   if (callee()->is_static())  return false;  // caller must have the capability!
2433   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2434   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2435   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2436   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2437 
2438   if (is_reference_type(type)) {
2439     decorators |= ON_UNKNOWN_OOP_REF;
2440   }
2441 
2442   if (unaligned) {
2443     decorators |= C2_UNALIGNED;
2444   }
2445 
2446 #ifndef PRODUCT
2447   {
2448     ResourceMark rm;
2449     // Check the signatures.
2450     ciSignature* sig = callee()->signature();
2451 #ifdef ASSERT
2452     if (!is_store) {
2453       // Object getReference(Object base, int/long offset), etc.
2454       BasicType rtype = sig->return_type()->basic_type();
2455       assert(rtype == type, "getter must return the expected value");
2456       assert(sig->count() == 2, "oop getter has 2 arguments");
2457       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2458       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2459     } else {
2460       // void putReference(Object base, int/long offset, Object x), etc.
2461       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2462       assert(sig->count() == 3, "oop putter has 3 arguments");
2463       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2464       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2465       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2466       assert(vtype == type, "putter must accept the expected value");
2467     }
2468 #endif // ASSERT
2469  }
2470 #endif //PRODUCT
2471 
2472   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2473 
2474   Node* receiver = argument(0);  // type: oop
2475 
2476   // Build address expression.
2477   Node* heap_base_oop = top();
2478 
2479   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2480   Node* base = argument(1);  // type: oop
2481   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2482   Node* offset = argument(2);  // type: long
2483   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2484   // to be plain byte offsets, which are also the same as those accepted
2485   // by oopDesc::field_addr.
2486   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2487          "fieldOffset must be byte-scaled");

















































2488   // 32-bit machines ignore the high half!
2489   offset = ConvL2X(offset);
2490 
2491   // Save state and restore on bailout
2492   SavedState old_state(this);
2493 
2494   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2495   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2496 
2497   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2498     if (type != T_OBJECT) {
2499       decorators |= IN_NATIVE; // off-heap primitive access
2500     } else {
2501       return false; // off-heap oop accesses are not supported
2502     }
2503   } else {
2504     heap_base_oop = base; // on-heap or mixed access
2505   }
2506 
2507   // Can base be null? Otherwise, always on-heap access.
2508   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2509 
2510   if (!can_access_non_heap) {
2511     decorators |= IN_HEAP;
2512   }
2513 
2514   Node* val = is_store ? argument(4) : nullptr;
2515 
2516   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2517   if (adr_type == TypePtr::NULL_PTR) {
2518     return false; // off-heap access with zero address
2519   }
2520 
2521   // Try to categorize the address.
2522   Compile::AliasType* alias_type = C->alias_type(adr_type);
2523   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2524 
2525   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2526       alias_type->adr_type() == TypeAryPtr::RANGE) {
2527     return false; // not supported
2528   }
2529 
2530   bool mismatched = false;
2531   BasicType bt = alias_type->basic_type();




























2532   if (bt != T_ILLEGAL) {
2533     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2534     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2535       // Alias type doesn't differentiate between byte[] and boolean[]).
2536       // Use address type to get the element type.
2537       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2538     }
2539     if (is_reference_type(bt, true)) {
2540       // accessing an array field with getReference is not a mismatch
2541       bt = T_OBJECT;
2542     }
2543     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2544       // Don't intrinsify mismatched object accesses
2545       return false;
2546     }
2547     mismatched = (bt != type);
2548   } else if (alias_type->adr_type()->isa_oopptr()) {
2549     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2550   }
2551 





















2552   old_state.discard();
2553   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2554 
2555   if (mismatched) {
2556     decorators |= C2_MISMATCHED;
2557   }
2558 
2559   // First guess at the value type.
2560   const Type *value_type = Type::get_const_basic_type(type);
2561 
2562   // Figure out the memory ordering.
2563   decorators |= mo_decorator_for_access_kind(kind);
2564 
2565   if (!is_store && type == T_OBJECT) {
2566     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2567     if (tjp != nullptr) {
2568       value_type = tjp;


2569     }
2570   }
2571 
2572   receiver = null_check(receiver);
2573   if (stopped()) {
2574     return true;
2575   }
2576   // Heap pointers get a null-check from the interpreter,
2577   // as a courtesy.  However, this is not guaranteed by Unsafe,
2578   // and it is not possible to fully distinguish unintended nulls
2579   // from intended ones in this API.
2580 
2581   if (!is_store) {
2582     Node* p = nullptr;
2583     // Try to constant fold a load from a constant field
2584     ciField* field = alias_type->field();
2585     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2586       // final or stable field
2587       p = make_constant_from_field(field, heap_base_oop);
2588     }
2589 
2590     if (p == nullptr) { // Could not constant fold the load
2591       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);









2592       // Normalize the value returned by getBoolean in the following cases
2593       if (type == T_BOOLEAN &&
2594           (mismatched ||
2595            heap_base_oop == top() ||                  // - heap_base_oop is null or
2596            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2597                                                       //   and the unsafe access is made to large offset
2598                                                       //   (i.e., larger than the maximum offset necessary for any
2599                                                       //   field access)
2600             ) {
2601           IdealKit ideal = IdealKit(this);
2602 #define __ ideal.
2603           IdealVariable normalized_result(ideal);
2604           __ declarations_done();
2605           __ set(normalized_result, p);
2606           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2607           __ set(normalized_result, ideal.ConI(1));
2608           ideal.end_if();
2609           final_sync(ideal);
2610           p = __ value(normalized_result);
2611 #undef __
2612       }
2613     }
2614     if (type == T_ADDRESS) {
2615       p = gvn().transform(new CastP2XNode(nullptr, p));
2616       p = ConvX2UL(p);
2617     }
2618     // The load node has the control of the preceding MemBarCPUOrder.  All
2619     // following nodes will have the control of the MemBarCPUOrder inserted at
2620     // the end of this method.  So, pushing the load onto the stack at a later
2621     // point is fine.
2622     set_result(p);
2623   } else {
2624     if (bt == T_ADDRESS) {
2625       // Repackage the long as a pointer.
2626       val = ConvL2X(val);
2627       val = gvn().transform(new CastX2PNode(val));
2628     }
2629     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);




2630   }
2631 
2632   return true;
2633 }
2634 











































































































































































































































2635 //----------------------------inline_unsafe_load_store----------------------------
2636 // This method serves a couple of different customers (depending on LoadStoreKind):
2637 //
2638 // LS_cmp_swap:
2639 //
2640 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2641 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2642 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2643 //
2644 // LS_cmp_swap_weak:
2645 //
2646 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2647 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2648 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2649 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2650 //
2651 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2652 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2653 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2654 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);

2817     }
2818     case LS_cmp_swap:
2819     case LS_cmp_swap_weak:
2820     case LS_get_add:
2821       break;
2822     default:
2823       ShouldNotReachHere();
2824   }
2825 
2826   // Null check receiver.
2827   receiver = null_check(receiver);
2828   if (stopped()) {
2829     return true;
2830   }
2831 
2832   int alias_idx = C->get_alias_index(adr_type);
2833 
2834   if (is_reference_type(type)) {
2835     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2836 













2837     // Transformation of a value which could be null pointer (CastPP #null)
2838     // could be delayed during Parse (for example, in adjust_map_after_if()).
2839     // Execute transformation here to avoid barrier generation in such case.
2840     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2841       newval = _gvn.makecon(TypePtr::NULL_PTR);
2842 
2843     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2844       // Refine the value to a null constant, when it is known to be null
2845       oldval = _gvn.makecon(TypePtr::NULL_PTR);
2846     }
2847   }
2848 
2849   Node* result = nullptr;
2850   switch (kind) {
2851     case LS_cmp_exchange: {
2852       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2853                                             oldval, newval, value_type, type, decorators);
2854       break;
2855     }
2856     case LS_cmp_swap_weak:

2885   insert_mem_bar(Op_MemBarCPUOrder);
2886   switch(id) {
2887     case vmIntrinsics::_loadFence:
2888       insert_mem_bar(Op_LoadFence);
2889       return true;
2890     case vmIntrinsics::_storeFence:
2891       insert_mem_bar(Op_StoreFence);
2892       return true;
2893     case vmIntrinsics::_storeStoreFence:
2894       insert_mem_bar(Op_StoreStoreFence);
2895       return true;
2896     case vmIntrinsics::_fullFence:
2897       insert_mem_bar(Op_MemBarVolatile);
2898       return true;
2899     default:
2900       fatal_unexpected_iid(id);
2901       return false;
2902   }
2903 }
2904 








































































2905 bool LibraryCallKit::inline_onspinwait() {
2906   insert_mem_bar(Op_OnSpinWait);
2907   return true;
2908 }
2909 
2910 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2911   if (!kls->is_Con()) {
2912     return true;
2913   }
2914   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2915   if (klsptr == nullptr) {
2916     return true;
2917   }
2918   ciInstanceKlass* ik = klsptr->instance_klass();
2919   // don't need a guard for a klass that is already initialized
2920   return !ik->is_initialized();
2921 }
2922 
2923 //----------------------------inline_unsafe_writeback0-------------------------
2924 // public native void Unsafe.writeback0(long address)

3003                     Deoptimization::Action_make_not_entrant);
3004     }
3005     if (stopped()) {
3006       return true;
3007     }
3008 #endif //INCLUDE_JVMTI
3009 
3010   Node* test = nullptr;
3011   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3012     // Note:  The argument might still be an illegal value like
3013     // Serializable.class or Object[].class.   The runtime will handle it.
3014     // But we must make an explicit check for initialization.
3015     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3016     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3017     // can generate code to load it as unsigned byte.
3018     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3019     Node* bits = intcon(InstanceKlass::fully_initialized);
3020     test = _gvn.transform(new SubINode(inst, bits));
3021     // The 'test' is non-zero if we need to take a slow path.
3022   }
3023 
3024   Node* obj = new_instance(kls, test);





3025   set_result(obj);
3026   return true;
3027 }
3028 
3029 //------------------------inline_native_time_funcs--------------
3030 // inline code for System.currentTimeMillis() and System.nanoTime()
3031 // these have the same type and signature
3032 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3033   const TypeFunc* tf = OptoRuntime::void_long_Type();
3034   const TypePtr* no_memory_effects = nullptr;
3035   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3036   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3037 #ifdef ASSERT
3038   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3039   assert(value_top == top(), "second value must be top");
3040 #endif
3041   set_result(value);
3042   return true;
3043 }
3044 

3785   Node* thread = _gvn.transform(new ThreadLocalNode());
3786   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3787   Node* thread_obj_handle
3788     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3789   thread_obj_handle = _gvn.transform(thread_obj_handle);
3790   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3791   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3792 
3793   // Change the _monitor_owner_id of the JavaThread
3794   Node* tid = load_field_from_object(arr, "tid", "J");
3795   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3796   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3797 
3798   JFR_ONLY(extend_setCurrentThread(thread, arr);)
3799   return true;
3800 }
3801 
3802 const Type* LibraryCallKit::scopedValueCache_type() {
3803   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3804   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3805   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3806 
3807   // Because we create the scopedValue cache lazily we have to make the
3808   // type of the result BotPTR.
3809   bool xk = etype->klass_is_exact();
3810   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3811   return objects_type;
3812 }
3813 
3814 Node* LibraryCallKit::scopedValueCache_helper() {
3815   Node* thread = _gvn.transform(new ThreadLocalNode());
3816   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3817   // We cannot use immutable_memory() because we might flip onto a
3818   // different carrier thread, at which point we'll need to use that
3819   // carrier thread's cache.
3820   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3821   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3822   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3823 }
3824 
3825 //------------------------inline_native_scopedValueCache------------------
3826 bool LibraryCallKit::inline_native_scopedValueCache() {
3827   Node* cache_obj_handle = scopedValueCache_helper();
3828   const Type* objects_type = scopedValueCache_type();
3829   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3830 

3914   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3915 
3916   // Result of top level CFG and Memory.
3917   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3918   record_for_igvn(result_rgn);
3919   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3920   record_for_igvn(result_mem);
3921 
3922   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
3923   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
3924   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3925   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3926 
3927   // Set output state.
3928   set_control(_gvn.transform(result_rgn));
3929   set_all_memory(_gvn.transform(result_mem));
3930 
3931   return true;
3932 }
3933 
3934 //---------------------------load_mirror_from_klass----------------------------
3935 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3936 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3937   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3938   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3939   // mirror = ((OopHandle)mirror)->resolve();
3940   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3941 }
3942 
3943 //-----------------------load_klass_from_mirror_common-------------------------
3944 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3945 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3946 // and branch to the given path on the region.
3947 // If never_see_null, take an uncommon trap on null, so we can optimistically
3948 // compile for the non-null case.
3949 // If the region is null, force never_see_null = true.
3950 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3951                                                     bool never_see_null,
3952                                                     RegionNode* region,
3953                                                     int null_path,
3954                                                     int offset) {
3955   if (region == nullptr)  never_see_null = true;
3956   Node* p = basic_plus_adr(mirror, offset);
3957   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3958   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3959   Node* null_ctl = top();
3960   kls = null_check_oop(kls, &null_ctl, never_see_null);
3961   if (region != nullptr) {
3962     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).

3966   }
3967   return kls;
3968 }
3969 
3970 //--------------------(inline_native_Class_query helpers)---------------------
3971 // Use this for JVM_ACC_INTERFACE.
3972 // Fall through if (mods & mask) == bits, take the guard otherwise.
3973 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3974                                                  ByteSize offset, const Type* type, BasicType bt) {
3975   // Branch around if the given klass has the given modifier bit set.
3976   // Like generate_guard, adds a new path onto the region.
3977   Node* modp = basic_plus_adr(kls, in_bytes(offset));
3978   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3979   Node* mask = intcon(modifier_mask);
3980   Node* bits = intcon(modifier_bits);
3981   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3982   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3983   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3984   return generate_fair_guard(bol, region);
3985 }

3986 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3987   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3988                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3989 }
3990 
3991 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3992 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3993   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3994                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3995 }
3996 
3997 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3998   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3999 }
4000 
4001 //-------------------------inline_native_Class_query-------------------
4002 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4003   const Type* return_type = TypeInt::BOOL;
4004   Node* prim_return_value = top();  // what happens if it's a primitive class?
4005   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);

4087       phi->add_req(intcon(1));
4088     // If we fall through, it's a plain class.
4089     query_value = intcon(0);
4090     break;
4091 
4092 
4093   case vmIntrinsics::_getSuperclass:
4094     // The rules here are somewhat unfortunate, but we can still do better
4095     // with random logic than with a JNI call.
4096     // Interfaces store null or Object as _super, but must report null.
4097     // Arrays store an intermediate super as _super, but must report Object.
4098     // Other types can report the actual _super.
4099     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4100     if (generate_interface_guard(kls, region) != nullptr)
4101       // A guard was added.  If the guard is taken, it was an interface.
4102       phi->add_req(null());
4103     if (generate_array_guard(kls, region) != nullptr)
4104       // A guard was added.  If the guard is taken, it was an array.
4105       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4106     // If we fall through, it's a plain class.  Get its _super.
4107     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4108     kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4109     null_ctl = top();
4110     kls = null_check_oop(kls, &null_ctl);
4111     if (null_ctl != top()) {
4112       // If the guard is taken, Object.superClass is null (both klass and mirror).
4113       region->add_req(null_ctl);
4114       phi   ->add_req(null());
4115     }
4116     if (!stopped()) {
4117       query_value = load_mirror_from_klass(kls);











4118     }
4119     break;
4120 
4121   default:
4122     fatal_unexpected_iid(id);
4123     break;
4124   }
4125 
4126   // Fall-through is the normal case of a query to a real class.
4127   phi->init_req(1, query_value);
4128   region->init_req(1, control());
4129 
4130   C->set_has_split_ifs(true); // Has chance for split-if optimization
4131   set_result(region, phi);
4132   return true;
4133 }
4134 

4135 //-------------------------inline_Class_cast-------------------
4136 bool LibraryCallKit::inline_Class_cast() {
4137   Node* mirror = argument(0); // Class
4138   Node* obj    = argument(1);
4139   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4140   if (mirror_con == nullptr) {
4141     return false;  // dead path (mirror->is_top()).
4142   }
4143   if (obj == nullptr || obj->is_top()) {
4144     return false;  // dead path
4145   }
4146   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4147 
4148   // First, see if Class.cast() can be folded statically.
4149   // java_mirror_type() returns non-null for compile-time Class constants.
4150   ciType* tm = mirror_con->java_mirror_type();
4151   if (tm != nullptr && tm->is_klass() &&
4152       tp != nullptr) {
4153     if (!tp->is_loaded()) {
4154       // Don't use intrinsic when class is not loaded.
4155       return false;
4156     } else {
4157       int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());

4158       if (static_res == Compile::SSC_always_true) {
4159         // isInstance() is true - fold the code.
4160         set_result(obj);
4161         return true;
4162       } else if (static_res == Compile::SSC_always_false) {
4163         // Don't use intrinsic, have to throw ClassCastException.
4164         // If the reference is null, the non-intrinsic bytecode will
4165         // be optimized appropriately.
4166         return false;
4167       }
4168     }
4169   }
4170 
4171   // Bailout intrinsic and do normal inlining if exception path is frequent.
4172   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4173     return false;
4174   }
4175 
4176   // Generate dynamic checks.
4177   // Class.cast() is java implementation of _checkcast bytecode.
4178   // Do checkcast (Parse::do_checkcast()) optimizations here.
4179 
4180   mirror = null_check(mirror);
4181   // If mirror is dead, only null-path is taken.
4182   if (stopped()) {
4183     return true;
4184   }
4185 
4186   // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4187   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4188   RegionNode* region = new RegionNode(PATH_LIMIT);
4189   record_for_igvn(region);
4190 
4191   // Now load the mirror's klass metaobject, and null-check it.
4192   // If kls is null, we have a primitive mirror and
4193   // nothing is an instance of a primitive type.
4194   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4195 
4196   Node* res = top();


4197   if (!stopped()) {

4198     Node* bad_type_ctrl = top();
4199     // Do checkcast optimizations.
4200     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4201     region->init_req(_bad_type_path, bad_type_ctrl);
4202   }
4203   if (region->in(_prim_path) != top() ||
4204       region->in(_bad_type_path) != top()) {

4205     // Let Interpreter throw ClassCastException.
4206     PreserveJVMState pjvms(this);
4207     set_control(_gvn.transform(region));



4208     uncommon_trap(Deoptimization::Reason_intrinsic,
4209                   Deoptimization::Action_maybe_recompile);
4210   }
4211   if (!stopped()) {
4212     set_result(res);
4213   }
4214   return true;
4215 }
4216 
4217 
4218 //--------------------------inline_native_subtype_check------------------------
4219 // This intrinsic takes the JNI calls out of the heart of
4220 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4221 bool LibraryCallKit::inline_native_subtype_check() {
4222   // Pull both arguments off the stack.
4223   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4224   args[0] = argument(0);
4225   args[1] = argument(1);
4226   Node* klasses[2];             // corresponding Klasses: superk, subk
4227   klasses[0] = klasses[1] = top();
4228 
4229   enum {
4230     // A full decision tree on {superc is prim, subc is prim}:
4231     _prim_0_path = 1,           // {P,N} => false
4232                                 // {P,P} & superc!=subc => false
4233     _prim_same_path,            // {P,P} & superc==subc => true
4234     _prim_1_path,               // {N,P} => false
4235     _ref_subtype_path,          // {N,N} & subtype check wins => true
4236     _both_ref_path,             // {N,N} & subtype check loses => false
4237     PATH_LIMIT
4238   };
4239 
4240   RegionNode* region = new RegionNode(PATH_LIMIT);

4241   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4242   record_for_igvn(region);

4243 
4244   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4245   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4246   int class_klass_offset = java_lang_Class::klass_offset();
4247 
4248   // First null-check both mirrors and load each mirror's klass metaobject.
4249   int which_arg;
4250   for (which_arg = 0; which_arg <= 1; which_arg++) {
4251     Node* arg = args[which_arg];
4252     arg = null_check(arg);
4253     if (stopped())  break;
4254     args[which_arg] = arg;
4255 
4256     Node* p = basic_plus_adr(arg, class_klass_offset);
4257     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4258     klasses[which_arg] = _gvn.transform(kls);
4259   }
4260 
4261   // Having loaded both klasses, test each for null.
4262   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4263   for (which_arg = 0; which_arg <= 1; which_arg++) {
4264     Node* kls = klasses[which_arg];
4265     Node* null_ctl = top();
4266     kls = null_check_oop(kls, &null_ctl, never_see_null);
4267     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4268     region->init_req(prim_path, null_ctl);



4269     if (stopped())  break;
4270     klasses[which_arg] = kls;
4271   }
4272 
4273   if (!stopped()) {
4274     // now we have two reference types, in klasses[0..1]
4275     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4276     Node* superk = klasses[0];  // the receiver
4277     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4278     // now we have a successful reference subtype check
4279     region->set_req(_ref_subtype_path, control());
4280   }
4281 
4282   // If both operands are primitive (both klasses null), then
4283   // we must return true when they are identical primitives.
4284   // It is convenient to test this after the first null klass check.
4285   set_control(region->in(_prim_0_path)); // go back to first null check

4286   if (!stopped()) {
4287     // Since superc is primitive, make a guard for the superc==subc case.
4288     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4289     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4290     generate_guard(bol_eq, region, PROB_FAIR);
4291     if (region->req() == PATH_LIMIT+1) {
4292       // A guard was added.  If the added guard is taken, superc==subc.
4293       region->swap_edges(PATH_LIMIT, _prim_same_path);
4294       region->del_req(PATH_LIMIT);
4295     }
4296     region->set_req(_prim_0_path, control()); // Not equal after all.
4297   }
4298 
4299   // these are the only paths that produce 'true':
4300   phi->set_req(_prim_same_path,   intcon(1));
4301   phi->set_req(_ref_subtype_path, intcon(1));
4302 
4303   // pull together the cases:
4304   assert(region->req() == PATH_LIMIT, "sane region");
4305   for (uint i = 1; i < region->req(); i++) {
4306     Node* ctl = region->in(i);
4307     if (ctl == nullptr || ctl == top()) {
4308       region->set_req(i, top());
4309       phi   ->set_req(i, top());
4310     } else if (phi->in(i) == nullptr) {
4311       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4312     }
4313   }
4314 
4315   set_control(_gvn.transform(region));
4316   set_result(_gvn.transform(phi));
4317   return true;
4318 }
4319 
4320 //---------------------generate_array_guard_common------------------------
4321 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4322                                                   bool obj_array, bool not_array, Node** obj) {
4323 
4324   if (stopped()) {
4325     return nullptr;
4326   }
4327 
4328   // If obj_array/non_array==false/false:
4329   // Branch around if the given klass is in fact an array (either obj or prim).
4330   // If obj_array/non_array==false/true:
4331   // Branch around if the given klass is not an array klass of any kind.
4332   // If obj_array/non_array==true/true:
4333   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4334   // If obj_array/non_array==true/false:
4335   // Branch around if the kls is an oop array (Object[] or subtype)
4336   //
4337   // Like generate_guard, adds a new path onto the region.
4338   jint  layout_con = 0;
4339   Node* layout_val = get_layout_helper(kls, layout_con);
4340   if (layout_val == nullptr) {
4341     bool query = (obj_array
4342                   ? Klass::layout_helper_is_objArray(layout_con)
4343                   : Klass::layout_helper_is_array(layout_con));
4344     if (query == not_array) {







4345       return nullptr;                       // never a branch
4346     } else {                             // always a branch
4347       Node* always_branch = control();
4348       if (region != nullptr)
4349         region->add_req(always_branch);
4350       set_control(top());
4351       return always_branch;
4352     }
4353   }





















4354   // Now test the correct condition.
4355   jint  nval = (obj_array
4356                 ? (jint)(Klass::_lh_array_tag_type_value
4357                    <<    Klass::_lh_array_tag_shift)
4358                 : Klass::_lh_neutral_value);
4359   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4360   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
4361   // invert the test if we are looking for a non-array
4362   if (not_array)  btest = BoolTest(btest).negate();
4363   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4364   Node* ctrl = generate_fair_guard(bol, region);
4365   Node* is_array_ctrl = not_array ? control() : ctrl;
4366   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4367     // Keep track of the fact that 'obj' is an array to prevent
4368     // array specific accesses from floating above the guard.
4369     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4370   }
4371   return ctrl;
4372 }
4373 



































































































































4374 
4375 //-----------------------inline_native_newArray--------------------------
4376 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4377 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4378 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4379   Node* mirror;
4380   Node* count_val;
4381   if (uninitialized) {
4382     null_check_receiver();
4383     mirror    = argument(1);
4384     count_val = argument(2);
4385   } else {
4386     mirror    = argument(0);
4387     count_val = argument(1);
4388   }
4389 
4390   mirror = null_check(mirror);
4391   // If mirror or obj is dead, only null-path is taken.
4392   if (stopped())  return true;
4393 
4394   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4395   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4396   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);

4414     CallJavaNode* slow_call = nullptr;
4415     if (uninitialized) {
4416       // Generate optimized virtual call (holder class 'Unsafe' is final)
4417       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4418     } else {
4419       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4420     }
4421     Node* slow_result = set_results_for_java_call(slow_call);
4422     // this->control() comes from set_results_for_java_call
4423     result_reg->set_req(_slow_path, control());
4424     result_val->set_req(_slow_path, slow_result);
4425     result_io ->set_req(_slow_path, i_o());
4426     result_mem->set_req(_slow_path, reset_memory());
4427   }
4428 
4429   set_control(normal_ctl);
4430   if (!stopped()) {
4431     // Normal case:  The array type has been cached in the java.lang.Class.
4432     // The following call works fine even if the array type is polymorphic.
4433     // It could be a dynamic mix of int[], boolean[], Object[], etc.



4434     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4435     result_reg->init_req(_normal_path, control());
4436     result_val->init_req(_normal_path, obj);
4437     result_io ->init_req(_normal_path, i_o());
4438     result_mem->init_req(_normal_path, reset_memory());
4439 
4440     if (uninitialized) {
4441       // Mark the allocation so that zeroing is skipped
4442       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4443       alloc->maybe_set_complete(&_gvn);
4444     }
4445   }
4446 
4447   // Return the combined state.
4448   set_i_o(        _gvn.transform(result_io)  );
4449   set_all_memory( _gvn.transform(result_mem));
4450 
4451   C->set_has_split_ifs(true); // Has chance for split-if optimization
4452   set_result(result_reg, result_val);
4453   return true;

4502   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4503   { PreserveReexecuteState preexecs(this);
4504     jvms()->set_should_reexecute(true);
4505 
4506     array_type_mirror = null_check(array_type_mirror);
4507     original          = null_check(original);
4508 
4509     // Check if a null path was taken unconditionally.
4510     if (stopped())  return true;
4511 
4512     Node* orig_length = load_array_length(original);
4513 
4514     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4515     klass_node = null_check(klass_node);
4516 
4517     RegionNode* bailout = new RegionNode(1);
4518     record_for_igvn(bailout);
4519 
4520     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4521     // Bail out if that is so.
4522     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);















4523     if (not_objArray != nullptr) {
4524       // Improve the klass node's type from the new optimistic assumption:
4525       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4526       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4527       Node* cast = new CastPPNode(control(), klass_node, akls);
4528       klass_node = _gvn.transform(cast);
4529     }
4530 
4531     // Bail out if either start or end is negative.
4532     generate_negative_guard(start, bailout, &start);
4533     generate_negative_guard(end,   bailout, &end);
4534 
4535     Node* length = end;
4536     if (_gvn.type(start) != TypeInt::ZERO) {
4537       length = _gvn.transform(new SubINode(end, start));
4538     }
4539 
4540     // Bail out if length is negative (i.e., if start > end).
4541     // Without this the new_array would throw
4542     // NegativeArraySizeException but IllegalArgumentException is what
4543     // should be thrown
4544     generate_negative_guard(length, bailout, &length);
4545 







































4546     // Bail out if start is larger than the original length
4547     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4548     generate_negative_guard(orig_tail, bailout, &orig_tail);
4549 
4550     if (bailout->req() > 1) {
4551       PreserveJVMState pjvms(this);
4552       set_control(_gvn.transform(bailout));
4553       uncommon_trap(Deoptimization::Reason_intrinsic,
4554                     Deoptimization::Action_maybe_recompile);
4555     }
4556 
4557     if (!stopped()) {
4558       // How many elements will we copy from the original?
4559       // The answer is MinI(orig_tail, length).
4560       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4561 
4562       // Generate a direct call to the right arraycopy function(s).
4563       // We know the copy is disjoint but we might not know if the
4564       // oop stores need checking.
4565       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).

4571       // to the copyOf to be validated, including that the copy to the
4572       // new array won't trigger an ArrayStoreException. That subtype
4573       // check can be optimized if we know something on the type of
4574       // the input array from type speculation.
4575       if (_gvn.type(klass_node)->singleton()) {
4576         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4577         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4578 
4579         int test = C->static_subtype_check(superk, subk);
4580         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4581           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4582           if (t_original->speculative_type() != nullptr) {
4583             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4584           }
4585         }
4586       }
4587 
4588       bool validated = false;
4589       // Reason_class_check rather than Reason_intrinsic because we
4590       // want to intrinsify even if this traps.
4591       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4592         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4593 
4594         if (not_subtype_ctrl != top()) {
4595           PreserveJVMState pjvms(this);
4596           set_control(not_subtype_ctrl);
4597           uncommon_trap(Deoptimization::Reason_class_check,
4598                         Deoptimization::Action_make_not_entrant);
4599           assert(stopped(), "Should be stopped");
4600         }
4601         validated = true;
4602       }
4603 
4604       if (!stopped()) {
4605         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4606 
4607         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4608                                                 load_object_klass(original), klass_node);
4609         if (!is_copyOfRange) {
4610           ac->set_copyof(validated);
4611         } else {
4612           ac->set_copyofrange(validated);
4613         }
4614         Node* n = _gvn.transform(ac);
4615         if (n == ac) {
4616           ac->connect_outputs(this);
4617         } else {
4618           assert(validated, "shouldn't transform if all arguments not validated");
4619           set_all_memory(n);
4620         }
4621       }
4622     }
4623   } // original reexecute is set back here
4624 
4625   C->set_has_split_ifs(true); // Has chance for split-if optimization

4657 
4658 //-----------------------generate_method_call----------------------------
4659 // Use generate_method_call to make a slow-call to the real
4660 // method if the fast path fails.  An alternative would be to
4661 // use a stub like OptoRuntime::slow_arraycopy_Java.
4662 // This only works for expanding the current library call,
4663 // not another intrinsic.  (E.g., don't use this for making an
4664 // arraycopy call inside of the copyOf intrinsic.)
4665 CallJavaNode*
4666 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4667   // When compiling the intrinsic method itself, do not use this technique.
4668   guarantee(callee() != C->method(), "cannot make slow-call to self");
4669 
4670   ciMethod* method = callee();
4671   // ensure the JVMS we have will be correct for this call
4672   guarantee(method_id == method->intrinsic_id(), "must match");
4673 
4674   const TypeFunc* tf = TypeFunc::make(method);
4675   if (res_not_null) {
4676     assert(tf->return_type() == T_OBJECT, "");
4677     const TypeTuple* range = tf->range();
4678     const Type** fields = TypeTuple::fields(range->cnt());
4679     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4680     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4681     tf = TypeFunc::make(tf->domain(), new_range);
4682   }
4683   CallJavaNode* slow_call;
4684   if (is_static) {
4685     assert(!is_virtual, "");
4686     slow_call = new CallStaticJavaNode(C, tf,
4687                            SharedRuntime::get_resolve_static_call_stub(), method);
4688   } else if (is_virtual) {
4689     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4690     int vtable_index = Method::invalid_vtable_index;
4691     if (UseInlineCaches) {
4692       // Suppress the vtable call
4693     } else {
4694       // hashCode and clone are not a miranda methods,
4695       // so the vtable index is fixed.
4696       // No need to use the linkResolver to get it.
4697        vtable_index = method->vtable_index();
4698        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4699               "bad index %d", vtable_index);
4700     }
4701     slow_call = new CallDynamicJavaNode(tf,

4718   set_edges_for_java_call(slow_call);
4719   return slow_call;
4720 }
4721 
4722 
4723 /**
4724  * Build special case code for calls to hashCode on an object. This call may
4725  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4726  * slightly different code.
4727  */
4728 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4729   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4730   assert(!(is_virtual && is_static), "either virtual, special, or static");
4731 
4732   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4733 
4734   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4735   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4736   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4737   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4738   Node* obj = nullptr;







4739   if (!is_static) {
4740     // Check for hashing null object
4741     obj = null_check_receiver();
4742     if (stopped())  return true;        // unconditionally null
4743     result_reg->init_req(_null_path, top());
4744     result_val->init_req(_null_path, top());
4745   } else {
4746     // Do a null check, and return zero if null.
4747     // System.identityHashCode(null) == 0
4748     obj = argument(0);
4749     Node* null_ctl = top();
4750     obj = null_check_oop(obj, &null_ctl);
4751     result_reg->init_req(_null_path, null_ctl);
4752     result_val->init_req(_null_path, _gvn.intcon(0));
4753   }
4754 
4755   // Unconditionally null?  Then return right away.
4756   if (stopped()) {
4757     set_control( result_reg->in(_null_path));
4758     if (!stopped())
4759       set_result(result_val->in(_null_path));
4760     return true;
4761   }
4762 
4763   // We only go to the fast case code if we pass a number of guards.  The
4764   // paths which do not pass are accumulated in the slow_region.
4765   RegionNode* slow_region = new RegionNode(1);
4766   record_for_igvn(slow_region);
4767 
4768   // If this is a virtual call, we generate a funny guard.  We pull out
4769   // the vtable entry corresponding to hashCode() from the target object.
4770   // If the target method which we are calling happens to be the native
4771   // Object hashCode() method, we pass the guard.  We do not need this
4772   // guard for non-virtual calls -- the caller is known to be the native
4773   // Object hashCode().
4774   if (is_virtual) {
4775     // After null check, get the object's klass.
4776     Node* obj_klass = load_object_klass(obj);
4777     generate_virtual_guard(obj_klass, slow_region);
4778   }
4779 
4780   // Get the header out of the object, use LoadMarkNode when available
4781   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4782   // The control of the load must be null. Otherwise, the load can move before
4783   // the null check after castPP removal.
4784   Node* no_ctrl = nullptr;
4785   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4786 
4787   if (!UseObjectMonitorTable) {
4788     // Test the header to see if it is safe to read w.r.t. locking.


4789     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
4790     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4791     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
4792     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4793     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4794 
4795     generate_slow_guard(test_monitor, slow_region);
4796   }
4797 
4798   // Get the hash value and check to see that it has been properly assigned.
4799   // We depend on hash_mask being at most 32 bits and avoid the use of
4800   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4801   // vm: see markWord.hpp.
4802   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
4803   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
4804   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4805   // This hack lets the hash bits live anywhere in the mark object now, as long
4806   // as the shift drops the relevant bits into the low 32 bits.  Note that
4807   // Java spec says that HashCode is an int so there's no point in capturing
4808   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).

4836     // this->control() comes from set_results_for_java_call
4837     result_reg->init_req(_slow_path, control());
4838     result_val->init_req(_slow_path, slow_result);
4839     result_io  ->set_req(_slow_path, i_o());
4840     result_mem ->set_req(_slow_path, reset_memory());
4841   }
4842 
4843   // Return the combined state.
4844   set_i_o(        _gvn.transform(result_io)  );
4845   set_all_memory( _gvn.transform(result_mem));
4846 
4847   set_result(result_reg, result_val);
4848   return true;
4849 }
4850 
4851 //---------------------------inline_native_getClass----------------------------
4852 // public final native Class<?> java.lang.Object.getClass();
4853 //
4854 // Build special case code for calls to getClass on an object.
4855 bool LibraryCallKit::inline_native_getClass() {
4856   Node* obj = null_check_receiver();









4857   if (stopped())  return true;
4858   set_result(load_mirror_from_klass(load_object_klass(obj)));
4859   return true;
4860 }
4861 
4862 //-----------------inline_native_Reflection_getCallerClass---------------------
4863 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4864 //
4865 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4866 //
4867 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4868 // in that it must skip particular security frames and checks for
4869 // caller sensitive methods.
4870 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4871 #ifndef PRODUCT
4872   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4873     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4874   }
4875 #endif
4876 

5258 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5259 //
5260 // The general case has two steps, allocation and copying.
5261 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5262 //
5263 // Copying also has two cases, oop arrays and everything else.
5264 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5265 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5266 //
5267 // These steps fold up nicely if and when the cloned object's klass
5268 // can be sharply typed as an object array, a type array, or an instance.
5269 //
5270 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5271   PhiNode* result_val;
5272 
5273   // Set the reexecute bit for the interpreter to reexecute
5274   // the bytecode that invokes Object.clone if deoptimization happens.
5275   { PreserveReexecuteState preexecs(this);
5276     jvms()->set_should_reexecute(true);
5277 
5278     Node* obj = null_check_receiver();

5279     if (stopped())  return true;
5280 
5281     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();






5282 
5283     // If we are going to clone an instance, we need its exact type to
5284     // know the number and types of fields to convert the clone to
5285     // loads/stores. Maybe a speculative type can help us.
5286     if (!obj_type->klass_is_exact() &&
5287         obj_type->speculative_type() != nullptr &&
5288         obj_type->speculative_type()->is_instance_klass()) {

5289       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5290       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5291           !spec_ik->has_injected_fields()) {
5292         if (!obj_type->isa_instptr() ||
5293             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5294           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5295         }
5296       }
5297     }
5298 
5299     // Conservatively insert a memory barrier on all memory slices.
5300     // Do not let writes into the original float below the clone.
5301     insert_mem_bar(Op_MemBarCPUOrder);
5302 
5303     // paths into result_reg:
5304     enum {
5305       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5306       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5307       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5308       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5309       PATH_LIMIT
5310     };
5311     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5312     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5313     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5314     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5315     record_for_igvn(result_reg);
5316 
5317     Node* obj_klass = load_object_klass(obj);





5318     Node* array_obj = obj;
5319     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5320     if (array_ctl != nullptr) {
5321       // It's an array.
5322       PreserveJVMState pjvms(this);
5323       set_control(array_ctl);
5324       Node* obj_length = load_array_length(array_obj);
5325       Node* array_size = nullptr; // Size of the array without object alignment padding.
5326       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5327 
5328       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5329       if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5330         // If it is an oop array, it requires very special treatment,
5331         // because gc barriers are required when accessing the array.
5332         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5333         if (is_obja != nullptr) {
5334           PreserveJVMState pjvms2(this);
5335           set_control(is_obja);
5336           // Generate a direct call to the right arraycopy function(s).
5337           // Clones are always tightly coupled.
5338           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5339           ac->set_clone_oop_array();
5340           Node* n = _gvn.transform(ac);
5341           assert(n == ac, "cannot disappear");
5342           ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5343 
5344           result_reg->init_req(_objArray_path, control());
5345           result_val->init_req(_objArray_path, alloc_obj);
5346           result_i_o ->set_req(_objArray_path, i_o());
5347           result_mem ->set_req(_objArray_path, reset_memory());
5348         }
5349       }
5350       // Otherwise, there are no barriers to worry about.
5351       // (We can dispense with card marks if we know the allocation
5352       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5353       //  causes the non-eden paths to take compensating steps to
5354       //  simulate a fresh allocation, so that no further
5355       //  card marks are required in compiled code to initialize
5356       //  the object.)
5357 
5358       if (!stopped()) {
5359         copy_to_clone(array_obj, alloc_obj, array_size, true);
5360 
5361         // Present the results of the copy.
5362         result_reg->init_req(_array_path, control());
5363         result_val->init_req(_array_path, alloc_obj);
5364         result_i_o ->set_req(_array_path, i_o());
5365         result_mem ->set_req(_array_path, reset_memory());




































5366       }
5367     }
5368 
5369     // We only go to the instance fast case code if we pass a number of guards.
5370     // The paths which do not pass are accumulated in the slow_region.
5371     RegionNode* slow_region = new RegionNode(1);
5372     record_for_igvn(slow_region);
5373     if (!stopped()) {
5374       // It's an instance (we did array above).  Make the slow-path tests.
5375       // If this is a virtual call, we generate a funny guard.  We grab
5376       // the vtable entry corresponding to clone() from the target object.
5377       // If the target method which we are calling happens to be the
5378       // Object clone() method, we pass the guard.  We do not need this
5379       // guard for non-virtual calls; the caller is known to be the native
5380       // Object clone().
5381       if (is_virtual) {
5382         generate_virtual_guard(obj_klass, slow_region);
5383       }
5384 
5385       // The object must be easily cloneable and must not have a finalizer.
5386       // Both of these conditions may be checked in a single test.
5387       // We could optimize the test further, but we don't care.
5388       generate_misc_flags_guard(obj_klass,
5389                                 // Test both conditions:
5390                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5391                                 // Must be cloneable but not finalizer:
5392                                 KlassFlags::_misc_is_cloneable_fast,

5484         set_jvms(sfpt->jvms());
5485         _reexecute_sp = jvms()->sp();
5486 
5487         return saved_jvms;
5488       }
5489     }
5490   }
5491   return nullptr;
5492 }
5493 
5494 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5495 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5496 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5497   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5498   uint size = alloc->req();
5499   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5500   old_jvms->set_map(sfpt);
5501   for (uint i = 0; i < size; i++) {
5502     sfpt->init_req(i, alloc->in(i));
5503   }












5504   // re-push array length for deoptimization
5505   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5506   old_jvms->set_sp(old_jvms->sp()+1);
5507   old_jvms->set_monoff(old_jvms->monoff()+1);
5508   old_jvms->set_scloff(old_jvms->scloff()+1);
5509   old_jvms->set_endoff(old_jvms->endoff()+1);











5510   old_jvms->set_should_reexecute(true);
5511 
5512   sfpt->set_i_o(map()->i_o());
5513   sfpt->set_memory(map()->memory());
5514   sfpt->set_control(map()->control());
5515   return sfpt;
5516 }
5517 
5518 // In case of a deoptimization, we restart execution at the
5519 // allocation, allocating a new array. We would leave an uninitialized
5520 // array in the heap that GCs wouldn't expect. Move the allocation
5521 // after the traps so we don't allocate the array if we
5522 // deoptimize. This is possible because tightly_coupled_allocation()
5523 // guarantees there's no observer of the allocated array at this point
5524 // and the control flow is simple enough.
5525 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5526                                                     int saved_reexecute_sp, uint new_idx) {
5527   if (saved_jvms_before_guards != nullptr && !stopped()) {
5528     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5529 
5530     assert(alloc != nullptr, "only with a tightly coupled allocation");
5531     // restore JVM state to the state at the arraycopy
5532     saved_jvms_before_guards->map()->set_control(map()->control());
5533     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5534     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5535     // If we've improved the types of some nodes (null check) while
5536     // emitting the guards, propagate them to the current state
5537     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5538     set_jvms(saved_jvms_before_guards);
5539     _reexecute_sp = saved_reexecute_sp;
5540 
5541     // Remove the allocation from above the guards
5542     CallProjections callprojs;
5543     alloc->extract_projections(&callprojs, true);
5544     InitializeNode* init = alloc->initialization();
5545     Node* alloc_mem = alloc->in(TypeFunc::Memory);
5546     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5547     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5548 
5549     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5550     // the allocation (i.e. is only valid if the allocation succeeds):
5551     // 1) replace CastIINode with AllocateArrayNode's length here
5552     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5553     //
5554     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5555     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5556     Node* init_control = init->proj_out(TypeFunc::Control);
5557     Node* alloc_length = alloc->Ideal_length();
5558 #ifdef ASSERT
5559     Node* prev_cast = nullptr;
5560 #endif
5561     for (uint i = 0; i < init_control->outcnt(); i++) {
5562       Node* init_out = init_control->raw_out(i);
5563       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5564 #ifdef ASSERT
5565         if (prev_cast == nullptr) {
5566           prev_cast = init_out;

5568           if (prev_cast->cmp(*init_out) == false) {
5569             prev_cast->dump();
5570             init_out->dump();
5571             assert(false, "not equal CastIINode");
5572           }
5573         }
5574 #endif
5575         C->gvn_replace_by(init_out, alloc_length);
5576       }
5577     }
5578     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5579 
5580     // move the allocation here (after the guards)
5581     _gvn.hash_delete(alloc);
5582     alloc->set_req(TypeFunc::Control, control());
5583     alloc->set_req(TypeFunc::I_O, i_o());
5584     Node *mem = reset_memory();
5585     set_all_memory(mem);
5586     alloc->set_req(TypeFunc::Memory, mem);
5587     set_control(init->proj_out_or_null(TypeFunc::Control));
5588     set_i_o(callprojs.fallthrough_ioproj);
5589 
5590     // Update memory as done in GraphKit::set_output_for_allocation()
5591     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5592     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5593     if (ary_type->isa_aryptr() && length_type != nullptr) {
5594       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5595     }
5596     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5597     int            elemidx  = C->get_alias_index(telemref);
5598     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5599     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5600 
5601     Node* allocx = _gvn.transform(alloc);
5602     assert(allocx == alloc, "where has the allocation gone?");
5603     assert(dest->is_CheckCastPP(), "not an allocation result?");
5604 
5605     _gvn.hash_delete(dest);
5606     dest->set_req(0, control());
5607     Node* destx = _gvn.transform(dest);
5608     assert(destx == dest, "where has the allocation result gone?");

5906         top_src  = src_type->isa_aryptr();
5907         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5908         src_spec = true;
5909       }
5910       if (!has_dest) {
5911         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5912         dest_type  = _gvn.type(dest);
5913         top_dest  = dest_type->isa_aryptr();
5914         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5915         dest_spec = true;
5916       }
5917     }
5918   }
5919 
5920   if (has_src && has_dest && can_emit_guards) {
5921     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5922     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5923     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5924     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5925 
5926     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5927       // If both arrays are object arrays then having the exact types
5928       // for both will remove the need for a subtype check at runtime
5929       // before the call and may make it possible to pick a faster copy
5930       // routine (without a subtype check on every element)
5931       // Do we have the exact type of src?
5932       bool could_have_src = src_spec;
5933       // Do we have the exact type of dest?
5934       bool could_have_dest = dest_spec;
5935       ciKlass* src_k = nullptr;
5936       ciKlass* dest_k = nullptr;
5937       if (!src_spec) {
5938         src_k = src_type->speculative_type_not_null();
5939         if (src_k != nullptr && src_k->is_array_klass()) {
5940           could_have_src = true;
5941         }
5942       }
5943       if (!dest_spec) {
5944         dest_k = dest_type->speculative_type_not_null();
5945         if (dest_k != nullptr && dest_k->is_array_klass()) {
5946           could_have_dest = true;
5947         }
5948       }
5949       if (could_have_src && could_have_dest) {
5950         // If we can have both exact types, emit the missing guards
5951         if (could_have_src && !src_spec) {
5952           src = maybe_cast_profiled_obj(src, src_k, true);


5953         }
5954         if (could_have_dest && !dest_spec) {
5955           dest = maybe_cast_profiled_obj(dest, dest_k, true);


5956         }
5957       }
5958     }
5959   }
5960 
5961   ciMethod* trap_method = method();
5962   int trap_bci = bci();
5963   if (saved_jvms_before_guards != nullptr) {
5964     trap_method = alloc->jvms()->method();
5965     trap_bci = alloc->jvms()->bci();
5966   }
5967 
5968   bool negative_length_guard_generated = false;
5969 
5970   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5971       can_emit_guards &&
5972       !src->is_top() && !dest->is_top()) {
5973     // validate arguments: enables transformation the ArrayCopyNode
5974     validated = true;
5975 
5976     RegionNode* slow_region = new RegionNode(1);
5977     record_for_igvn(slow_region);
5978 
5979     // (1) src and dest are arrays.
5980     generate_non_array_guard(load_object_klass(src), slow_region, &src);
5981     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5982 
5983     // (2) src and dest arrays must have elements of the same BasicType
5984     // done at macro expansion or at Ideal transformation time
5985 
5986     // (4) src_offset must not be negative.
5987     generate_negative_guard(src_offset, slow_region);
5988 
5989     // (5) dest_offset must not be negative.
5990     generate_negative_guard(dest_offset, slow_region);
5991 
5992     // (7) src_offset + length must not exceed length of src.
5993     generate_limit_guard(src_offset, length,
5994                          load_array_length(src),
5995                          slow_region);
5996 
5997     // (8) dest_offset + length must not exceed length of dest.
5998     generate_limit_guard(dest_offset, length,
5999                          load_array_length(dest),
6000                          slow_region);
6001 
6002     // (6) length must not be negative.
6003     // This is also checked in generate_arraycopy() during macro expansion, but
6004     // we also have to check it here for the case where the ArrayCopyNode will
6005     // be eliminated by Escape Analysis.
6006     if (EliminateAllocations) {
6007       generate_negative_guard(length, slow_region);
6008       negative_length_guard_generated = true;
6009     }
6010 
6011     // (9) each element of an oop array must be assignable
6012     Node* dest_klass = load_object_klass(dest);

6013     if (src != dest) {

6014       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6015 
6016       if (not_subtype_ctrl != top()) {
6017         PreserveJVMState pjvms(this);
6018         set_control(not_subtype_ctrl);
6019         uncommon_trap(Deoptimization::Reason_intrinsic,
6020                       Deoptimization::Action_make_not_entrant);
6021         assert(stopped(), "Should be stopped");
6022       }
6023     }





















6024     {
6025       PreserveJVMState pjvms(this);
6026       set_control(_gvn.transform(slow_region));
6027       uncommon_trap(Deoptimization::Reason_intrinsic,
6028                     Deoptimization::Action_make_not_entrant);
6029       assert(stopped(), "Should be stopped");
6030     }
6031 
6032     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6033     const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6034     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6035     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6036   }
6037 
6038   if (stopped()) {
6039     return true;
6040   }
6041 



6042   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6043                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6044                                           // so the compiler has a chance to eliminate them: during macro expansion,
6045                                           // we have to set their control (CastPP nodes are eliminated).
6046                                           load_object_klass(src), load_object_klass(dest),
6047                                           load_array_length(src), load_array_length(dest));
6048 
6049   ac->set_arraycopy(validated);
6050 
6051   Node* n = _gvn.transform(ac);
6052   if (n == ac) {
6053     ac->connect_outputs(this);
6054   } else {
6055     assert(validated, "shouldn't transform if all arguments not validated");
6056     set_all_memory(n);
6057   }
6058   clear_upper_avx();
6059 
6060 
6061   return true;
6062 }
6063 
6064 
6065 // Helper function which determines if an arraycopy immediately follows
6066 // an allocation, with no intervening tests or other escapes for the object.

   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 "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/stubRoutines.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 //---------------------------make_vm_intrinsic----------------------------
  76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  77   vmIntrinsicID id = m->intrinsic_id();
  78   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  79 
  80   if (!m->is_loaded()) {
  81     // Do not attempt to inline unloaded methods.
  82     return nullptr;
  83   }
  84 
  85   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  86   bool is_available = false;
  87 
  88   {
  89     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  90     // the compiler must transition to '_thread_in_vm' state because both
  91     // methods access VM-internal data.

 312   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 313   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 314   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 315   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 316   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 317 
 318   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 319 
 320   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 321 
 322   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 323   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 324   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 325   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 326 
 327   case vmIntrinsics::_compressStringC:
 328   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 329   case vmIntrinsics::_inflateStringC:
 330   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 331 
 332   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 333   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 344 
 345   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 346   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 347   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 348   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 349   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 350   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 351   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 352   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 353   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 354   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 355 
 356   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 357   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 358   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 359   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 360   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 361   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 362   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 363   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 364   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 365 
 366   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 367   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 368   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 369   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 370   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 371   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 372   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 373   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 374   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);

 406   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 407   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 408   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 409   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 410   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 411   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 412   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 413   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 414   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 415 
 416   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 417   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 418   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 419   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 420   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 421   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 422   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 423   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 424   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 425 
 426   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 427   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 428 
 429   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 432   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 433   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 434 
 435   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 439   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 440   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 441   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 442   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 443   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 444   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 445   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 446   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 447   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 448   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);

 468   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 469   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 470   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 471 
 472   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 474   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 475   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 476 
 477   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 480   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 481   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 482 
 483   case vmIntrinsics::_loadFence:
 484   case vmIntrinsics::_storeFence:
 485   case vmIntrinsics::_storeStoreFence:
 486   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 487 
 488   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 489   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 490   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 491 
 492   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 493 
 494   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 495   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 496   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 497 
 498   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 499   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 500 
 501   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 502   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 503 
 504 #if INCLUDE_JVMTI
 505   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 506                                                                                          "notifyJvmtiStart", true, false);
 507   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 508                                                                                          "notifyJvmtiEnd", false, true);
 509   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 510                                                                                          "notifyJvmtiMount", false, false);
 511   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),

 520 #endif
 521   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 522   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 523   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 524   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 525   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 526   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 527   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 528   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 529   case vmIntrinsics::_getLength:                return inline_native_getLength();
 530   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 531   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 532   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 533   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 534   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 535   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 536   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 537 
 538   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 539   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 540   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 541   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 542   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 543   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 544   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 545   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 546 
 547   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 548 
 549   case vmIntrinsics::_isInstance:
 550   case vmIntrinsics::_isHidden:
 551   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 552 
 553   case vmIntrinsics::_floatToRawIntBits:
 554   case vmIntrinsics::_floatToIntBits:
 555   case vmIntrinsics::_intBitsToFloat:
 556   case vmIntrinsics::_doubleToRawLongBits:
 557   case vmIntrinsics::_doubleToLongBits:
 558   case vmIntrinsics::_longBitsToDouble:
 559   case vmIntrinsics::_floatToFloat16:
 560   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 561   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 562   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 563   case vmIntrinsics::_floatIsFinite:
 564   case vmIntrinsics::_floatIsInfinite:
 565   case vmIntrinsics::_doubleIsFinite:

2343     case vmIntrinsics::_remainderUnsigned_l: {
2344       zero_check_long(argument(2));
2345       // Compile-time detect of null-exception
2346       if (stopped()) {
2347         return true; // keep the graph constructed so far
2348       }
2349       n = new UModLNode(control(), argument(0), argument(2));
2350       break;
2351     }
2352     default:  fatal_unexpected_iid(id);  break;
2353   }
2354   set_result(_gvn.transform(n));
2355   return true;
2356 }
2357 
2358 //----------------------------inline_unsafe_access----------------------------
2359 
2360 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2361   // Attempt to infer a sharper value type from the offset and base type.
2362   ciKlass* sharpened_klass = nullptr;
2363   bool null_free = false;
2364 
2365   // See if it is an instance field, with an object type.
2366   if (alias_type->field() != nullptr) {
2367     if (alias_type->field()->type()->is_klass()) {
2368       sharpened_klass = alias_type->field()->type()->as_klass();
2369       null_free = alias_type->field()->is_null_free();
2370     }
2371   }
2372 
2373   const TypeOopPtr* result = nullptr;
2374   // See if it is a narrow oop array.
2375   if (adr_type->isa_aryptr()) {
2376     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2377       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2378       null_free = adr_type->is_aryptr()->is_null_free();
2379       if (elem_type != nullptr && elem_type->is_loaded()) {
2380         // Sharpen the value type.
2381         result = elem_type;
2382       }
2383     }
2384   }
2385 
2386   // The sharpened class might be unloaded if there is no class loader
2387   // contraint in place.
2388   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2389     // Sharpen the value type.
2390     result = TypeOopPtr::make_from_klass(sharpened_klass);
2391     if (null_free) {
2392       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2393     }
2394   }
2395   if (result != nullptr) {
2396 #ifndef PRODUCT
2397     if (C->print_intrinsics() || C->print_inlining()) {
2398       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2399       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2400     }
2401 #endif
2402   }
2403   return result;
2404 }
2405 
2406 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2407   switch (kind) {
2408       case Relaxed:
2409         return MO_UNORDERED;
2410       case Opaque:
2411         return MO_RELAXED;
2412       case Acquire:
2413         return MO_ACQUIRE;

2445   _kit->jvms()->set_sp(_sp);
2446   _map->set_jvms(_kit->jvms());
2447   _kit->set_map(_map);
2448   _kit->set_sp(_sp);
2449   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2450     Node* out = _kit->control()->fast_out(i);
2451     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2452       _kit->_gvn.hash_delete(out);
2453       out->set_req(0, _kit->C->top());
2454       _kit->C->record_for_igvn(out);
2455       --i; --imax;
2456       _kit->_gvn.hash_find_insert(out);
2457     }
2458   }
2459 }
2460 
2461 void LibraryCallKit::SavedState::discard() {
2462   _discarded = true;
2463 }
2464 
2465 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2466   if (callee()->is_static())  return false;  // caller must have the capability!
2467   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2468   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2469   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2470   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2471 
2472   if (is_reference_type(type)) {
2473     decorators |= ON_UNKNOWN_OOP_REF;
2474   }
2475 
2476   if (unaligned) {
2477     decorators |= C2_UNALIGNED;
2478   }
2479 
2480 #ifndef PRODUCT
2481   {
2482     ResourceMark rm;
2483     // Check the signatures.
2484     ciSignature* sig = callee()->signature();
2485 #ifdef ASSERT
2486     if (!is_store) {
2487       // Object getReference(Object base, int/long offset), etc.
2488       BasicType rtype = sig->return_type()->basic_type();
2489       assert(rtype == type, "getter must return the expected value");
2490       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2491       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2492       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2493     } else {
2494       // void putReference(Object base, int/long offset, Object x), etc.
2495       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2496       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2497       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2498       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2499       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2500       assert(vtype == type, "putter must accept the expected value");
2501     }
2502 #endif // ASSERT
2503  }
2504 #endif //PRODUCT
2505 
2506   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2507 
2508   Node* receiver = argument(0);  // type: oop
2509 
2510   // Build address expression.
2511   Node* heap_base_oop = top();
2512 
2513   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2514   Node* base = argument(1);  // type: oop
2515   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2516   Node* offset = argument(2);  // type: long
2517   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2518   // to be plain byte offsets, which are also the same as those accepted
2519   // by oopDesc::field_addr.
2520   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2521          "fieldOffset must be byte-scaled");
2522 
2523   ciInlineKlass* inline_klass = nullptr;
2524   if (is_flat) {
2525     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2526     if (cls == nullptr || cls->const_oop() == nullptr) {
2527       return false;
2528     }
2529     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2530     if (!mirror_type->is_inlinetype()) {
2531       return false;
2532     }
2533     inline_klass = mirror_type->as_inline_klass();
2534   }
2535 
2536   if (base->is_InlineType()) {
2537     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2538     InlineTypeNode* vt = base->as_InlineType();
2539     if (offset->is_Con()) {
2540       long off = find_long_con(offset, 0);
2541       ciInlineKlass* vk = vt->type()->inline_klass();
2542       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2543         return false;
2544       }
2545 
2546       ciField* field = vk->get_non_flat_field_by_offset(off);
2547       if (field != nullptr) {
2548         BasicType bt = type2field[field->type()->basic_type()];
2549         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2550           bt = T_OBJECT;
2551         }
2552         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2553           Node* value = vt->field_value_by_offset(off, false);
2554           if (value->is_InlineType()) {
2555             value = value->as_InlineType()->adjust_scalarization_depth(this);
2556           }
2557           set_result(value);
2558           return true;
2559         }
2560       }
2561     }
2562     {
2563       // Re-execute the unsafe access if allocation triggers deoptimization.
2564       PreserveReexecuteState preexecs(this);
2565       jvms()->set_should_reexecute(true);
2566       vt = vt->buffer(this);
2567     }
2568     base = vt->get_oop();
2569   }
2570 
2571   // 32-bit machines ignore the high half!
2572   offset = ConvL2X(offset);
2573 
2574   // Save state and restore on bailout
2575   SavedState old_state(this);
2576 
2577   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2578   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2579 
2580   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2581     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2582       decorators |= IN_NATIVE; // off-heap primitive access
2583     } else {
2584       return false; // off-heap oop accesses are not supported
2585     }
2586   } else {
2587     heap_base_oop = base; // on-heap or mixed access
2588   }
2589 
2590   // Can base be null? Otherwise, always on-heap access.
2591   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2592 
2593   if (!can_access_non_heap) {
2594     decorators |= IN_HEAP;
2595   }
2596 
2597   Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2598 
2599   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2600   if (adr_type == TypePtr::NULL_PTR) {
2601     return false; // off-heap access with zero address
2602   }
2603 
2604   // Try to categorize the address.
2605   Compile::AliasType* alias_type = C->alias_type(adr_type);
2606   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2607 
2608   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2609       alias_type->adr_type() == TypeAryPtr::RANGE) {
2610     return false; // not supported
2611   }
2612 
2613   bool mismatched = false;
2614   BasicType bt = T_ILLEGAL;
2615   ciField* field = nullptr;
2616   if (adr_type->isa_instptr()) {
2617     const TypeInstPtr* instptr = adr_type->is_instptr();
2618     ciInstanceKlass* k = instptr->instance_klass();
2619     int off = instptr->offset();
2620     if (instptr->const_oop() != nullptr &&
2621         k == ciEnv::current()->Class_klass() &&
2622         instptr->offset() >= (k->size_helper() * wordSize)) {
2623       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2624       field = k->get_field_by_offset(off, true);
2625     } else {
2626       field = k->get_non_flat_field_by_offset(off);
2627     }
2628     if (field != nullptr) {
2629       bt = type2field[field->type()->basic_type()];
2630     }
2631     if (bt != alias_type->basic_type()) {
2632       // Type mismatch. Is it an access to a nested flat field?
2633       field = k->get_field_by_offset(off, false);
2634       if (field != nullptr) {
2635         bt = type2field[field->type()->basic_type()];
2636       }
2637     }
2638     assert(bt == alias_type->basic_type() || is_flat, "should match");
2639   } else {
2640     bt = alias_type->basic_type();
2641   }
2642 
2643   if (bt != T_ILLEGAL) {
2644     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2645     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2646       // Alias type doesn't differentiate between byte[] and boolean[]).
2647       // Use address type to get the element type.
2648       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2649     }
2650     if (is_reference_type(bt, true)) {
2651       // accessing an array field with getReference is not a mismatch
2652       bt = T_OBJECT;
2653     }
2654     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2655       // Don't intrinsify mismatched object accesses
2656       return false;
2657     }
2658     mismatched = (bt != type);
2659   } else if (alias_type->adr_type()->isa_oopptr()) {
2660     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2661   }
2662 
2663   if (is_flat) {
2664     if (adr_type->isa_instptr()) {
2665       if (field == nullptr || field->type() != inline_klass) {
2666         mismatched = true;
2667       }
2668     } else if (adr_type->isa_aryptr()) {
2669       const Type* elem = adr_type->is_aryptr()->elem();
2670       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2671         mismatched = true;
2672       }
2673     } else {
2674       mismatched = true;
2675     }
2676     if (is_store) {
2677       const Type* val_t = _gvn.type(val);
2678       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2679         return false;
2680       }
2681     }
2682   }
2683 
2684   old_state.discard();
2685   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2686 
2687   if (mismatched) {
2688     decorators |= C2_MISMATCHED;
2689   }
2690 
2691   // First guess at the value type.
2692   const Type *value_type = Type::get_const_basic_type(type);
2693 
2694   // Figure out the memory ordering.
2695   decorators |= mo_decorator_for_access_kind(kind);
2696 
2697   if (!is_store) {
2698     if (type == T_OBJECT && !is_flat) {
2699       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2700       if (tjp != nullptr) {
2701         value_type = tjp;
2702       }
2703     }
2704   }
2705 
2706   receiver = null_check(receiver);
2707   if (stopped()) {
2708     return true;
2709   }
2710   // Heap pointers get a null-check from the interpreter,
2711   // as a courtesy.  However, this is not guaranteed by Unsafe,
2712   // and it is not possible to fully distinguish unintended nulls
2713   // from intended ones in this API.
2714 
2715   if (!is_store) {
2716     Node* p = nullptr;
2717     // Try to constant fold a load from a constant field
2718 
2719     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2720       // final or stable field
2721       p = make_constant_from_field(field, heap_base_oop);
2722     }
2723 
2724     if (p == nullptr) { // Could not constant fold the load
2725       if (is_flat) {
2726         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2727       } else {
2728         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2729         const TypeOopPtr* ptr = value_type->make_oopptr();
2730         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2731           // Load a non-flattened inline type from memory
2732           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2733         }
2734       }
2735       // Normalize the value returned by getBoolean in the following cases
2736       if (type == T_BOOLEAN &&
2737           (mismatched ||
2738            heap_base_oop == top() ||                  // - heap_base_oop is null or
2739            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2740                                                       //   and the unsafe access is made to large offset
2741                                                       //   (i.e., larger than the maximum offset necessary for any
2742                                                       //   field access)
2743             ) {
2744           IdealKit ideal = IdealKit(this);
2745 #define __ ideal.
2746           IdealVariable normalized_result(ideal);
2747           __ declarations_done();
2748           __ set(normalized_result, p);
2749           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2750           __ set(normalized_result, ideal.ConI(1));
2751           ideal.end_if();
2752           final_sync(ideal);
2753           p = __ value(normalized_result);
2754 #undef __
2755       }
2756     }
2757     if (type == T_ADDRESS) {
2758       p = gvn().transform(new CastP2XNode(nullptr, p));
2759       p = ConvX2UL(p);
2760     }
2761     // The load node has the control of the preceding MemBarCPUOrder.  All
2762     // following nodes will have the control of the MemBarCPUOrder inserted at
2763     // the end of this method.  So, pushing the load onto the stack at a later
2764     // point is fine.
2765     set_result(p);
2766   } else {
2767     if (bt == T_ADDRESS) {
2768       // Repackage the long as a pointer.
2769       val = ConvL2X(val);
2770       val = gvn().transform(new CastX2PNode(val));
2771     }
2772     if (is_flat) {
2773       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2774     } else {
2775       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2776     }
2777   }
2778 
2779   return true;
2780 }
2781 
2782 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2783 #ifdef ASSERT
2784   {
2785     ResourceMark rm;
2786     // Check the signatures.
2787     ciSignature* sig = callee()->signature();
2788     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2789     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2790     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2791     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2792     if (is_store) {
2793       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2794       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2795       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2796     } else {
2797       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2798       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2799     }
2800  }
2801 #endif // ASSERT
2802 
2803   assert(kind == Relaxed, "Only plain accesses for now");
2804   if (callee()->is_static()) {
2805     // caller must have the capability!
2806     return false;
2807   }
2808   C->set_has_unsafe_access(true);
2809 
2810   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2811   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2812     // parameter valueType is not a constant
2813     return false;
2814   }
2815   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2816   if (!mirror_type->is_inlinetype()) {
2817     // Dead code
2818     return false;
2819   }
2820   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2821 
2822   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2823   if (layout_type == nullptr || !layout_type->is_con()) {
2824     // parameter layoutKind is not a constant
2825     return false;
2826   }
2827   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2828          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2829          "invalid layoutKind %d", layout_type->get_con());
2830   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2831   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2832          layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2833          "unexpected layoutKind %d", layout_type->get_con());
2834 
2835   null_check(argument(0));
2836   if (stopped()) {
2837     return true;
2838   }
2839 
2840   Node* base = must_be_not_null(argument(1), true);
2841   Node* offset = argument(2);
2842   const Type* base_type = _gvn.type(base);
2843 
2844   Node* ptr;
2845   bool immutable_memory = false;
2846   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2847   if (base_type->isa_instptr()) {
2848     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2849     if (offset_type == nullptr || !offset_type->is_con()) {
2850       // Offset into a non-array should be a constant
2851       decorators |= C2_MISMATCHED;
2852     } else {
2853       int offset_con = checked_cast<int>(offset_type->get_con());
2854       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2855       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2856       if (field == nullptr) {
2857         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2858         decorators |= C2_MISMATCHED;
2859       } else {
2860         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2861                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2862         immutable_memory = field->is_strict() && field->is_final();
2863 
2864         if (base->is_InlineType()) {
2865           assert(!is_store, "Cannot store into a non-larval value object");
2866           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2867           return true;
2868         }
2869       }
2870     }
2871 
2872     if (base->is_InlineType()) {
2873       assert(!is_store, "Cannot store into a non-larval value object");
2874       base = base->as_InlineType()->buffer(this, true);
2875     }
2876     ptr = basic_plus_adr(base, ConvL2X(offset));
2877   } else if (base_type->isa_aryptr()) {
2878     decorators |= IS_ARRAY;
2879     if (layout == LayoutKind::REFERENCE) {
2880       if (!base_type->is_aryptr()->is_not_flat()) {
2881         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2882         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2883         replace_in_map(base, new_base);
2884         base = new_base;
2885       }
2886       ptr = basic_plus_adr(base, ConvL2X(offset));
2887     } else {
2888       if (UseArrayFlattening) {
2889         // Flat array must have an exact type
2890         bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2891         bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2892         Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2893         replace_in_map(base, new_base);
2894         base = new_base;
2895         ptr = basic_plus_adr(base, ConvL2X(offset));
2896         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2897         if (ptr_type->field_offset().get() != 0) {
2898           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2899         }
2900       } else {
2901         uncommon_trap(Deoptimization::Reason_intrinsic,
2902                       Deoptimization::Action_none);
2903         return true;
2904       }
2905     }
2906   } else {
2907     decorators |= C2_MISMATCHED;
2908     ptr = basic_plus_adr(base, ConvL2X(offset));
2909   }
2910 
2911   if (is_store) {
2912     Node* value = argument(6);
2913     const Type* value_type = _gvn.type(value);
2914     if (!value_type->is_inlinetypeptr()) {
2915       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2916       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2917       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2918       replace_in_map(value, new_value);
2919       value = new_value;
2920     }
2921 
2922     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2923     if (layout == LayoutKind::REFERENCE) {
2924       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2925       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2926     } else {
2927       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2928       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2929       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2930     }
2931 
2932     return true;
2933   } else {
2934     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2935     InlineTypeNode* result;
2936     if (layout == LayoutKind::REFERENCE) {
2937       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2938       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2939       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2940     } else {
2941       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2942       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2943       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2944     }
2945 
2946     set_result(result);
2947     return true;
2948   }
2949 }
2950 
2951 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2952   Node* receiver = argument(0);
2953   Node* value = argument(1);
2954 
2955   const Type* type = gvn().type(value);
2956   if (!type->is_inlinetypeptr()) {
2957     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2958     return false;
2959   }
2960 
2961   null_check(receiver);
2962   if (stopped()) {
2963     return true;
2964   }
2965 
2966   value = null_check(value);
2967   if (stopped()) {
2968     return true;
2969   }
2970 
2971   ciInlineKlass* vk = type->inline_klass();
2972   Node* klass = makecon(TypeKlassPtr::make(vk));
2973   Node* obj = new_instance(klass);
2974   AllocateNode::Ideal_allocation(obj)->_larval = true;
2975 
2976   assert(value->is_InlineType(), "must be an InlineTypeNode");
2977   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2978   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2979 
2980   set_result(obj);
2981   return true;
2982 }
2983 
2984 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2985   Node* receiver = argument(0);
2986   Node* buffer = argument(1);
2987 
2988   const Type* type = gvn().type(buffer);
2989   if (!type->is_inlinetypeptr()) {
2990     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2991     return false;
2992   }
2993 
2994   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2995   if (alloc == nullptr) {
2996     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2997     return false;
2998   }
2999 
3000   null_check(receiver);
3001   if (stopped()) {
3002     return true;
3003   }
3004 
3005   // Unset the larval bit in the object header
3006   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3007   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3008   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3009 
3010   // We must ensure that the buffer is properly published
3011   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3012   assert(!type->maybe_null(), "result of an allocation should not be null");
3013   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3014   return true;
3015 }
3016 
3017 //----------------------------inline_unsafe_load_store----------------------------
3018 // This method serves a couple of different customers (depending on LoadStoreKind):
3019 //
3020 // LS_cmp_swap:
3021 //
3022 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3023 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
3024 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
3025 //
3026 // LS_cmp_swap_weak:
3027 //
3028 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
3029 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
3030 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3031 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3032 //
3033 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
3034 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
3035 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
3036 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);

3199     }
3200     case LS_cmp_swap:
3201     case LS_cmp_swap_weak:
3202     case LS_get_add:
3203       break;
3204     default:
3205       ShouldNotReachHere();
3206   }
3207 
3208   // Null check receiver.
3209   receiver = null_check(receiver);
3210   if (stopped()) {
3211     return true;
3212   }
3213 
3214   int alias_idx = C->get_alias_index(adr_type);
3215 
3216   if (is_reference_type(type)) {
3217     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3218 
3219     if (oldval != nullptr && oldval->is_InlineType()) {
3220       // Re-execute the unsafe access if allocation triggers deoptimization.
3221       PreserveReexecuteState preexecs(this);
3222       jvms()->set_should_reexecute(true);
3223       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3224     }
3225     if (newval != nullptr && newval->is_InlineType()) {
3226       // Re-execute the unsafe access if allocation triggers deoptimization.
3227       PreserveReexecuteState preexecs(this);
3228       jvms()->set_should_reexecute(true);
3229       newval = newval->as_InlineType()->buffer(this)->get_oop();
3230     }
3231 
3232     // Transformation of a value which could be null pointer (CastPP #null)
3233     // could be delayed during Parse (for example, in adjust_map_after_if()).
3234     // Execute transformation here to avoid barrier generation in such case.
3235     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3236       newval = _gvn.makecon(TypePtr::NULL_PTR);
3237 
3238     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3239       // Refine the value to a null constant, when it is known to be null
3240       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3241     }
3242   }
3243 
3244   Node* result = nullptr;
3245   switch (kind) {
3246     case LS_cmp_exchange: {
3247       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3248                                             oldval, newval, value_type, type, decorators);
3249       break;
3250     }
3251     case LS_cmp_swap_weak:

3280   insert_mem_bar(Op_MemBarCPUOrder);
3281   switch(id) {
3282     case vmIntrinsics::_loadFence:
3283       insert_mem_bar(Op_LoadFence);
3284       return true;
3285     case vmIntrinsics::_storeFence:
3286       insert_mem_bar(Op_StoreFence);
3287       return true;
3288     case vmIntrinsics::_storeStoreFence:
3289       insert_mem_bar(Op_StoreStoreFence);
3290       return true;
3291     case vmIntrinsics::_fullFence:
3292       insert_mem_bar(Op_MemBarVolatile);
3293       return true;
3294     default:
3295       fatal_unexpected_iid(id);
3296       return false;
3297   }
3298 }
3299 
3300 // private native int arrayInstanceBaseOffset0(Object[] array);
3301 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3302   Node* array = argument(1);
3303   Node* klass_node = load_object_klass(array);
3304 
3305   jint  layout_con = Klass::_lh_neutral_value;
3306   Node* layout_val = get_layout_helper(klass_node, layout_con);
3307   int   layout_is_con = (layout_val == nullptr);
3308 
3309   Node* header_size = nullptr;
3310   if (layout_is_con) {
3311     int hsize = Klass::layout_helper_header_size(layout_con);
3312     header_size = intcon(hsize);
3313   } else {
3314     Node* hss = intcon(Klass::_lh_header_size_shift);
3315     Node* hsm = intcon(Klass::_lh_header_size_mask);
3316     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3317     header_size = _gvn.transform(new AndINode(header_size, hsm));
3318   }
3319   set_result(header_size);
3320   return true;
3321 }
3322 
3323 // private native int arrayInstanceIndexScale0(Object[] array);
3324 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3325   Node* array = argument(1);
3326   Node* klass_node = load_object_klass(array);
3327 
3328   jint  layout_con = Klass::_lh_neutral_value;
3329   Node* layout_val = get_layout_helper(klass_node, layout_con);
3330   int   layout_is_con = (layout_val == nullptr);
3331 
3332   Node* element_size = nullptr;
3333   if (layout_is_con) {
3334     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3335     int elem_size = 1 << log_element_size;
3336     element_size = intcon(elem_size);
3337   } else {
3338     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3339     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3340     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3341     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3342     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3343   }
3344   set_result(element_size);
3345   return true;
3346 }
3347 
3348 // private native int arrayLayout0(Object[] array);
3349 bool LibraryCallKit::inline_arrayLayout() {
3350   RegionNode* region = new RegionNode(2);
3351   Node* phi = new PhiNode(region, TypeInt::POS);
3352 
3353   Node* array = argument(1);
3354   Node* klass_node = load_object_klass(array);
3355   generate_refArray_guard(klass_node, region);
3356   if (region->req() == 3) {
3357     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3358   }
3359 
3360   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3361   Node* layout_kind_addr = basic_plus_adr(klass_node, klass_node, layout_kind_offset);
3362   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3363 
3364   region->init_req(1, control());
3365   phi->init_req(1, layout_kind);
3366 
3367   set_control(_gvn.transform(region));
3368   set_result(_gvn.transform(phi));
3369   return true;
3370 }
3371 
3372 bool LibraryCallKit::inline_onspinwait() {
3373   insert_mem_bar(Op_OnSpinWait);
3374   return true;
3375 }
3376 
3377 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3378   if (!kls->is_Con()) {
3379     return true;
3380   }
3381   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3382   if (klsptr == nullptr) {
3383     return true;
3384   }
3385   ciInstanceKlass* ik = klsptr->instance_klass();
3386   // don't need a guard for a klass that is already initialized
3387   return !ik->is_initialized();
3388 }
3389 
3390 //----------------------------inline_unsafe_writeback0-------------------------
3391 // public native void Unsafe.writeback0(long address)

3470                     Deoptimization::Action_make_not_entrant);
3471     }
3472     if (stopped()) {
3473       return true;
3474     }
3475 #endif //INCLUDE_JVMTI
3476 
3477   Node* test = nullptr;
3478   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3479     // Note:  The argument might still be an illegal value like
3480     // Serializable.class or Object[].class.   The runtime will handle it.
3481     // But we must make an explicit check for initialization.
3482     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3483     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3484     // can generate code to load it as unsigned byte.
3485     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3486     Node* bits = intcon(InstanceKlass::fully_initialized);
3487     test = _gvn.transform(new SubINode(inst, bits));
3488     // The 'test' is non-zero if we need to take a slow path.
3489   }
3490   Node* obj = nullptr;
3491   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3492   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3493     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3494   } else {
3495     obj = new_instance(kls, test);
3496   }
3497   set_result(obj);
3498   return true;
3499 }
3500 
3501 //------------------------inline_native_time_funcs--------------
3502 // inline code for System.currentTimeMillis() and System.nanoTime()
3503 // these have the same type and signature
3504 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3505   const TypeFunc* tf = OptoRuntime::void_long_Type();
3506   const TypePtr* no_memory_effects = nullptr;
3507   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3508   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3509 #ifdef ASSERT
3510   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3511   assert(value_top == top(), "second value must be top");
3512 #endif
3513   set_result(value);
3514   return true;
3515 }
3516 

4257   Node* thread = _gvn.transform(new ThreadLocalNode());
4258   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4259   Node* thread_obj_handle
4260     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4261   thread_obj_handle = _gvn.transform(thread_obj_handle);
4262   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4263   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4264 
4265   // Change the _monitor_owner_id of the JavaThread
4266   Node* tid = load_field_from_object(arr, "tid", "J");
4267   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4268   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4269 
4270   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4271   return true;
4272 }
4273 
4274 const Type* LibraryCallKit::scopedValueCache_type() {
4275   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4276   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4277   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4278 
4279   // Because we create the scopedValue cache lazily we have to make the
4280   // type of the result BotPTR.
4281   bool xk = etype->klass_is_exact();
4282   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4283   return objects_type;
4284 }
4285 
4286 Node* LibraryCallKit::scopedValueCache_helper() {
4287   Node* thread = _gvn.transform(new ThreadLocalNode());
4288   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4289   // We cannot use immutable_memory() because we might flip onto a
4290   // different carrier thread, at which point we'll need to use that
4291   // carrier thread's cache.
4292   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4293   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4294   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4295 }
4296 
4297 //------------------------inline_native_scopedValueCache------------------
4298 bool LibraryCallKit::inline_native_scopedValueCache() {
4299   Node* cache_obj_handle = scopedValueCache_helper();
4300   const Type* objects_type = scopedValueCache_type();
4301   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4302 

4386   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4387 
4388   // Result of top level CFG and Memory.
4389   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4390   record_for_igvn(result_rgn);
4391   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4392   record_for_igvn(result_mem);
4393 
4394   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4395   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4396   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4397   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4398 
4399   // Set output state.
4400   set_control(_gvn.transform(result_rgn));
4401   set_all_memory(_gvn.transform(result_mem));
4402 
4403   return true;
4404 }
4405 









4406 //-----------------------load_klass_from_mirror_common-------------------------
4407 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4408 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4409 // and branch to the given path on the region.
4410 // If never_see_null, take an uncommon trap on null, so we can optimistically
4411 // compile for the non-null case.
4412 // If the region is null, force never_see_null = true.
4413 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4414                                                     bool never_see_null,
4415                                                     RegionNode* region,
4416                                                     int null_path,
4417                                                     int offset) {
4418   if (region == nullptr)  never_see_null = true;
4419   Node* p = basic_plus_adr(mirror, offset);
4420   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4421   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4422   Node* null_ctl = top();
4423   kls = null_check_oop(kls, &null_ctl, never_see_null);
4424   if (region != nullptr) {
4425     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).

4429   }
4430   return kls;
4431 }
4432 
4433 //--------------------(inline_native_Class_query helpers)---------------------
4434 // Use this for JVM_ACC_INTERFACE.
4435 // Fall through if (mods & mask) == bits, take the guard otherwise.
4436 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4437                                                  ByteSize offset, const Type* type, BasicType bt) {
4438   // Branch around if the given klass has the given modifier bit set.
4439   // Like generate_guard, adds a new path onto the region.
4440   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4441   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4442   Node* mask = intcon(modifier_mask);
4443   Node* bits = intcon(modifier_bits);
4444   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4445   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4446   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4447   return generate_fair_guard(bol, region);
4448 }
4449 
4450 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4451   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4452                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4453 }
4454 
4455 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4456 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4457   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4458                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4459 }
4460 
4461 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4462   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4463 }
4464 
4465 //-------------------------inline_native_Class_query-------------------
4466 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4467   const Type* return_type = TypeInt::BOOL;
4468   Node* prim_return_value = top();  // what happens if it's a primitive class?
4469   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);

4551       phi->add_req(intcon(1));
4552     // If we fall through, it's a plain class.
4553     query_value = intcon(0);
4554     break;
4555 
4556 
4557   case vmIntrinsics::_getSuperclass:
4558     // The rules here are somewhat unfortunate, but we can still do better
4559     // with random logic than with a JNI call.
4560     // Interfaces store null or Object as _super, but must report null.
4561     // Arrays store an intermediate super as _super, but must report Object.
4562     // Other types can report the actual _super.
4563     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4564     if (generate_interface_guard(kls, region) != nullptr)
4565       // A guard was added.  If the guard is taken, it was an interface.
4566       phi->add_req(null());
4567     if (generate_array_guard(kls, region) != nullptr)
4568       // A guard was added.  If the guard is taken, it was an array.
4569       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4570     // If we fall through, it's a plain class.  Get its _super.









4571     if (!stopped()) {
4572       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4573       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4574       null_ctl = top();
4575       kls = null_check_oop(kls, &null_ctl);
4576       if (null_ctl != top()) {
4577         // If the guard is taken, Object.superClass is null (both klass and mirror).
4578         region->add_req(null_ctl);
4579         phi   ->add_req(null());
4580       }
4581       if (!stopped()) {
4582         query_value = load_mirror_from_klass(kls);
4583       }
4584     }
4585     break;
4586 
4587   default:
4588     fatal_unexpected_iid(id);
4589     break;
4590   }
4591 
4592   // Fall-through is the normal case of a query to a real class.
4593   phi->init_req(1, query_value);
4594   region->init_req(1, control());
4595 
4596   C->set_has_split_ifs(true); // Has chance for split-if optimization
4597   set_result(region, phi);
4598   return true;
4599 }
4600 
4601 
4602 //-------------------------inline_Class_cast-------------------
4603 bool LibraryCallKit::inline_Class_cast() {
4604   Node* mirror = argument(0); // Class
4605   Node* obj    = argument(1);
4606   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4607   if (mirror_con == nullptr) {
4608     return false;  // dead path (mirror->is_top()).
4609   }
4610   if (obj == nullptr || obj->is_top()) {
4611     return false;  // dead path
4612   }
4613   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4614 
4615   // First, see if Class.cast() can be folded statically.
4616   // java_mirror_type() returns non-null for compile-time Class constants.
4617   ciType* tm = mirror_con->java_mirror_type();
4618   if (tm != nullptr && tm->is_klass() &&
4619       tp != nullptr) {
4620     if (!tp->is_loaded()) {
4621       // Don't use intrinsic when class is not loaded.
4622       return false;
4623     } else {
4624       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4625       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4626       if (static_res == Compile::SSC_always_true) {
4627         // isInstance() is true - fold the code.
4628         set_result(obj);
4629         return true;
4630       } else if (static_res == Compile::SSC_always_false) {
4631         // Don't use intrinsic, have to throw ClassCastException.
4632         // If the reference is null, the non-intrinsic bytecode will
4633         // be optimized appropriately.
4634         return false;
4635       }
4636     }
4637   }
4638 
4639   // Bailout intrinsic and do normal inlining if exception path is frequent.
4640   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4641     return false;
4642   }
4643 
4644   // Generate dynamic checks.
4645   // Class.cast() is java implementation of _checkcast bytecode.
4646   // Do checkcast (Parse::do_checkcast()) optimizations here.
4647 
4648   mirror = null_check(mirror);
4649   // If mirror is dead, only null-path is taken.
4650   if (stopped()) {
4651     return true;
4652   }
4653 
4654   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4655   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4656   RegionNode* region = new RegionNode(PATH_LIMIT);
4657   record_for_igvn(region);
4658 
4659   // Now load the mirror's klass metaobject, and null-check it.
4660   // If kls is null, we have a primitive mirror and
4661   // nothing is an instance of a primitive type.
4662   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4663 
4664   Node* res = top();
4665   Node* io = i_o();
4666   Node* mem = merged_memory();
4667   if (!stopped()) {
4668 
4669     Node* bad_type_ctrl = top();
4670     // Do checkcast optimizations.
4671     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4672     region->init_req(_bad_type_path, bad_type_ctrl);
4673   }
4674   if (region->in(_prim_path) != top() ||
4675       region->in(_bad_type_path) != top() ||
4676       region->in(_npe_path) != top()) {
4677     // Let Interpreter throw ClassCastException.
4678     PreserveJVMState pjvms(this);
4679     set_control(_gvn.transform(region));
4680     // Set IO and memory because gen_checkcast may override them when buffering inline types
4681     set_i_o(io);
4682     set_all_memory(mem);
4683     uncommon_trap(Deoptimization::Reason_intrinsic,
4684                   Deoptimization::Action_maybe_recompile);
4685   }
4686   if (!stopped()) {
4687     set_result(res);
4688   }
4689   return true;
4690 }
4691 
4692 
4693 //--------------------------inline_native_subtype_check------------------------
4694 // This intrinsic takes the JNI calls out of the heart of
4695 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4696 bool LibraryCallKit::inline_native_subtype_check() {
4697   // Pull both arguments off the stack.
4698   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4699   args[0] = argument(0);
4700   args[1] = argument(1);
4701   Node* klasses[2];             // corresponding Klasses: superk, subk
4702   klasses[0] = klasses[1] = top();
4703 
4704   enum {
4705     // A full decision tree on {superc is prim, subc is prim}:
4706     _prim_0_path = 1,           // {P,N} => false
4707                                 // {P,P} & superc!=subc => false
4708     _prim_same_path,            // {P,P} & superc==subc => true
4709     _prim_1_path,               // {N,P} => false
4710     _ref_subtype_path,          // {N,N} & subtype check wins => true
4711     _both_ref_path,             // {N,N} & subtype check loses => false
4712     PATH_LIMIT
4713   };
4714 
4715   RegionNode* region = new RegionNode(PATH_LIMIT);
4716   RegionNode* prim_region = new RegionNode(2);
4717   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4718   record_for_igvn(region);
4719   record_for_igvn(prim_region);
4720 
4721   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4722   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4723   int class_klass_offset = java_lang_Class::klass_offset();
4724 
4725   // First null-check both mirrors and load each mirror's klass metaobject.
4726   int which_arg;
4727   for (which_arg = 0; which_arg <= 1; which_arg++) {
4728     Node* arg = args[which_arg];
4729     arg = null_check(arg);
4730     if (stopped())  break;
4731     args[which_arg] = arg;
4732 
4733     Node* p = basic_plus_adr(arg, class_klass_offset);
4734     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4735     klasses[which_arg] = _gvn.transform(kls);
4736   }
4737 
4738   // Having loaded both klasses, test each for null.
4739   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4740   for (which_arg = 0; which_arg <= 1; which_arg++) {
4741     Node* kls = klasses[which_arg];
4742     Node* null_ctl = top();
4743     kls = null_check_oop(kls, &null_ctl, never_see_null);
4744     if (which_arg == 0) {
4745       prim_region->init_req(1, null_ctl);
4746     } else {
4747       region->init_req(_prim_1_path, null_ctl);
4748     }
4749     if (stopped())  break;
4750     klasses[which_arg] = kls;
4751   }
4752 
4753   if (!stopped()) {
4754     // now we have two reference types, in klasses[0..1]
4755     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4756     Node* superk = klasses[0];  // the receiver
4757     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));

4758     region->set_req(_ref_subtype_path, control());
4759   }
4760 
4761   // If both operands are primitive (both klasses null), then
4762   // we must return true when they are identical primitives.
4763   // It is convenient to test this after the first null klass check.
4764   // This path is also used if superc is a value mirror.
4765   set_control(_gvn.transform(prim_region));
4766   if (!stopped()) {
4767     // Since superc is primitive, make a guard for the superc==subc case.
4768     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4769     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4770     generate_fair_guard(bol_eq, region);
4771     if (region->req() == PATH_LIMIT+1) {
4772       // A guard was added.  If the added guard is taken, superc==subc.
4773       region->swap_edges(PATH_LIMIT, _prim_same_path);
4774       region->del_req(PATH_LIMIT);
4775     }
4776     region->set_req(_prim_0_path, control()); // Not equal after all.
4777   }
4778 
4779   // these are the only paths that produce 'true':
4780   phi->set_req(_prim_same_path,   intcon(1));
4781   phi->set_req(_ref_subtype_path, intcon(1));
4782 
4783   // pull together the cases:
4784   assert(region->req() == PATH_LIMIT, "sane region");
4785   for (uint i = 1; i < region->req(); i++) {
4786     Node* ctl = region->in(i);
4787     if (ctl == nullptr || ctl == top()) {
4788       region->set_req(i, top());
4789       phi   ->set_req(i, top());
4790     } else if (phi->in(i) == nullptr) {
4791       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4792     }
4793   }
4794 
4795   set_control(_gvn.transform(region));
4796   set_result(_gvn.transform(phi));
4797   return true;
4798 }
4799 
4800 //---------------------generate_array_guard_common------------------------
4801 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {

4802 
4803   if (stopped()) {
4804     return nullptr;
4805   }
4806 









4807   // Like generate_guard, adds a new path onto the region.
4808   jint  layout_con = 0;
4809   Node* layout_val = get_layout_helper(kls, layout_con);
4810   if (layout_val == nullptr) {
4811     bool query = 0;
4812     switch(kind) {
4813       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4814       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4815       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4816       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4817       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4818       default:
4819         ShouldNotReachHere();
4820     }
4821     if (!query) {
4822       return nullptr;                       // never a branch
4823     } else {                             // always a branch
4824       Node* always_branch = control();
4825       if (region != nullptr)
4826         region->add_req(always_branch);
4827       set_control(top());
4828       return always_branch;
4829     }
4830   }
4831   unsigned int value = 0;
4832   BoolTest::mask btest = BoolTest::illegal;
4833   switch(kind) {
4834     case RefArray:
4835     case NonRefArray: {
4836       value = Klass::_lh_array_tag_ref_value;
4837       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4838       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4839       break;
4840     }
4841     case TypeArray: {
4842       value = Klass::_lh_array_tag_type_value;
4843       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4844       btest = BoolTest::eq;
4845       break;
4846     }
4847     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4848     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4849     default:
4850       ShouldNotReachHere();
4851   }
4852   // Now test the correct condition.
4853   jint nval = (jint)value;



4854   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));



4855   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4856   Node* ctrl = generate_fair_guard(bol, region);
4857   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4858   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4859     // Keep track of the fact that 'obj' is an array to prevent
4860     // array specific accesses from floating above the guard.
4861     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4862   }
4863   return ctrl;
4864 }
4865 
4866 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4867 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4868 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4869 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4870   assert(null_free || atomic, "nullable implies atomic");
4871   Node* componentType = argument(0);
4872   Node* length = argument(1);
4873   Node* init_val = null_free ? argument(2) : nullptr;
4874 
4875   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4876   if (tp != nullptr) {
4877     ciInstanceKlass* ik = tp->instance_klass();
4878     if (ik == C->env()->Class_klass()) {
4879       ciType* t = tp->java_mirror_type();
4880       if (t != nullptr && t->is_inlinetype()) {
4881 
4882         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4883         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4884         assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4885 
4886         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4887         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4888           return false;
4889         }
4890 
4891         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4892           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4893           if (null_free) {
4894             if (init_val->is_InlineType()) {
4895               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4896                 // Zeroing is enough because the init value is the all-zero value
4897                 init_val = nullptr;
4898               } else {
4899                 init_val = init_val->as_InlineType()->buffer(this);
4900               }
4901             }
4902             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4903           }
4904           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4905           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4906           assert(arytype->is_null_free() == null_free, "inconsistency");
4907           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4908           assert(arytype->is_atomic() == atomic, "inconsistency");
4909           set_result(obj);
4910           return true;
4911         }
4912       }
4913     }
4914   }
4915   return false;
4916 }
4917 
4918 // public static native boolean ValueClass::isFlatArray(Object array);
4919 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4920 // public static native boolean ValueClass::isAtomicArray(Object array);
4921 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4922   Node* array = argument(0);
4923 
4924   Node* bol;
4925   switch(check) {
4926     case IsFlat:
4927       // TODO 8350865 Use the object version here instead of loading the klass
4928       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4929       bol = flat_array_test(load_object_klass(array));
4930       break;
4931     case IsNullRestricted:
4932       bol = null_free_array_test(array);
4933       break;
4934     case IsAtomic:
4935       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4936       // Enable TestIntrinsics::test87/88 once this is implemented
4937       // bol = null_free_atomic_array_test
4938       return false;
4939     default:
4940       ShouldNotReachHere();
4941   }
4942 
4943   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4944   set_result(res);
4945   return true;
4946 }
4947 
4948 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4949 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4950 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4951   RegionNode* region = new RegionNode(2);
4952   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4953 
4954   if (type_array_guard) {
4955     generate_typeArray_guard(klass_node, region);
4956     if (region->req() == 3) {
4957       phi->add_req(klass_node);
4958     }
4959   }
4960   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4961   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4962 
4963   // Can be null if not initialized yet, just deopt
4964   Node* null_ctl = top();
4965   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4966 
4967   region->init_req(1, control());
4968   phi->init_req(1, refined_klass);
4969 
4970   set_control(_gvn.transform(region));
4971   return _gvn.transform(phi);
4972 }
4973 
4974 // Load the non-refined array klass from an ObjArrayKlass.
4975 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4976   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4977   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4978     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4979   }
4980 
4981   RegionNode* region = new RegionNode(2);
4982   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4983 
4984   generate_typeArray_guard(klass_node, region);
4985   if (region->req() == 3) {
4986     phi->add_req(klass_node);
4987   }
4988   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4989   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4990 
4991   region->init_req(1, control());
4992   phi->init_req(1, super_klass);
4993 
4994   set_control(_gvn.transform(region));
4995   return _gvn.transform(phi);
4996 }
4997 
4998 //-----------------------inline_native_newArray--------------------------
4999 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5000 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5001 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5002   Node* mirror;
5003   Node* count_val;
5004   if (uninitialized) {
5005     null_check_receiver();
5006     mirror    = argument(1);
5007     count_val = argument(2);
5008   } else {
5009     mirror    = argument(0);
5010     count_val = argument(1);
5011   }
5012 
5013   mirror = null_check(mirror);
5014   // If mirror or obj is dead, only null-path is taken.
5015   if (stopped())  return true;
5016 
5017   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5018   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5019   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);

5037     CallJavaNode* slow_call = nullptr;
5038     if (uninitialized) {
5039       // Generate optimized virtual call (holder class 'Unsafe' is final)
5040       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5041     } else {
5042       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5043     }
5044     Node* slow_result = set_results_for_java_call(slow_call);
5045     // this->control() comes from set_results_for_java_call
5046     result_reg->set_req(_slow_path, control());
5047     result_val->set_req(_slow_path, slow_result);
5048     result_io ->set_req(_slow_path, i_o());
5049     result_mem->set_req(_slow_path, reset_memory());
5050   }
5051 
5052   set_control(normal_ctl);
5053   if (!stopped()) {
5054     // Normal case:  The array type has been cached in the java.lang.Class.
5055     // The following call works fine even if the array type is polymorphic.
5056     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5057 
5058     klass_node = load_default_refined_array_klass(klass_node);
5059 
5060     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5061     result_reg->init_req(_normal_path, control());
5062     result_val->init_req(_normal_path, obj);
5063     result_io ->init_req(_normal_path, i_o());
5064     result_mem->init_req(_normal_path, reset_memory());
5065 
5066     if (uninitialized) {
5067       // Mark the allocation so that zeroing is skipped
5068       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5069       alloc->maybe_set_complete(&_gvn);
5070     }
5071   }
5072 
5073   // Return the combined state.
5074   set_i_o(        _gvn.transform(result_io)  );
5075   set_all_memory( _gvn.transform(result_mem));
5076 
5077   C->set_has_split_ifs(true); // Has chance for split-if optimization
5078   set_result(result_reg, result_val);
5079   return true;

5128   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5129   { PreserveReexecuteState preexecs(this);
5130     jvms()->set_should_reexecute(true);
5131 
5132     array_type_mirror = null_check(array_type_mirror);
5133     original          = null_check(original);
5134 
5135     // Check if a null path was taken unconditionally.
5136     if (stopped())  return true;
5137 
5138     Node* orig_length = load_array_length(original);
5139 
5140     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5141     klass_node = null_check(klass_node);
5142 
5143     RegionNode* bailout = new RegionNode(1);
5144     record_for_igvn(bailout);
5145 
5146     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5147     // Bail out if that is so.
5148     // Inline type array may have object field that would require a
5149     // write barrier. Conservatively, go to slow path.
5150     // TODO 8251971: Optimize for the case when flat src/dst are later found
5151     // to not contain oops (i.e., move this check to the macro expansion phase).
5152     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5153     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5154     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5155     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5156                         // Can src array be flat and contain oops?
5157                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5158                         // Can dest array be flat and contain oops?
5159                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5160     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5161 
5162     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5163 
5164     if (not_objArray != nullptr) {
5165       // Improve the klass node's type from the new optimistic assumption:
5166       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5167       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5168       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5169       refined_klass_node = _gvn.transform(cast);
5170     }
5171 
5172     // Bail out if either start or end is negative.
5173     generate_negative_guard(start, bailout, &start);
5174     generate_negative_guard(end,   bailout, &end);
5175 
5176     Node* length = end;
5177     if (_gvn.type(start) != TypeInt::ZERO) {
5178       length = _gvn.transform(new SubINode(end, start));
5179     }
5180 
5181     // Bail out if length is negative (i.e., if start > end).
5182     // Without this the new_array would throw
5183     // NegativeArraySizeException but IllegalArgumentException is what
5184     // should be thrown
5185     generate_negative_guard(length, bailout, &length);
5186 
5187     // Handle inline type arrays
5188     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5189     if (!stopped()) {
5190       // TODO JDK-8329224
5191       if (!orig_t->is_null_free()) {
5192         // Not statically known to be null free, add a check
5193         generate_fair_guard(null_free_array_test(original), bailout);
5194       }
5195       orig_t = _gvn.type(original)->isa_aryptr();
5196       if (orig_t != nullptr && orig_t->is_flat()) {
5197         // Src is flat, check that dest is flat as well
5198         if (exclude_flat) {
5199           // Dest can't be flat, bail out
5200           bailout->add_req(control());
5201           set_control(top());
5202         } else {
5203           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5204         }
5205         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5206       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5207                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5208                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5209         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5210         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5211         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5212         if (orig_t != nullptr) {
5213           orig_t = orig_t->cast_to_not_flat();
5214           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5215         }
5216       }
5217       if (!can_validate) {
5218         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5219         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5220         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5221         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5222         generate_fair_guard(null_free_array_test(original), bailout);
5223       }
5224     }
5225 
5226     // Bail out if start is larger than the original length
5227     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5228     generate_negative_guard(orig_tail, bailout, &orig_tail);
5229 
5230     if (bailout->req() > 1) {
5231       PreserveJVMState pjvms(this);
5232       set_control(_gvn.transform(bailout));
5233       uncommon_trap(Deoptimization::Reason_intrinsic,
5234                     Deoptimization::Action_maybe_recompile);
5235     }
5236 
5237     if (!stopped()) {
5238       // How many elements will we copy from the original?
5239       // The answer is MinI(orig_tail, length).
5240       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5241 
5242       // Generate a direct call to the right arraycopy function(s).
5243       // We know the copy is disjoint but we might not know if the
5244       // oop stores need checking.
5245       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).

5251       // to the copyOf to be validated, including that the copy to the
5252       // new array won't trigger an ArrayStoreException. That subtype
5253       // check can be optimized if we know something on the type of
5254       // the input array from type speculation.
5255       if (_gvn.type(klass_node)->singleton()) {
5256         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5257         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5258 
5259         int test = C->static_subtype_check(superk, subk);
5260         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5261           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5262           if (t_original->speculative_type() != nullptr) {
5263             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5264           }
5265         }
5266       }
5267 
5268       bool validated = false;
5269       // Reason_class_check rather than Reason_intrinsic because we
5270       // want to intrinsify even if this traps.
5271       if (can_validate) {
5272         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5273 
5274         if (not_subtype_ctrl != top()) {
5275           PreserveJVMState pjvms(this);
5276           set_control(not_subtype_ctrl);
5277           uncommon_trap(Deoptimization::Reason_class_check,
5278                         Deoptimization::Action_make_not_entrant);
5279           assert(stopped(), "Should be stopped");
5280         }
5281         validated = true;
5282       }
5283 
5284       if (!stopped()) {
5285         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5286 
5287         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5288                                                 load_object_klass(original), klass_node);
5289         if (!is_copyOfRange) {
5290           ac->set_copyof(validated);
5291         } else {
5292           ac->set_copyofrange(validated);
5293         }
5294         Node* n = _gvn.transform(ac);
5295         if (n == ac) {
5296           ac->connect_outputs(this);
5297         } else {
5298           assert(validated, "shouldn't transform if all arguments not validated");
5299           set_all_memory(n);
5300         }
5301       }
5302     }
5303   } // original reexecute is set back here
5304 
5305   C->set_has_split_ifs(true); // Has chance for split-if optimization

5337 
5338 //-----------------------generate_method_call----------------------------
5339 // Use generate_method_call to make a slow-call to the real
5340 // method if the fast path fails.  An alternative would be to
5341 // use a stub like OptoRuntime::slow_arraycopy_Java.
5342 // This only works for expanding the current library call,
5343 // not another intrinsic.  (E.g., don't use this for making an
5344 // arraycopy call inside of the copyOf intrinsic.)
5345 CallJavaNode*
5346 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5347   // When compiling the intrinsic method itself, do not use this technique.
5348   guarantee(callee() != C->method(), "cannot make slow-call to self");
5349 
5350   ciMethod* method = callee();
5351   // ensure the JVMS we have will be correct for this call
5352   guarantee(method_id == method->intrinsic_id(), "must match");
5353 
5354   const TypeFunc* tf = TypeFunc::make(method);
5355   if (res_not_null) {
5356     assert(tf->return_type() == T_OBJECT, "");
5357     const TypeTuple* range = tf->range_cc();
5358     const Type** fields = TypeTuple::fields(range->cnt());
5359     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5360     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5361     tf = TypeFunc::make(tf->domain_cc(), new_range);
5362   }
5363   CallJavaNode* slow_call;
5364   if (is_static) {
5365     assert(!is_virtual, "");
5366     slow_call = new CallStaticJavaNode(C, tf,
5367                            SharedRuntime::get_resolve_static_call_stub(), method);
5368   } else if (is_virtual) {
5369     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5370     int vtable_index = Method::invalid_vtable_index;
5371     if (UseInlineCaches) {
5372       // Suppress the vtable call
5373     } else {
5374       // hashCode and clone are not a miranda methods,
5375       // so the vtable index is fixed.
5376       // No need to use the linkResolver to get it.
5377        vtable_index = method->vtable_index();
5378        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5379               "bad index %d", vtable_index);
5380     }
5381     slow_call = new CallDynamicJavaNode(tf,

5398   set_edges_for_java_call(slow_call);
5399   return slow_call;
5400 }
5401 
5402 
5403 /**
5404  * Build special case code for calls to hashCode on an object. This call may
5405  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5406  * slightly different code.
5407  */
5408 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5409   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5410   assert(!(is_virtual && is_static), "either virtual, special, or static");
5411 
5412   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5413 
5414   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5415   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5416   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5417   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5418   Node* obj = argument(0);
5419 
5420   // Don't intrinsify hashcode on inline types for now.
5421   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5422   if (gvn().type(obj)->is_inlinetypeptr()) {
5423     return false;
5424   }
5425 
5426   if (!is_static) {
5427     // Check for hashing null object
5428     obj = null_check_receiver();
5429     if (stopped())  return true;        // unconditionally null
5430     result_reg->init_req(_null_path, top());
5431     result_val->init_req(_null_path, top());
5432   } else {
5433     // Do a null check, and return zero if null.
5434     // System.identityHashCode(null) == 0

5435     Node* null_ctl = top();
5436     obj = null_check_oop(obj, &null_ctl);
5437     result_reg->init_req(_null_path, null_ctl);
5438     result_val->init_req(_null_path, _gvn.intcon(0));
5439   }
5440 
5441   // Unconditionally null?  Then return right away.
5442   if (stopped()) {
5443     set_control( result_reg->in(_null_path));
5444     if (!stopped())
5445       set_result(result_val->in(_null_path));
5446     return true;
5447   }
5448 
5449   // We only go to the fast case code if we pass a number of guards.  The
5450   // paths which do not pass are accumulated in the slow_region.
5451   RegionNode* slow_region = new RegionNode(1);
5452   record_for_igvn(slow_region);
5453 
5454   // If this is a virtual call, we generate a funny guard.  We pull out
5455   // the vtable entry corresponding to hashCode() from the target object.
5456   // If the target method which we are calling happens to be the native
5457   // Object hashCode() method, we pass the guard.  We do not need this
5458   // guard for non-virtual calls -- the caller is known to be the native
5459   // Object hashCode().
5460   if (is_virtual) {
5461     // After null check, get the object's klass.
5462     Node* obj_klass = load_object_klass(obj);
5463     generate_virtual_guard(obj_klass, slow_region);
5464   }
5465 
5466   // Get the header out of the object, use LoadMarkNode when available
5467   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5468   // The control of the load must be null. Otherwise, the load can move before
5469   // the null check after castPP removal.
5470   Node* no_ctrl = nullptr;
5471   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5472 
5473   if (!UseObjectMonitorTable) {
5474     // Test the header to see if it is safe to read w.r.t. locking.
5475     // We cannot use the inline type mask as this may check bits that are overriden
5476     // by an object monitor's pointer when inflating locking.
5477     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5478     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5479     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5480     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5481     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5482 
5483     generate_slow_guard(test_monitor, slow_region);
5484   }
5485 
5486   // Get the hash value and check to see that it has been properly assigned.
5487   // We depend on hash_mask being at most 32 bits and avoid the use of
5488   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5489   // vm: see markWord.hpp.
5490   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5491   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5492   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5493   // This hack lets the hash bits live anywhere in the mark object now, as long
5494   // as the shift drops the relevant bits into the low 32 bits.  Note that
5495   // Java spec says that HashCode is an int so there's no point in capturing
5496   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).

5524     // this->control() comes from set_results_for_java_call
5525     result_reg->init_req(_slow_path, control());
5526     result_val->init_req(_slow_path, slow_result);
5527     result_io  ->set_req(_slow_path, i_o());
5528     result_mem ->set_req(_slow_path, reset_memory());
5529   }
5530 
5531   // Return the combined state.
5532   set_i_o(        _gvn.transform(result_io)  );
5533   set_all_memory( _gvn.transform(result_mem));
5534 
5535   set_result(result_reg, result_val);
5536   return true;
5537 }
5538 
5539 //---------------------------inline_native_getClass----------------------------
5540 // public final native Class<?> java.lang.Object.getClass();
5541 //
5542 // Build special case code for calls to getClass on an object.
5543 bool LibraryCallKit::inline_native_getClass() {
5544   Node* obj = argument(0);
5545   if (obj->is_InlineType()) {
5546     const Type* t = _gvn.type(obj);
5547     if (t->maybe_null()) {
5548       null_check(obj);
5549     }
5550     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5551     return true;
5552   }
5553   obj = null_check_receiver();
5554   if (stopped())  return true;
5555   set_result(load_mirror_from_klass(load_object_klass(obj)));
5556   return true;
5557 }
5558 
5559 //-----------------inline_native_Reflection_getCallerClass---------------------
5560 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5561 //
5562 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5563 //
5564 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5565 // in that it must skip particular security frames and checks for
5566 // caller sensitive methods.
5567 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5568 #ifndef PRODUCT
5569   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5570     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5571   }
5572 #endif
5573 

5955 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5956 //
5957 // The general case has two steps, allocation and copying.
5958 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5959 //
5960 // Copying also has two cases, oop arrays and everything else.
5961 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5962 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5963 //
5964 // These steps fold up nicely if and when the cloned object's klass
5965 // can be sharply typed as an object array, a type array, or an instance.
5966 //
5967 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5968   PhiNode* result_val;
5969 
5970   // Set the reexecute bit for the interpreter to reexecute
5971   // the bytecode that invokes Object.clone if deoptimization happens.
5972   { PreserveReexecuteState preexecs(this);
5973     jvms()->set_should_reexecute(true);
5974 
5975     Node* obj = argument(0);
5976     obj = null_check_receiver();
5977     if (stopped())  return true;
5978 
5979     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5980     if (obj_type->is_inlinetypeptr()) {
5981       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5982       // no identity.
5983       set_result(obj);
5984       return true;
5985     }
5986 
5987     // If we are going to clone an instance, we need its exact type to
5988     // know the number and types of fields to convert the clone to
5989     // loads/stores. Maybe a speculative type can help us.
5990     if (!obj_type->klass_is_exact() &&
5991         obj_type->speculative_type() != nullptr &&
5992         obj_type->speculative_type()->is_instance_klass() &&
5993         !obj_type->speculative_type()->is_inlinetype()) {
5994       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5995       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5996           !spec_ik->has_injected_fields()) {
5997         if (!obj_type->isa_instptr() ||
5998             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5999           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6000         }
6001       }
6002     }
6003 
6004     // Conservatively insert a memory barrier on all memory slices.
6005     // Do not let writes into the original float below the clone.
6006     insert_mem_bar(Op_MemBarCPUOrder);
6007 
6008     // paths into result_reg:
6009     enum {
6010       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6011       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6012       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6013       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6014       PATH_LIMIT
6015     };
6016     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6017     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6018     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6019     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6020     record_for_igvn(result_reg);
6021 
6022     Node* obj_klass = load_object_klass(obj);
6023     // We only go to the fast case code if we pass a number of guards.
6024     // The paths which do not pass are accumulated in the slow_region.
6025     RegionNode* slow_region = new RegionNode(1);
6026     record_for_igvn(slow_region);
6027 
6028     Node* array_obj = obj;
6029     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6030     if (array_ctl != nullptr) {
6031       // It's an array.
6032       PreserveJVMState pjvms(this);
6033       set_control(array_ctl);



6034 
6035       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6036       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6037       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6038           obj_type->can_be_inline_array() &&
6039           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6040         // Flat inline type array may have object field that would require a
6041         // write barrier. Conservatively, go to slow path.
6042         generate_fair_guard(flat_array_test(obj_klass), slow_region);













6043       }







6044 
6045       if (!stopped()) {
6046         Node* obj_length = load_array_length(array_obj);
6047         Node* array_size = nullptr; // Size of the array without object alignment padding.
6048         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6049 
6050         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6051         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6052           // If it is an oop array, it requires very special treatment,
6053           // because gc barriers are required when accessing the array.
6054           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6055           if (is_obja != nullptr) {
6056             PreserveJVMState pjvms2(this);
6057             set_control(is_obja);
6058             // Generate a direct call to the right arraycopy function(s).
6059             // Clones are always tightly coupled.
6060             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6061             ac->set_clone_oop_array();
6062             Node* n = _gvn.transform(ac);
6063             assert(n == ac, "cannot disappear");
6064             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6065 
6066             result_reg->init_req(_objArray_path, control());
6067             result_val->init_req(_objArray_path, alloc_obj);
6068             result_i_o ->set_req(_objArray_path, i_o());
6069             result_mem ->set_req(_objArray_path, reset_memory());
6070           }
6071         }
6072         // Otherwise, there are no barriers to worry about.
6073         // (We can dispense with card marks if we know the allocation
6074         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6075         //  causes the non-eden paths to take compensating steps to
6076         //  simulate a fresh allocation, so that no further
6077         //  card marks are required in compiled code to initialize
6078         //  the object.)
6079 
6080         if (!stopped()) {
6081           copy_to_clone(obj, alloc_obj, array_size, true);
6082 
6083           // Present the results of the copy.
6084           result_reg->init_req(_array_path, control());
6085           result_val->init_req(_array_path, alloc_obj);
6086           result_i_o ->set_req(_array_path, i_o());
6087           result_mem ->set_req(_array_path, reset_memory());
6088         }
6089       }
6090     }
6091 




6092     if (!stopped()) {
6093       // It's an instance (we did array above).  Make the slow-path tests.
6094       // If this is a virtual call, we generate a funny guard.  We grab
6095       // the vtable entry corresponding to clone() from the target object.
6096       // If the target method which we are calling happens to be the
6097       // Object clone() method, we pass the guard.  We do not need this
6098       // guard for non-virtual calls; the caller is known to be the native
6099       // Object clone().
6100       if (is_virtual) {
6101         generate_virtual_guard(obj_klass, slow_region);
6102       }
6103 
6104       // The object must be easily cloneable and must not have a finalizer.
6105       // Both of these conditions may be checked in a single test.
6106       // We could optimize the test further, but we don't care.
6107       generate_misc_flags_guard(obj_klass,
6108                                 // Test both conditions:
6109                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6110                                 // Must be cloneable but not finalizer:
6111                                 KlassFlags::_misc_is_cloneable_fast,

6203         set_jvms(sfpt->jvms());
6204         _reexecute_sp = jvms()->sp();
6205 
6206         return saved_jvms;
6207       }
6208     }
6209   }
6210   return nullptr;
6211 }
6212 
6213 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6214 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6215 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6216   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6217   uint size = alloc->req();
6218   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6219   old_jvms->set_map(sfpt);
6220   for (uint i = 0; i < size; i++) {
6221     sfpt->init_req(i, alloc->in(i));
6222   }
6223   int adjustment = 1;
6224   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6225   if (ary_klass_ptr->is_null_free()) {
6226     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6227     // also requires the componentType and initVal on stack for re-execution.
6228     // Re-create and push the componentType.
6229     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6230     ciInstance* instance = klass->component_mirror_instance();
6231     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6232     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6233     adjustment++;
6234   }
6235   // re-push array length for deoptimization
6236   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6237   if (ary_klass_ptr->is_null_free()) {
6238     // Re-create and push the initVal.
6239     Node* init_val = alloc->in(AllocateNode::InitValue);
6240     if (init_val == nullptr) {
6241       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6242     } else if (UseCompressedOops) {
6243       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6244     }
6245     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6246     adjustment++;
6247   }
6248   old_jvms->set_sp(old_jvms->sp() + adjustment);
6249   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6250   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6251   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6252   old_jvms->set_should_reexecute(true);
6253 
6254   sfpt->set_i_o(map()->i_o());
6255   sfpt->set_memory(map()->memory());
6256   sfpt->set_control(map()->control());
6257   return sfpt;
6258 }
6259 
6260 // In case of a deoptimization, we restart execution at the
6261 // allocation, allocating a new array. We would leave an uninitialized
6262 // array in the heap that GCs wouldn't expect. Move the allocation
6263 // after the traps so we don't allocate the array if we
6264 // deoptimize. This is possible because tightly_coupled_allocation()
6265 // guarantees there's no observer of the allocated array at this point
6266 // and the control flow is simple enough.
6267 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6268                                                     int saved_reexecute_sp, uint new_idx) {
6269   if (saved_jvms_before_guards != nullptr && !stopped()) {
6270     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6271 
6272     assert(alloc != nullptr, "only with a tightly coupled allocation");
6273     // restore JVM state to the state at the arraycopy
6274     saved_jvms_before_guards->map()->set_control(map()->control());
6275     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6276     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6277     // If we've improved the types of some nodes (null check) while
6278     // emitting the guards, propagate them to the current state
6279     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6280     set_jvms(saved_jvms_before_guards);
6281     _reexecute_sp = saved_reexecute_sp;
6282 
6283     // Remove the allocation from above the guards
6284     CallProjections* callprojs = alloc->extract_projections(true);

6285     InitializeNode* init = alloc->initialization();
6286     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6287     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6288     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6289 
6290     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6291     // the allocation (i.e. is only valid if the allocation succeeds):
6292     // 1) replace CastIINode with AllocateArrayNode's length here
6293     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6294     //
6295     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6296     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6297     Node* init_control = init->proj_out(TypeFunc::Control);
6298     Node* alloc_length = alloc->Ideal_length();
6299 #ifdef ASSERT
6300     Node* prev_cast = nullptr;
6301 #endif
6302     for (uint i = 0; i < init_control->outcnt(); i++) {
6303       Node* init_out = init_control->raw_out(i);
6304       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6305 #ifdef ASSERT
6306         if (prev_cast == nullptr) {
6307           prev_cast = init_out;

6309           if (prev_cast->cmp(*init_out) == false) {
6310             prev_cast->dump();
6311             init_out->dump();
6312             assert(false, "not equal CastIINode");
6313           }
6314         }
6315 #endif
6316         C->gvn_replace_by(init_out, alloc_length);
6317       }
6318     }
6319     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6320 
6321     // move the allocation here (after the guards)
6322     _gvn.hash_delete(alloc);
6323     alloc->set_req(TypeFunc::Control, control());
6324     alloc->set_req(TypeFunc::I_O, i_o());
6325     Node *mem = reset_memory();
6326     set_all_memory(mem);
6327     alloc->set_req(TypeFunc::Memory, mem);
6328     set_control(init->proj_out_or_null(TypeFunc::Control));
6329     set_i_o(callprojs->fallthrough_ioproj);
6330 
6331     // Update memory as done in GraphKit::set_output_for_allocation()
6332     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6333     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6334     if (ary_type->isa_aryptr() && length_type != nullptr) {
6335       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6336     }
6337     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6338     int            elemidx  = C->get_alias_index(telemref);
6339     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6340     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6341 
6342     Node* allocx = _gvn.transform(alloc);
6343     assert(allocx == alloc, "where has the allocation gone?");
6344     assert(dest->is_CheckCastPP(), "not an allocation result?");
6345 
6346     _gvn.hash_delete(dest);
6347     dest->set_req(0, control());
6348     Node* destx = _gvn.transform(dest);
6349     assert(destx == dest, "where has the allocation result gone?");

6647         top_src  = src_type->isa_aryptr();
6648         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6649         src_spec = true;
6650       }
6651       if (!has_dest) {
6652         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6653         dest_type  = _gvn.type(dest);
6654         top_dest  = dest_type->isa_aryptr();
6655         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6656         dest_spec = true;
6657       }
6658     }
6659   }
6660 
6661   if (has_src && has_dest && can_emit_guards) {
6662     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6663     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6664     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6665     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6666 
6667     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6668       // If both arrays are object arrays then having the exact types
6669       // for both will remove the need for a subtype check at runtime
6670       // before the call and may make it possible to pick a faster copy
6671       // routine (without a subtype check on every element)
6672       // Do we have the exact type of src?
6673       bool could_have_src = src_spec;
6674       // Do we have the exact type of dest?
6675       bool could_have_dest = dest_spec;
6676       ciKlass* src_k = nullptr;
6677       ciKlass* dest_k = nullptr;
6678       if (!src_spec) {
6679         src_k = src_type->speculative_type_not_null();
6680         if (src_k != nullptr && src_k->is_array_klass()) {
6681           could_have_src = true;
6682         }
6683       }
6684       if (!dest_spec) {
6685         dest_k = dest_type->speculative_type_not_null();
6686         if (dest_k != nullptr && dest_k->is_array_klass()) {
6687           could_have_dest = true;
6688         }
6689       }
6690       if (could_have_src && could_have_dest) {
6691         // If we can have both exact types, emit the missing guards
6692         if (could_have_src && !src_spec) {
6693           src = maybe_cast_profiled_obj(src, src_k, true);
6694           src_type = _gvn.type(src);
6695           top_src = src_type->isa_aryptr();
6696         }
6697         if (could_have_dest && !dest_spec) {
6698           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6699           dest_type = _gvn.type(dest);
6700           top_dest = dest_type->isa_aryptr();
6701         }
6702       }
6703     }
6704   }
6705 
6706   ciMethod* trap_method = method();
6707   int trap_bci = bci();
6708   if (saved_jvms_before_guards != nullptr) {
6709     trap_method = alloc->jvms()->method();
6710     trap_bci = alloc->jvms()->bci();
6711   }
6712 
6713   bool negative_length_guard_generated = false;
6714 
6715   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6716       can_emit_guards && !src->is_top() && !dest->is_top()) {

6717     // validate arguments: enables transformation the ArrayCopyNode
6718     validated = true;
6719 
6720     RegionNode* slow_region = new RegionNode(1);
6721     record_for_igvn(slow_region);
6722 
6723     // (1) src and dest are arrays.
6724     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6725     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6726 
6727     // (2) src and dest arrays must have elements of the same BasicType
6728     // done at macro expansion or at Ideal transformation time
6729 
6730     // (4) src_offset must not be negative.
6731     generate_negative_guard(src_offset, slow_region);
6732 
6733     // (5) dest_offset must not be negative.
6734     generate_negative_guard(dest_offset, slow_region);
6735 
6736     // (7) src_offset + length must not exceed length of src.
6737     generate_limit_guard(src_offset, length,
6738                          load_array_length(src),
6739                          slow_region);
6740 
6741     // (8) dest_offset + length must not exceed length of dest.
6742     generate_limit_guard(dest_offset, length,
6743                          load_array_length(dest),
6744                          slow_region);
6745 
6746     // (6) length must not be negative.
6747     // This is also checked in generate_arraycopy() during macro expansion, but
6748     // we also have to check it here for the case where the ArrayCopyNode will
6749     // be eliminated by Escape Analysis.
6750     if (EliminateAllocations) {
6751       generate_negative_guard(length, slow_region);
6752       negative_length_guard_generated = true;
6753     }
6754 
6755     // (9) each element of an oop array must be assignable
6756     Node* dest_klass = load_object_klass(dest);
6757     Node* refined_dest_klass = dest_klass;
6758     if (src != dest) {
6759       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6760       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6761       slow_region->add_req(not_subtype_ctrl);







6762     }
6763 
6764     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6765     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6766     Node* src_klass = load_object_klass(src);
6767     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6768     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6769     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6770     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6771 
6772     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6773     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6774     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6775 
6776     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6777     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6778     generate_fair_guard(tst, slow_region);
6779 
6780     // TODO 8350865 This is too strong
6781     generate_fair_guard(flat_array_test(src), slow_region);
6782     generate_fair_guard(flat_array_test(dest), slow_region);
6783 
6784     {
6785       PreserveJVMState pjvms(this);
6786       set_control(_gvn.transform(slow_region));
6787       uncommon_trap(Deoptimization::Reason_intrinsic,
6788                     Deoptimization::Action_make_not_entrant);
6789       assert(stopped(), "Should be stopped");
6790     }
6791 
6792     const TypeKlassPtr* dest_klass_t = _gvn.type(refined_dest_klass)->is_klassptr();
6793     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6794     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6795     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6796   }
6797 
6798   if (stopped()) {
6799     return true;
6800   }
6801 
6802   Node* dest_klass = load_object_klass(dest);
6803   dest_klass = load_non_refined_array_klass(dest_klass);
6804 
6805   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6806                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6807                                           // so the compiler has a chance to eliminate them: during macro expansion,
6808                                           // we have to set their control (CastPP nodes are eliminated).
6809                                           load_object_klass(src), dest_klass,
6810                                           load_array_length(src), load_array_length(dest));
6811 
6812   ac->set_arraycopy(validated);
6813 
6814   Node* n = _gvn.transform(ac);
6815   if (n == ac) {
6816     ac->connect_outputs(this);
6817   } else {
6818     assert(validated, "shouldn't transform if all arguments not validated");
6819     set_all_memory(n);
6820   }
6821   clear_upper_avx();
6822 
6823 
6824   return true;
6825 }
6826 
6827 
6828 // Helper function which determines if an arraycopy immediately follows
6829 // an allocation, with no intervening tests or other escapes for the object.
< prev index next >