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/mountUnmountDisabler.hpp"
59 #include "runtime/objectMonitor.hpp"
60 #include "runtime/sharedRuntime.hpp"
61 #include "runtime/stubRoutines.hpp"
62 #include "utilities/macros.hpp"
63 #include "utilities/powerOfTwo.hpp"
64
65 //---------------------------make_vm_intrinsic----------------------------
66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
67 vmIntrinsicID id = m->intrinsic_id();
68 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
69
70 if (!m->is_loaded()) {
71 // Do not attempt to inline unloaded methods.
72 return nullptr;
73 }
74
75 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
76 bool is_available = false;
77
78 {
79 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
80 // the compiler must transition to '_thread_in_vm' state because both
81 // methods access VM-internal data.
302 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
303 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
304 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
305 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
306 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
307
308 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
309
310 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
311
312 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
313 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
314 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
315 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
316
317 case vmIntrinsics::_compressStringC:
318 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
319 case vmIntrinsics::_inflateStringC:
320 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
321
322 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
323 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
324 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
325 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
326 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
327 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
328 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
329 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
330 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
331
332 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
333 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
334 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
335 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
336 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
337 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
338 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
339 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
340 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
341
392 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
393 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
394 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
395 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
396 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
397 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
398 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
399 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
400 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
401
402 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
403 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
404 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
405 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
406 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
407 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
408 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
409 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
410 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
411
412 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
413 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
414 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
415 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
416 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
417
418 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
419 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
420 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
421 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
422 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
423 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
424 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
425 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
426 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
427 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
428 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
429 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
430 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
431 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
451 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
452 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
453 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
454
455 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
456 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
457 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
458 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
459
460 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
461 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
462 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
463 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
464 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
465
466 case vmIntrinsics::_loadFence:
467 case vmIntrinsics::_storeFence:
468 case vmIntrinsics::_storeStoreFence:
469 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
470
471 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
472
473 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
474 case vmIntrinsics::_currentThread: return inline_native_currentThread();
475 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
476
477 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
478 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
479
480 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
481 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
482
483 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
484 "endFirstTransition", true);
485 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
486 "startFinalTransition", true);
487 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
488 "startTransition", false);
489 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
490 "endTransition", false);
499 #endif
500 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
501 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
502 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
503 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
504 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
505 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
506 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
507 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
508 case vmIntrinsics::_getLength: return inline_native_getLength();
509 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
510 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
511 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
512 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
513 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
514 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
515 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
516
517 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
518 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
519
520 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
521
522 case vmIntrinsics::_isInstance:
523 case vmIntrinsics::_isHidden:
524 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
525
526 case vmIntrinsics::_floatToRawIntBits:
527 case vmIntrinsics::_floatToIntBits:
528 case vmIntrinsics::_intBitsToFloat:
529 case vmIntrinsics::_doubleToRawLongBits:
530 case vmIntrinsics::_doubleToLongBits:
531 case vmIntrinsics::_longBitsToDouble:
532 case vmIntrinsics::_floatToFloat16:
533 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
534 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
535 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
536 case vmIntrinsics::_floatIsFinite:
537 case vmIntrinsics::_floatIsInfinite:
538 case vmIntrinsics::_doubleIsFinite:
2316 case vmIntrinsics::_remainderUnsigned_l: {
2317 zero_check_long(argument(2));
2318 // Compile-time detect of null-exception
2319 if (stopped()) {
2320 return true; // keep the graph constructed so far
2321 }
2322 n = new UModLNode(control(), argument(0), argument(2));
2323 break;
2324 }
2325 default: fatal_unexpected_iid(id); break;
2326 }
2327 set_result(_gvn.transform(n));
2328 return true;
2329 }
2330
2331 //----------------------------inline_unsafe_access----------------------------
2332
2333 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2334 // Attempt to infer a sharper value type from the offset and base type.
2335 ciKlass* sharpened_klass = nullptr;
2336
2337 // See if it is an instance field, with an object type.
2338 if (alias_type->field() != nullptr) {
2339 if (alias_type->field()->type()->is_klass()) {
2340 sharpened_klass = alias_type->field()->type()->as_klass();
2341 }
2342 }
2343
2344 const TypeOopPtr* result = nullptr;
2345 // See if it is a narrow oop array.
2346 if (adr_type->isa_aryptr()) {
2347 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2348 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2349 if (elem_type != nullptr && elem_type->is_loaded()) {
2350 // Sharpen the value type.
2351 result = elem_type;
2352 }
2353 }
2354 }
2355
2356 // The sharpened class might be unloaded if there is no class loader
2357 // contraint in place.
2358 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2359 // Sharpen the value type.
2360 result = TypeOopPtr::make_from_klass(sharpened_klass);
2361 }
2362 if (result != nullptr) {
2363 #ifndef PRODUCT
2364 if (C->print_intrinsics() || C->print_inlining()) {
2365 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2366 tty->print(" sharpened value: "); result->dump(); tty->cr();
2367 }
2368 #endif
2369 }
2370 return result;
2371 }
2372
2373 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2374 switch (kind) {
2375 case Relaxed:
2376 return MO_UNORDERED;
2377 case Opaque:
2378 return MO_RELAXED;
2379 case Acquire:
2380 return MO_ACQUIRE;
2469 #endif // ASSERT
2470 }
2471 #endif //PRODUCT
2472
2473 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2474
2475 Node* receiver = argument(0); // type: oop
2476
2477 // Build address expression.
2478 Node* heap_base_oop = top();
2479
2480 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2481 Node* base = argument(1); // type: oop
2482 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2483 Node* offset = argument(2); // type: long
2484 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2485 // to be plain byte offsets, which are also the same as those accepted
2486 // by oopDesc::field_addr.
2487 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2488 "fieldOffset must be byte-scaled");
2489 // 32-bit machines ignore the high half!
2490 offset = ConvL2X(offset);
2491
2492 // Save state and restore on bailout
2493 SavedState old_state(this);
2494
2495 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2496 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2497
2498 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2499 if (type != T_OBJECT) {
2500 decorators |= IN_NATIVE; // off-heap primitive access
2501 } else {
2502 return false; // off-heap oop accesses are not supported
2503 }
2504 } else {
2505 heap_base_oop = base; // on-heap or mixed access
2506 }
2507
2508 // Can base be null? Otherwise, always on-heap access.
2512 decorators |= IN_HEAP;
2513 }
2514
2515 Node* val = is_store ? argument(4) : nullptr;
2516
2517 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2518 if (adr_type == TypePtr::NULL_PTR) {
2519 return false; // off-heap access with zero address
2520 }
2521
2522 // Try to categorize the address.
2523 Compile::AliasType* alias_type = C->alias_type(adr_type);
2524 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2525
2526 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2527 alias_type->adr_type() == TypeAryPtr::RANGE) {
2528 return false; // not supported
2529 }
2530
2531 bool mismatched = false;
2532 BasicType bt = alias_type->basic_type();
2533 if (bt != T_ILLEGAL) {
2534 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2535 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2536 // Alias type doesn't differentiate between byte[] and boolean[]).
2537 // Use address type to get the element type.
2538 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2539 }
2540 if (is_reference_type(bt, true)) {
2541 // accessing an array field with getReference is not a mismatch
2542 bt = T_OBJECT;
2543 }
2544 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2545 // Don't intrinsify mismatched object accesses
2546 return false;
2547 }
2548 mismatched = (bt != type);
2549 } else if (alias_type->adr_type()->isa_oopptr()) {
2550 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2551 }
2552
2553 old_state.discard();
2554 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2555
2556 if (mismatched) {
2557 decorators |= C2_MISMATCHED;
2558 }
2559
2560 // First guess at the value type.
2561 const Type *value_type = Type::get_const_basic_type(type);
2562
2563 // Figure out the memory ordering.
2564 decorators |= mo_decorator_for_access_kind(kind);
2565
2566 if (!is_store && type == T_OBJECT) {
2567 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2568 if (tjp != nullptr) {
2569 value_type = tjp;
2570 }
2571 }
2572
2573 receiver = null_check(receiver);
2574 if (stopped()) {
2575 return true;
2576 }
2577 // Heap pointers get a null-check from the interpreter,
2578 // as a courtesy. However, this is not guaranteed by Unsafe,
2579 // and it is not possible to fully distinguish unintended nulls
2580 // from intended ones in this API.
2581
2582 if (!is_store) {
2583 Node* p = nullptr;
2584 // Try to constant fold a load from a constant field
2585 ciField* field = alias_type->field();
2586 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2587 // final or stable field
2588 p = make_constant_from_field(field, heap_base_oop);
2589 }
2590
2591 if (p == nullptr) { // Could not constant fold the load
2592 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2593 // Normalize the value returned by getBoolean in the following cases
2594 if (type == T_BOOLEAN &&
2595 (mismatched ||
2596 heap_base_oop == top() || // - heap_base_oop is null or
2597 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2598 // and the unsafe access is made to large offset
2599 // (i.e., larger than the maximum offset necessary for any
2600 // field access)
2601 ) {
2602 IdealKit ideal = IdealKit(this);
2603 #define __ ideal.
2604 IdealVariable normalized_result(ideal);
2605 __ declarations_done();
2606 __ set(normalized_result, p);
2607 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2608 __ set(normalized_result, ideal.ConI(1));
2609 ideal.end_if();
2610 final_sync(ideal);
2611 p = __ value(normalized_result);
2612 #undef __
2616 p = gvn().transform(new CastP2XNode(nullptr, p));
2617 p = ConvX2UL(p);
2618 }
2619 // The load node has the control of the preceding MemBarCPUOrder. All
2620 // following nodes will have the control of the MemBarCPUOrder inserted at
2621 // the end of this method. So, pushing the load onto the stack at a later
2622 // point is fine.
2623 set_result(p);
2624 } else {
2625 if (bt == T_ADDRESS) {
2626 // Repackage the long as a pointer.
2627 val = ConvL2X(val);
2628 val = gvn().transform(new CastX2PNode(val));
2629 }
2630 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2631 }
2632
2633 return true;
2634 }
2635
2636 //----------------------------inline_unsafe_load_store----------------------------
2637 // This method serves a couple of different customers (depending on LoadStoreKind):
2638 //
2639 // LS_cmp_swap:
2640 //
2641 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2642 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2643 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2644 //
2645 // LS_cmp_swap_weak:
2646 //
2647 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2648 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2649 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2650 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2651 //
2652 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2653 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2654 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2655 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2818 }
2819 case LS_cmp_swap:
2820 case LS_cmp_swap_weak:
2821 case LS_get_add:
2822 break;
2823 default:
2824 ShouldNotReachHere();
2825 }
2826
2827 // Null check receiver.
2828 receiver = null_check(receiver);
2829 if (stopped()) {
2830 return true;
2831 }
2832
2833 int alias_idx = C->get_alias_index(adr_type);
2834
2835 if (is_reference_type(type)) {
2836 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2837
2838 // Transformation of a value which could be null pointer (CastPP #null)
2839 // could be delayed during Parse (for example, in adjust_map_after_if()).
2840 // Execute transformation here to avoid barrier generation in such case.
2841 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2842 newval = _gvn.makecon(TypePtr::NULL_PTR);
2843
2844 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2845 // Refine the value to a null constant, when it is known to be null
2846 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2847 }
2848 }
2849
2850 Node* result = nullptr;
2851 switch (kind) {
2852 case LS_cmp_exchange: {
2853 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2854 oldval, newval, value_type, type, decorators);
2855 break;
2856 }
2857 case LS_cmp_swap_weak:
2886 insert_mem_bar(Op_MemBarCPUOrder);
2887 switch(id) {
2888 case vmIntrinsics::_loadFence:
2889 insert_mem_bar(Op_LoadFence);
2890 return true;
2891 case vmIntrinsics::_storeFence:
2892 insert_mem_bar(Op_StoreFence);
2893 return true;
2894 case vmIntrinsics::_storeStoreFence:
2895 insert_mem_bar(Op_StoreStoreFence);
2896 return true;
2897 case vmIntrinsics::_fullFence:
2898 insert_mem_bar(Op_MemBarVolatile);
2899 return true;
2900 default:
2901 fatal_unexpected_iid(id);
2902 return false;
2903 }
2904 }
2905
2906 bool LibraryCallKit::inline_onspinwait() {
2907 insert_mem_bar(Op_OnSpinWait);
2908 return true;
2909 }
2910
2911 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2912 if (!kls->is_Con()) {
2913 return true;
2914 }
2915 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2916 if (klsptr == nullptr) {
2917 return true;
2918 }
2919 ciInstanceKlass* ik = klsptr->instance_klass();
2920 // don't need a guard for a klass that is already initialized
2921 return !ik->is_initialized();
2922 }
2923
2924 //----------------------------inline_unsafe_writeback0-------------------------
2925 // public native void Unsafe.writeback0(long address)
3004 Deoptimization::Action_make_not_entrant);
3005 }
3006 if (stopped()) {
3007 return true;
3008 }
3009 #endif //INCLUDE_JVMTI
3010
3011 Node* test = nullptr;
3012 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3013 // Note: The argument might still be an illegal value like
3014 // Serializable.class or Object[].class. The runtime will handle it.
3015 // But we must make an explicit check for initialization.
3016 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3017 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3018 // can generate code to load it as unsigned byte.
3019 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3020 Node* bits = intcon(InstanceKlass::fully_initialized);
3021 test = _gvn.transform(new SubINode(inst, bits));
3022 // The 'test' is non-zero if we need to take a slow path.
3023 }
3024
3025 Node* obj = new_instance(kls, test);
3026 set_result(obj);
3027 return true;
3028 }
3029
3030 //------------------------inline_native_time_funcs--------------
3031 // inline code for System.currentTimeMillis() and System.nanoTime()
3032 // these have the same type and signature
3033 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3034 const TypeFunc* tf = OptoRuntime::void_long_Type();
3035 const TypePtr* no_memory_effects = nullptr;
3036 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3037 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3038 #ifdef ASSERT
3039 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3040 assert(value_top == top(), "second value must be top");
3041 #endif
3042 set_result(value);
3043 return true;
3044 }
3045
3820 Node* thread = _gvn.transform(new ThreadLocalNode());
3821 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3822 Node* thread_obj_handle
3823 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3824 thread_obj_handle = _gvn.transform(thread_obj_handle);
3825 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3826 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3827
3828 // Change the _monitor_owner_id of the JavaThread
3829 Node* tid = load_field_from_object(arr, "tid", "J");
3830 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3831 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3832
3833 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3834 return true;
3835 }
3836
3837 const Type* LibraryCallKit::scopedValueCache_type() {
3838 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3839 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3840 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3841
3842 // Because we create the scopedValue cache lazily we have to make the
3843 // type of the result BotPTR.
3844 bool xk = etype->klass_is_exact();
3845 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3846 return objects_type;
3847 }
3848
3849 Node* LibraryCallKit::scopedValueCache_helper() {
3850 Node* thread = _gvn.transform(new ThreadLocalNode());
3851 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3852 // We cannot use immutable_memory() because we might flip onto a
3853 // different carrier thread, at which point we'll need to use that
3854 // carrier thread's cache.
3855 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3856 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3857 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3858 }
3859
3860 //------------------------inline_native_scopedValueCache------------------
3861 bool LibraryCallKit::inline_native_scopedValueCache() {
3862 Node* cache_obj_handle = scopedValueCache_helper();
3863 const Type* objects_type = scopedValueCache_type();
3864 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3865
4001 }
4002 return kls;
4003 }
4004
4005 //--------------------(inline_native_Class_query helpers)---------------------
4006 // Use this for JVM_ACC_INTERFACE.
4007 // Fall through if (mods & mask) == bits, take the guard otherwise.
4008 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4009 ByteSize offset, const Type* type, BasicType bt) {
4010 // Branch around if the given klass has the given modifier bit set.
4011 // Like generate_guard, adds a new path onto the region.
4012 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4013 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4014 Node* mask = intcon(modifier_mask);
4015 Node* bits = intcon(modifier_bits);
4016 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4017 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4018 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4019 return generate_fair_guard(bol, region);
4020 }
4021 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4022 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4023 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4024 }
4025
4026 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4027 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4028 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4029 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4030 }
4031
4032 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4033 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4034 }
4035
4036 //-------------------------inline_native_Class_query-------------------
4037 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4038 const Type* return_type = TypeInt::BOOL;
4039 Node* prim_return_value = top(); // what happens if it's a primitive class?
4040 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4126
4127
4128 case vmIntrinsics::_getSuperclass:
4129 // The rules here are somewhat unfortunate, but we can still do better
4130 // with random logic than with a JNI call.
4131 // Interfaces store null or Object as _super, but must report null.
4132 // Arrays store an intermediate super as _super, but must report Object.
4133 // Other types can report the actual _super.
4134 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4135 if (generate_array_guard(kls, region) != nullptr) {
4136 // A guard was added. If the guard is taken, it was an array.
4137 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4138 }
4139 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4140 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4141 if (generate_interface_guard(kls, region) != nullptr) {
4142 // A guard was added. If the guard is taken, it was an interface.
4143 phi->add_req(null());
4144 }
4145 // If we fall through, it's a plain class. Get its _super.
4146 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4147 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4148 null_ctl = top();
4149 kls = null_check_oop(kls, &null_ctl);
4150 if (null_ctl != top()) {
4151 // If the guard is taken, Object.superClass is null (both klass and mirror).
4152 region->add_req(null_ctl);
4153 phi ->add_req(null());
4154 }
4155 if (!stopped()) {
4156 query_value = load_mirror_from_klass(kls);
4157 }
4158 break;
4159
4160 default:
4161 fatal_unexpected_iid(id);
4162 break;
4163 }
4164
4165 // Fall-through is the normal case of a query to a real class.
4166 phi->init_req(1, query_value);
4167 region->init_req(1, control());
4168
4169 C->set_has_split_ifs(true); // Has chance for split-if optimization
4170 set_result(region, phi);
4171 return true;
4172 }
4173
4174 //-------------------------inline_Class_cast-------------------
4175 bool LibraryCallKit::inline_Class_cast() {
4176 Node* mirror = argument(0); // Class
4177 Node* obj = argument(1);
4178 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4179 if (mirror_con == nullptr) {
4180 return false; // dead path (mirror->is_top()).
4181 }
4182 if (obj == nullptr || obj->is_top()) {
4183 return false; // dead path
4184 }
4185 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4186
4187 // First, see if Class.cast() can be folded statically.
4188 // java_mirror_type() returns non-null for compile-time Class constants.
4189 ciType* tm = mirror_con->java_mirror_type();
4190 if (tm != nullptr && tm->is_klass() &&
4191 tp != nullptr) {
4192 if (!tp->is_loaded()) {
4193 // Don't use intrinsic when class is not loaded.
4194 return false;
4195 } else {
4196 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4197 if (static_res == Compile::SSC_always_true) {
4198 // isInstance() is true - fold the code.
4199 set_result(obj);
4200 return true;
4201 } else if (static_res == Compile::SSC_always_false) {
4202 // Don't use intrinsic, have to throw ClassCastException.
4203 // If the reference is null, the non-intrinsic bytecode will
4204 // be optimized appropriately.
4205 return false;
4206 }
4207 }
4208 }
4209
4210 // Bailout intrinsic and do normal inlining if exception path is frequent.
4211 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4212 return false;
4213 }
4214
4215 // Generate dynamic checks.
4216 // Class.cast() is java implementation of _checkcast bytecode.
4217 // Do checkcast (Parse::do_checkcast()) optimizations here.
4218
4219 mirror = null_check(mirror);
4220 // If mirror is dead, only null-path is taken.
4221 if (stopped()) {
4222 return true;
4223 }
4224
4225 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4226 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4227 RegionNode* region = new RegionNode(PATH_LIMIT);
4228 record_for_igvn(region);
4229
4230 // Now load the mirror's klass metaobject, and null-check it.
4231 // If kls is null, we have a primitive mirror and
4232 // nothing is an instance of a primitive type.
4233 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4234
4235 Node* res = top();
4236 if (!stopped()) {
4237 Node* bad_type_ctrl = top();
4238 // Do checkcast optimizations.
4239 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4240 region->init_req(_bad_type_path, bad_type_ctrl);
4241 }
4242 if (region->in(_prim_path) != top() ||
4243 region->in(_bad_type_path) != top()) {
4244 // Let Interpreter throw ClassCastException.
4245 PreserveJVMState pjvms(this);
4246 set_control(_gvn.transform(region));
4247 uncommon_trap(Deoptimization::Reason_intrinsic,
4248 Deoptimization::Action_maybe_recompile);
4249 }
4250 if (!stopped()) {
4251 set_result(res);
4252 }
4253 return true;
4254 }
4255
4256
4257 //--------------------------inline_native_subtype_check------------------------
4258 // This intrinsic takes the JNI calls out of the heart of
4259 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4260 bool LibraryCallKit::inline_native_subtype_check() {
4261 // Pull both arguments off the stack.
4262 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4263 args[0] = argument(0);
4264 args[1] = argument(1);
4265 Node* klasses[2]; // corresponding Klasses: superk, subk
4266 klasses[0] = klasses[1] = top();
4267
4268 enum {
4269 // A full decision tree on {superc is prim, subc is prim}:
4270 _prim_0_path = 1, // {P,N} => false
4271 // {P,P} & superc!=subc => false
4272 _prim_same_path, // {P,P} & superc==subc => true
4273 _prim_1_path, // {N,P} => false
4274 _ref_subtype_path, // {N,N} & subtype check wins => true
4275 _both_ref_path, // {N,N} & subtype check loses => false
4276 PATH_LIMIT
4277 };
4278
4279 RegionNode* region = new RegionNode(PATH_LIMIT);
4280 Node* phi = new PhiNode(region, TypeInt::BOOL);
4281 record_for_igvn(region);
4282
4283 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4284 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4285 int class_klass_offset = java_lang_Class::klass_offset();
4286
4287 // First null-check both mirrors and load each mirror's klass metaobject.
4288 int which_arg;
4289 for (which_arg = 0; which_arg <= 1; which_arg++) {
4290 Node* arg = args[which_arg];
4291 arg = null_check(arg);
4292 if (stopped()) break;
4293 args[which_arg] = arg;
4294
4295 Node* p = basic_plus_adr(arg, class_klass_offset);
4296 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4297 klasses[which_arg] = _gvn.transform(kls);
4298 }
4299
4300 // Having loaded both klasses, test each for null.
4301 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4302 for (which_arg = 0; which_arg <= 1; which_arg++) {
4303 Node* kls = klasses[which_arg];
4304 Node* null_ctl = top();
4305 kls = null_check_oop(kls, &null_ctl, never_see_null);
4306 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4307 region->init_req(prim_path, null_ctl);
4308 if (stopped()) break;
4309 klasses[which_arg] = kls;
4310 }
4311
4312 if (!stopped()) {
4313 // now we have two reference types, in klasses[0..1]
4314 Node* subk = klasses[1]; // the argument to isAssignableFrom
4315 Node* superk = klasses[0]; // the receiver
4316 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4317 // now we have a successful reference subtype check
4318 region->set_req(_ref_subtype_path, control());
4319 }
4320
4321 // If both operands are primitive (both klasses null), then
4322 // we must return true when they are identical primitives.
4323 // It is convenient to test this after the first null klass check.
4324 set_control(region->in(_prim_0_path)); // go back to first null check
4325 if (!stopped()) {
4326 // Since superc is primitive, make a guard for the superc==subc case.
4327 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4328 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4329 generate_guard(bol_eq, region, PROB_FAIR);
4330 if (region->req() == PATH_LIMIT+1) {
4331 // A guard was added. If the added guard is taken, superc==subc.
4332 region->swap_edges(PATH_LIMIT, _prim_same_path);
4333 region->del_req(PATH_LIMIT);
4334 }
4335 region->set_req(_prim_0_path, control()); // Not equal after all.
4336 }
4337
4338 // these are the only paths that produce 'true':
4339 phi->set_req(_prim_same_path, intcon(1));
4340 phi->set_req(_ref_subtype_path, intcon(1));
4341
4342 // pull together the cases:
4343 assert(region->req() == PATH_LIMIT, "sane region");
4344 for (uint i = 1; i < region->req(); i++) {
4345 Node* ctl = region->in(i);
4346 if (ctl == nullptr || ctl == top()) {
4347 region->set_req(i, top());
4348 phi ->set_req(i, top());
4349 } else if (phi->in(i) == nullptr) {
4350 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4351 }
4352 }
4353
4354 set_control(_gvn.transform(region));
4355 set_result(_gvn.transform(phi));
4356 return true;
4357 }
4358
4359 //---------------------generate_array_guard_common------------------------
4360 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4361 bool obj_array, bool not_array, Node** obj) {
4362
4363 if (stopped()) {
4364 return nullptr;
4365 }
4366
4367 // If obj_array/non_array==false/false:
4368 // Branch around if the given klass is in fact an array (either obj or prim).
4369 // If obj_array/non_array==false/true:
4370 // Branch around if the given klass is not an array klass of any kind.
4371 // If obj_array/non_array==true/true:
4372 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4373 // If obj_array/non_array==true/false:
4374 // Branch around if the kls is an oop array (Object[] or subtype)
4375 //
4376 // Like generate_guard, adds a new path onto the region.
4377 jint layout_con = 0;
4378 Node* layout_val = get_layout_helper(kls, layout_con);
4379 if (layout_val == nullptr) {
4380 bool query = (obj_array
4381 ? Klass::layout_helper_is_objArray(layout_con)
4382 : Klass::layout_helper_is_array(layout_con));
4383 if (query == not_array) {
4384 return nullptr; // never a branch
4385 } else { // always a branch
4386 Node* always_branch = control();
4387 if (region != nullptr)
4388 region->add_req(always_branch);
4389 set_control(top());
4390 return always_branch;
4391 }
4392 }
4393 // Now test the correct condition.
4394 jint nval = (obj_array
4395 ? (jint)(Klass::_lh_array_tag_type_value
4396 << Klass::_lh_array_tag_shift)
4397 : Klass::_lh_neutral_value);
4398 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4399 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4400 // invert the test if we are looking for a non-array
4401 if (not_array) btest = BoolTest(btest).negate();
4402 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4403 Node* ctrl = generate_fair_guard(bol, region);
4404 Node* is_array_ctrl = not_array ? control() : ctrl;
4405 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4406 // Keep track of the fact that 'obj' is an array to prevent
4407 // array specific accesses from floating above the guard.
4408 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4409 }
4410 return ctrl;
4411 }
4412
4413
4414 //-----------------------inline_native_newArray--------------------------
4415 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4416 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4417 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4418 Node* mirror;
4419 Node* count_val;
4420 if (uninitialized) {
4421 null_check_receiver();
4422 mirror = argument(1);
4423 count_val = argument(2);
4424 } else {
4425 mirror = argument(0);
4426 count_val = argument(1);
4427 }
4428
4429 mirror = null_check(mirror);
4430 // If mirror or obj is dead, only null-path is taken.
4431 if (stopped()) return true;
4432
4433 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4434 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4435 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4453 CallJavaNode* slow_call = nullptr;
4454 if (uninitialized) {
4455 // Generate optimized virtual call (holder class 'Unsafe' is final)
4456 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4457 } else {
4458 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4459 }
4460 Node* slow_result = set_results_for_java_call(slow_call);
4461 // this->control() comes from set_results_for_java_call
4462 result_reg->set_req(_slow_path, control());
4463 result_val->set_req(_slow_path, slow_result);
4464 result_io ->set_req(_slow_path, i_o());
4465 result_mem->set_req(_slow_path, reset_memory());
4466 }
4467
4468 set_control(normal_ctl);
4469 if (!stopped()) {
4470 // Normal case: The array type has been cached in the java.lang.Class.
4471 // The following call works fine even if the array type is polymorphic.
4472 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4473 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4474 result_reg->init_req(_normal_path, control());
4475 result_val->init_req(_normal_path, obj);
4476 result_io ->init_req(_normal_path, i_o());
4477 result_mem->init_req(_normal_path, reset_memory());
4478
4479 if (uninitialized) {
4480 // Mark the allocation so that zeroing is skipped
4481 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4482 alloc->maybe_set_complete(&_gvn);
4483 }
4484 }
4485
4486 // Return the combined state.
4487 set_i_o( _gvn.transform(result_io) );
4488 set_all_memory( _gvn.transform(result_mem));
4489
4490 C->set_has_split_ifs(true); // Has chance for split-if optimization
4491 set_result(result_reg, result_val);
4492 return true;
4541 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4542 { PreserveReexecuteState preexecs(this);
4543 jvms()->set_should_reexecute(true);
4544
4545 array_type_mirror = null_check(array_type_mirror);
4546 original = null_check(original);
4547
4548 // Check if a null path was taken unconditionally.
4549 if (stopped()) return true;
4550
4551 Node* orig_length = load_array_length(original);
4552
4553 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4554 klass_node = null_check(klass_node);
4555
4556 RegionNode* bailout = new RegionNode(1);
4557 record_for_igvn(bailout);
4558
4559 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4560 // Bail out if that is so.
4561 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4562 if (not_objArray != nullptr) {
4563 // Improve the klass node's type from the new optimistic assumption:
4564 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4565 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4566 Node* cast = new CastPPNode(control(), klass_node, akls);
4567 klass_node = _gvn.transform(cast);
4568 }
4569
4570 // Bail out if either start or end is negative.
4571 generate_negative_guard(start, bailout, &start);
4572 generate_negative_guard(end, bailout, &end);
4573
4574 Node* length = end;
4575 if (_gvn.type(start) != TypeInt::ZERO) {
4576 length = _gvn.transform(new SubINode(end, start));
4577 }
4578
4579 // Bail out if length is negative (i.e., if start > end).
4580 // Without this the new_array would throw
4581 // NegativeArraySizeException but IllegalArgumentException is what
4582 // should be thrown
4583 generate_negative_guard(length, bailout, &length);
4584
4585 // Bail out if start is larger than the original length
4586 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4587 generate_negative_guard(orig_tail, bailout, &orig_tail);
4588
4589 if (bailout->req() > 1) {
4590 PreserveJVMState pjvms(this);
4591 set_control(_gvn.transform(bailout));
4592 uncommon_trap(Deoptimization::Reason_intrinsic,
4593 Deoptimization::Action_maybe_recompile);
4594 }
4595
4596 if (!stopped()) {
4597 // How many elements will we copy from the original?
4598 // The answer is MinI(orig_tail, length).
4599 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4600
4601 // Generate a direct call to the right arraycopy function(s).
4602 // We know the copy is disjoint but we might not know if the
4603 // oop stores need checking.
4604 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4610 // to the copyOf to be validated, including that the copy to the
4611 // new array won't trigger an ArrayStoreException. That subtype
4612 // check can be optimized if we know something on the type of
4613 // the input array from type speculation.
4614 if (_gvn.type(klass_node)->singleton()) {
4615 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4616 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4617
4618 int test = C->static_subtype_check(superk, subk);
4619 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4620 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4621 if (t_original->speculative_type() != nullptr) {
4622 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4623 }
4624 }
4625 }
4626
4627 bool validated = false;
4628 // Reason_class_check rather than Reason_intrinsic because we
4629 // want to intrinsify even if this traps.
4630 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4631 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4632
4633 if (not_subtype_ctrl != top()) {
4634 PreserveJVMState pjvms(this);
4635 set_control(not_subtype_ctrl);
4636 uncommon_trap(Deoptimization::Reason_class_check,
4637 Deoptimization::Action_make_not_entrant);
4638 assert(stopped(), "Should be stopped");
4639 }
4640 validated = true;
4641 }
4642
4643 if (!stopped()) {
4644 newcopy = new_array(klass_node, length, 0); // no arguments to push
4645
4646 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4647 load_object_klass(original), klass_node);
4648 if (!is_copyOfRange) {
4649 ac->set_copyof(validated);
4650 } else {
4651 ac->set_copyofrange(validated);
4652 }
4653 Node* n = _gvn.transform(ac);
4654 if (n == ac) {
4655 ac->connect_outputs(this);
4656 } else {
4657 assert(validated, "shouldn't transform if all arguments not validated");
4658 set_all_memory(n);
4659 }
4660 }
4661 }
4662 } // original reexecute is set back here
4663
4664 C->set_has_split_ifs(true); // Has chance for split-if optimization
4696
4697 //-----------------------generate_method_call----------------------------
4698 // Use generate_method_call to make a slow-call to the real
4699 // method if the fast path fails. An alternative would be to
4700 // use a stub like OptoRuntime::slow_arraycopy_Java.
4701 // This only works for expanding the current library call,
4702 // not another intrinsic. (E.g., don't use this for making an
4703 // arraycopy call inside of the copyOf intrinsic.)
4704 CallJavaNode*
4705 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4706 // When compiling the intrinsic method itself, do not use this technique.
4707 guarantee(callee() != C->method(), "cannot make slow-call to self");
4708
4709 ciMethod* method = callee();
4710 // ensure the JVMS we have will be correct for this call
4711 guarantee(method_id == method->intrinsic_id(), "must match");
4712
4713 const TypeFunc* tf = TypeFunc::make(method);
4714 if (res_not_null) {
4715 assert(tf->return_type() == T_OBJECT, "");
4716 const TypeTuple* range = tf->range();
4717 const Type** fields = TypeTuple::fields(range->cnt());
4718 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4719 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4720 tf = TypeFunc::make(tf->domain(), new_range);
4721 }
4722 CallJavaNode* slow_call;
4723 if (is_static) {
4724 assert(!is_virtual, "");
4725 slow_call = new CallStaticJavaNode(C, tf,
4726 SharedRuntime::get_resolve_static_call_stub(), method);
4727 } else if (is_virtual) {
4728 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4729 int vtable_index = Method::invalid_vtable_index;
4730 if (UseInlineCaches) {
4731 // Suppress the vtable call
4732 } else {
4733 // hashCode and clone are not a miranda methods,
4734 // so the vtable index is fixed.
4735 // No need to use the linkResolver to get it.
4736 vtable_index = method->vtable_index();
4737 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4738 "bad index %d", vtable_index);
4739 }
4740 slow_call = new CallDynamicJavaNode(tf,
4757 set_edges_for_java_call(slow_call);
4758 return slow_call;
4759 }
4760
4761
4762 /**
4763 * Build special case code for calls to hashCode on an object. This call may
4764 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4765 * slightly different code.
4766 */
4767 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4768 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4769 assert(!(is_virtual && is_static), "either virtual, special, or static");
4770
4771 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4772
4773 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4774 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4775 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4776 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4777 Node* obj = nullptr;
4778 if (!is_static) {
4779 // Check for hashing null object
4780 obj = null_check_receiver();
4781 if (stopped()) return true; // unconditionally null
4782 result_reg->init_req(_null_path, top());
4783 result_val->init_req(_null_path, top());
4784 } else {
4785 // Do a null check, and return zero if null.
4786 // System.identityHashCode(null) == 0
4787 obj = argument(0);
4788 Node* null_ctl = top();
4789 obj = null_check_oop(obj, &null_ctl);
4790 result_reg->init_req(_null_path, null_ctl);
4791 result_val->init_req(_null_path, _gvn.intcon(0));
4792 }
4793
4794 // Unconditionally null? Then return right away.
4795 if (stopped()) {
4796 set_control( result_reg->in(_null_path));
4797 if (!stopped())
4798 set_result(result_val->in(_null_path));
4799 return true;
4800 }
4801
4802 // We only go to the fast case code if we pass a number of guards. The
4803 // paths which do not pass are accumulated in the slow_region.
4804 RegionNode* slow_region = new RegionNode(1);
4805 record_for_igvn(slow_region);
4806
4807 // If this is a virtual call, we generate a funny guard. We pull out
4808 // the vtable entry corresponding to hashCode() from the target object.
4809 // If the target method which we are calling happens to be the native
4810 // Object hashCode() method, we pass the guard. We do not need this
4811 // guard for non-virtual calls -- the caller is known to be the native
4812 // Object hashCode().
4813 if (is_virtual) {
4814 // After null check, get the object's klass.
4815 Node* obj_klass = load_object_klass(obj);
4816 generate_virtual_guard(obj_klass, slow_region);
4817 }
4818
4819 // Get the header out of the object, use LoadMarkNode when available
4820 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4821 // The control of the load must be null. Otherwise, the load can move before
4822 // the null check after castPP removal.
4823 Node* no_ctrl = nullptr;
4824 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4825
4826 if (!UseObjectMonitorTable) {
4827 // Test the header to see if it is safe to read w.r.t. locking.
4828 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4829 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4830 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4831 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4832 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4833
4834 generate_slow_guard(test_monitor, slow_region);
4835 }
4836
4837 // Get the hash value and check to see that it has been properly assigned.
4838 // We depend on hash_mask being at most 32 bits and avoid the use of
4839 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4840 // vm: see markWord.hpp.
4841 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4842 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4843 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4844 // This hack lets the hash bits live anywhere in the mark object now, as long
4845 // as the shift drops the relevant bits into the low 32 bits. Note that
4846 // Java spec says that HashCode is an int so there's no point in capturing
4847 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4875 // this->control() comes from set_results_for_java_call
4876 result_reg->init_req(_slow_path, control());
4877 result_val->init_req(_slow_path, slow_result);
4878 result_io ->set_req(_slow_path, i_o());
4879 result_mem ->set_req(_slow_path, reset_memory());
4880 }
4881
4882 // Return the combined state.
4883 set_i_o( _gvn.transform(result_io) );
4884 set_all_memory( _gvn.transform(result_mem));
4885
4886 set_result(result_reg, result_val);
4887 return true;
4888 }
4889
4890 //---------------------------inline_native_getClass----------------------------
4891 // public final native Class<?> java.lang.Object.getClass();
4892 //
4893 // Build special case code for calls to getClass on an object.
4894 bool LibraryCallKit::inline_native_getClass() {
4895 Node* obj = null_check_receiver();
4896 if (stopped()) return true;
4897 set_result(load_mirror_from_klass(load_object_klass(obj)));
4898 return true;
4899 }
4900
4901 //-----------------inline_native_Reflection_getCallerClass---------------------
4902 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4903 //
4904 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4905 //
4906 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4907 // in that it must skip particular security frames and checks for
4908 // caller sensitive methods.
4909 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4910 #ifndef PRODUCT
4911 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4912 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4913 }
4914 #endif
4915
5297 // not cloneable or finalizer => slow path to out-of-line Object.clone
5298 //
5299 // The general case has two steps, allocation and copying.
5300 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5301 //
5302 // Copying also has two cases, oop arrays and everything else.
5303 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5304 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5305 //
5306 // These steps fold up nicely if and when the cloned object's klass
5307 // can be sharply typed as an object array, a type array, or an instance.
5308 //
5309 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5310 PhiNode* result_val;
5311
5312 // Set the reexecute bit for the interpreter to reexecute
5313 // the bytecode that invokes Object.clone if deoptimization happens.
5314 { PreserveReexecuteState preexecs(this);
5315 jvms()->set_should_reexecute(true);
5316
5317 Node* obj = null_check_receiver();
5318 if (stopped()) return true;
5319
5320 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5321
5322 // If we are going to clone an instance, we need its exact type to
5323 // know the number and types of fields to convert the clone to
5324 // loads/stores. Maybe a speculative type can help us.
5325 if (!obj_type->klass_is_exact() &&
5326 obj_type->speculative_type() != nullptr &&
5327 obj_type->speculative_type()->is_instance_klass()) {
5328 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5329 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5330 !spec_ik->has_injected_fields()) {
5331 if (!obj_type->isa_instptr() ||
5332 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5333 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5334 }
5335 }
5336 }
5337
5338 // Conservatively insert a memory barrier on all memory slices.
5339 // Do not let writes into the original float below the clone.
5340 insert_mem_bar(Op_MemBarCPUOrder);
5341
5342 // paths into result_reg:
5343 enum {
5344 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5345 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5346 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5347 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5348 PATH_LIMIT
5349 };
5350 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5351 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5352 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5353 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5354 record_for_igvn(result_reg);
5355
5356 Node* obj_klass = load_object_klass(obj);
5357 Node* array_obj = obj;
5358 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5359 if (array_ctl != nullptr) {
5360 // It's an array.
5361 PreserveJVMState pjvms(this);
5362 set_control(array_ctl);
5363 Node* obj_length = load_array_length(array_obj);
5364 Node* array_size = nullptr; // Size of the array without object alignment padding.
5365 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5366
5367 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5368 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5369 // If it is an oop array, it requires very special treatment,
5370 // because gc barriers are required when accessing the array.
5371 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5372 if (is_obja != nullptr) {
5373 PreserveJVMState pjvms2(this);
5374 set_control(is_obja);
5375 // Generate a direct call to the right arraycopy function(s).
5376 // Clones are always tightly coupled.
5377 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5378 ac->set_clone_oop_array();
5379 Node* n = _gvn.transform(ac);
5380 assert(n == ac, "cannot disappear");
5381 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5382
5383 result_reg->init_req(_objArray_path, control());
5384 result_val->init_req(_objArray_path, alloc_obj);
5385 result_i_o ->set_req(_objArray_path, i_o());
5386 result_mem ->set_req(_objArray_path, reset_memory());
5387 }
5388 }
5389 // Otherwise, there are no barriers to worry about.
5390 // (We can dispense with card marks if we know the allocation
5391 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5392 // causes the non-eden paths to take compensating steps to
5393 // simulate a fresh allocation, so that no further
5394 // card marks are required in compiled code to initialize
5395 // the object.)
5396
5397 if (!stopped()) {
5398 copy_to_clone(array_obj, alloc_obj, array_size, true);
5399
5400 // Present the results of the copy.
5401 result_reg->init_req(_array_path, control());
5402 result_val->init_req(_array_path, alloc_obj);
5403 result_i_o ->set_req(_array_path, i_o());
5404 result_mem ->set_req(_array_path, reset_memory());
5405 }
5406 }
5407
5408 // We only go to the instance fast case code if we pass a number of guards.
5409 // The paths which do not pass are accumulated in the slow_region.
5410 RegionNode* slow_region = new RegionNode(1);
5411 record_for_igvn(slow_region);
5412 if (!stopped()) {
5413 // It's an instance (we did array above). Make the slow-path tests.
5414 // If this is a virtual call, we generate a funny guard. We grab
5415 // the vtable entry corresponding to clone() from the target object.
5416 // If the target method which we are calling happens to be the
5417 // Object clone() method, we pass the guard. We do not need this
5418 // guard for non-virtual calls; the caller is known to be the native
5419 // Object clone().
5420 if (is_virtual) {
5421 generate_virtual_guard(obj_klass, slow_region);
5422 }
5423
5424 // The object must be easily cloneable and must not have a finalizer.
5425 // Both of these conditions may be checked in a single test.
5426 // We could optimize the test further, but we don't care.
5427 generate_misc_flags_guard(obj_klass,
5428 // Test both conditions:
5429 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5430 // Must be cloneable but not finalizer:
5431 KlassFlags::_misc_is_cloneable_fast,
5523 set_jvms(sfpt->jvms());
5524 _reexecute_sp = jvms()->sp();
5525
5526 return saved_jvms;
5527 }
5528 }
5529 }
5530 return nullptr;
5531 }
5532
5533 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5534 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5535 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5536 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5537 uint size = alloc->req();
5538 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5539 old_jvms->set_map(sfpt);
5540 for (uint i = 0; i < size; i++) {
5541 sfpt->init_req(i, alloc->in(i));
5542 }
5543 // re-push array length for deoptimization
5544 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5545 old_jvms->set_sp(old_jvms->sp()+1);
5546 old_jvms->set_monoff(old_jvms->monoff()+1);
5547 old_jvms->set_scloff(old_jvms->scloff()+1);
5548 old_jvms->set_endoff(old_jvms->endoff()+1);
5549 old_jvms->set_should_reexecute(true);
5550
5551 sfpt->set_i_o(map()->i_o());
5552 sfpt->set_memory(map()->memory());
5553 sfpt->set_control(map()->control());
5554 return sfpt;
5555 }
5556
5557 // In case of a deoptimization, we restart execution at the
5558 // allocation, allocating a new array. We would leave an uninitialized
5559 // array in the heap that GCs wouldn't expect. Move the allocation
5560 // after the traps so we don't allocate the array if we
5561 // deoptimize. This is possible because tightly_coupled_allocation()
5562 // guarantees there's no observer of the allocated array at this point
5563 // and the control flow is simple enough.
5564 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5565 int saved_reexecute_sp, uint new_idx) {
5566 if (saved_jvms_before_guards != nullptr && !stopped()) {
5567 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5568
5569 assert(alloc != nullptr, "only with a tightly coupled allocation");
5570 // restore JVM state to the state at the arraycopy
5571 saved_jvms_before_guards->map()->set_control(map()->control());
5572 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5573 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5574 // If we've improved the types of some nodes (null check) while
5575 // emitting the guards, propagate them to the current state
5576 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5577 set_jvms(saved_jvms_before_guards);
5578 _reexecute_sp = saved_reexecute_sp;
5579
5580 // Remove the allocation from above the guards
5581 CallProjections callprojs;
5582 alloc->extract_projections(&callprojs, true);
5583 InitializeNode* init = alloc->initialization();
5584 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5585 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5586 init->replace_mem_projs_by(alloc_mem, C);
5587
5588 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5589 // the allocation (i.e. is only valid if the allocation succeeds):
5590 // 1) replace CastIINode with AllocateArrayNode's length here
5591 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5592 //
5593 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5594 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5595 Node* init_control = init->proj_out(TypeFunc::Control);
5596 Node* alloc_length = alloc->Ideal_length();
5597 #ifdef ASSERT
5598 Node* prev_cast = nullptr;
5599 #endif
5600 for (uint i = 0; i < init_control->outcnt(); i++) {
5601 Node* init_out = init_control->raw_out(i);
5602 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5603 #ifdef ASSERT
5604 if (prev_cast == nullptr) {
5605 prev_cast = init_out;
5607 if (prev_cast->cmp(*init_out) == false) {
5608 prev_cast->dump();
5609 init_out->dump();
5610 assert(false, "not equal CastIINode");
5611 }
5612 }
5613 #endif
5614 C->gvn_replace_by(init_out, alloc_length);
5615 }
5616 }
5617 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5618
5619 // move the allocation here (after the guards)
5620 _gvn.hash_delete(alloc);
5621 alloc->set_req(TypeFunc::Control, control());
5622 alloc->set_req(TypeFunc::I_O, i_o());
5623 Node *mem = reset_memory();
5624 set_all_memory(mem);
5625 alloc->set_req(TypeFunc::Memory, mem);
5626 set_control(init->proj_out_or_null(TypeFunc::Control));
5627 set_i_o(callprojs.fallthrough_ioproj);
5628
5629 // Update memory as done in GraphKit::set_output_for_allocation()
5630 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5631 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5632 if (ary_type->isa_aryptr() && length_type != nullptr) {
5633 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5634 }
5635 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5636 int elemidx = C->get_alias_index(telemref);
5637 // Need to properly move every memory projection for the Initialize
5638 #ifdef ASSERT
5639 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5640 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5641 #endif
5642 auto move_proj = [&](ProjNode* proj) {
5643 int alias_idx = C->get_alias_index(proj->adr_type());
5644 assert(alias_idx == Compile::AliasIdxRaw ||
5645 alias_idx == elemidx ||
5646 alias_idx == mark_idx ||
5647 alias_idx == klass_idx, "should be raw memory or array element type");
5957 top_src = src_type->isa_aryptr();
5958 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5959 src_spec = true;
5960 }
5961 if (!has_dest) {
5962 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5963 dest_type = _gvn.type(dest);
5964 top_dest = dest_type->isa_aryptr();
5965 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5966 dest_spec = true;
5967 }
5968 }
5969 }
5970
5971 if (has_src && has_dest && can_emit_guards) {
5972 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5973 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5974 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5975 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5976
5977 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5978 // If both arrays are object arrays then having the exact types
5979 // for both will remove the need for a subtype check at runtime
5980 // before the call and may make it possible to pick a faster copy
5981 // routine (without a subtype check on every element)
5982 // Do we have the exact type of src?
5983 bool could_have_src = src_spec;
5984 // Do we have the exact type of dest?
5985 bool could_have_dest = dest_spec;
5986 ciKlass* src_k = nullptr;
5987 ciKlass* dest_k = nullptr;
5988 if (!src_spec) {
5989 src_k = src_type->speculative_type_not_null();
5990 if (src_k != nullptr && src_k->is_array_klass()) {
5991 could_have_src = true;
5992 }
5993 }
5994 if (!dest_spec) {
5995 dest_k = dest_type->speculative_type_not_null();
5996 if (dest_k != nullptr && dest_k->is_array_klass()) {
5997 could_have_dest = true;
5998 }
5999 }
6000 if (could_have_src && could_have_dest) {
6001 // If we can have both exact types, emit the missing guards
6002 if (could_have_src && !src_spec) {
6003 src = maybe_cast_profiled_obj(src, src_k, true);
6004 }
6005 if (could_have_dest && !dest_spec) {
6006 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6007 }
6008 }
6009 }
6010 }
6011
6012 ciMethod* trap_method = method();
6013 int trap_bci = bci();
6014 if (saved_jvms_before_guards != nullptr) {
6015 trap_method = alloc->jvms()->method();
6016 trap_bci = alloc->jvms()->bci();
6017 }
6018
6019 bool negative_length_guard_generated = false;
6020
6021 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6022 can_emit_guards &&
6023 !src->is_top() && !dest->is_top()) {
6024 // validate arguments: enables transformation the ArrayCopyNode
6025 validated = true;
6026
6027 RegionNode* slow_region = new RegionNode(1);
6028 record_for_igvn(slow_region);
6029
6030 // (1) src and dest are arrays.
6031 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6032 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6033
6034 // (2) src and dest arrays must have elements of the same BasicType
6035 // done at macro expansion or at Ideal transformation time
6036
6037 // (4) src_offset must not be negative.
6038 generate_negative_guard(src_offset, slow_region);
6039
6040 // (5) dest_offset must not be negative.
6041 generate_negative_guard(dest_offset, slow_region);
6042
6043 // (7) src_offset + length must not exceed length of src.
6044 generate_limit_guard(src_offset, length,
6045 load_array_length(src),
6046 slow_region);
6047
6048 // (8) dest_offset + length must not exceed length of dest.
6049 generate_limit_guard(dest_offset, length,
6050 load_array_length(dest),
6051 slow_region);
6052
6053 // (6) length must not be negative.
6054 // This is also checked in generate_arraycopy() during macro expansion, but
6055 // we also have to check it here for the case where the ArrayCopyNode will
6056 // be eliminated by Escape Analysis.
6057 if (EliminateAllocations) {
6058 generate_negative_guard(length, slow_region);
6059 negative_length_guard_generated = true;
6060 }
6061
6062 // (9) each element of an oop array must be assignable
6063 Node* dest_klass = load_object_klass(dest);
6064 if (src != dest) {
6065 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6066
6067 if (not_subtype_ctrl != top()) {
6068 PreserveJVMState pjvms(this);
6069 set_control(not_subtype_ctrl);
6070 uncommon_trap(Deoptimization::Reason_intrinsic,
6071 Deoptimization::Action_make_not_entrant);
6072 assert(stopped(), "Should be stopped");
6073 }
6074 }
6075 {
6076 PreserveJVMState pjvms(this);
6077 set_control(_gvn.transform(slow_region));
6078 uncommon_trap(Deoptimization::Reason_intrinsic,
6079 Deoptimization::Action_make_not_entrant);
6080 assert(stopped(), "Should be stopped");
6081 }
6082
6083 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6084 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6085 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6086 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6087 }
6088
6089 if (stopped()) {
6090 return true;
6091 }
6092
6093 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6094 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6095 // so the compiler has a chance to eliminate them: during macro expansion,
6096 // we have to set their control (CastPP nodes are eliminated).
6097 load_object_klass(src), load_object_klass(dest),
6098 load_array_length(src), load_array_length(dest));
6099
6100 ac->set_arraycopy(validated);
6101
6102 Node* n = _gvn.transform(ac);
6103 if (n == ac) {
6104 ac->connect_outputs(this);
6105 } else {
6106 assert(validated, "shouldn't transform if all arguments not validated");
6107 set_all_memory(n);
6108 }
6109 clear_upper_avx();
6110
6111
6112 return true;
6113 }
6114
6115
6116 // Helper function which determines if an arraycopy immediately follows
6117 // 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/globals.hpp"
68 #include "runtime/jniHandles.inline.hpp"
69 #include "runtime/mountUnmountDisabler.hpp"
70 #include "runtime/objectMonitor.hpp"
71 #include "runtime/sharedRuntime.hpp"
72 #include "runtime/stubRoutines.hpp"
73 #include "utilities/globalDefinitions.hpp"
74 #include "utilities/macros.hpp"
75 #include "utilities/powerOfTwo.hpp"
76
77 //---------------------------make_vm_intrinsic----------------------------
78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
79 vmIntrinsicID id = m->intrinsic_id();
80 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
81
82 if (!m->is_loaded()) {
83 // Do not attempt to inline unloaded methods.
84 return nullptr;
85 }
86
87 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
88 bool is_available = false;
89
90 {
91 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
92 // the compiler must transition to '_thread_in_vm' state because both
93 // methods access VM-internal data.
314 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
315 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
316 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
317 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
318 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
319
320 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
321
322 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
323
324 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
325 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
326 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
327 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
328
329 case vmIntrinsics::_compressStringC:
330 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
331 case vmIntrinsics::_inflateStringC:
332 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
333
334 case vmIntrinsics::_makePrivateBuffer: return inline_unsafe_make_private_buffer();
335 case vmIntrinsics::_finishPrivateBuffer: return inline_unsafe_finish_private_buffer();
336 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
337 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
338 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
339 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
340 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
341 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
342 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
343 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
344 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
345
346 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
347 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
348 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
349 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
350 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
351 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
352 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
353 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
354 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
355
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 case vmIntrinsics::_getFieldMap: return inline_getFieldMap();
492
493 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
494
495 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
496 case vmIntrinsics::_currentThread: return inline_native_currentThread();
497 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
498
499 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
500 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
501
502 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
503 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
504
505 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
506 "endFirstTransition", true);
507 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
508 "startFinalTransition", true);
509 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
510 "startTransition", false);
511 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
512 "endTransition", false);
521 #endif
522 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
523 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
524 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
525 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
526 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
527 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
528 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
529 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
530 case vmIntrinsics::_getLength: return inline_native_getLength();
531 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
532 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
533 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
534 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
535 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
536 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
537 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
538
539 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
540 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
541 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
542 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
543 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
544 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
545 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
546 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
547
548 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
549
550 case vmIntrinsics::_isInstance:
551 case vmIntrinsics::_isHidden:
552 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
553
554 case vmIntrinsics::_floatToRawIntBits:
555 case vmIntrinsics::_floatToIntBits:
556 case vmIntrinsics::_intBitsToFloat:
557 case vmIntrinsics::_doubleToRawLongBits:
558 case vmIntrinsics::_doubleToLongBits:
559 case vmIntrinsics::_longBitsToDouble:
560 case vmIntrinsics::_floatToFloat16:
561 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
562 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
563 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
564 case vmIntrinsics::_floatIsFinite:
565 case vmIntrinsics::_floatIsInfinite:
566 case vmIntrinsics::_doubleIsFinite:
2344 case vmIntrinsics::_remainderUnsigned_l: {
2345 zero_check_long(argument(2));
2346 // Compile-time detect of null-exception
2347 if (stopped()) {
2348 return true; // keep the graph constructed so far
2349 }
2350 n = new UModLNode(control(), argument(0), argument(2));
2351 break;
2352 }
2353 default: fatal_unexpected_iid(id); break;
2354 }
2355 set_result(_gvn.transform(n));
2356 return true;
2357 }
2358
2359 //----------------------------inline_unsafe_access----------------------------
2360
2361 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2362 // Attempt to infer a sharper value type from the offset and base type.
2363 ciKlass* sharpened_klass = nullptr;
2364 bool null_free = false;
2365
2366 // See if it is an instance field, with an object type.
2367 if (alias_type->field() != nullptr) {
2368 if (alias_type->field()->type()->is_klass()) {
2369 sharpened_klass = alias_type->field()->type()->as_klass();
2370 null_free = alias_type->field()->is_null_free();
2371 }
2372 }
2373
2374 const TypeOopPtr* result = nullptr;
2375 // See if it is a narrow oop array.
2376 if (adr_type->isa_aryptr()) {
2377 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2378 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2379 null_free = adr_type->is_aryptr()->is_null_free();
2380 if (elem_type != nullptr && elem_type->is_loaded()) {
2381 // Sharpen the value type.
2382 result = elem_type;
2383 }
2384 }
2385 }
2386
2387 // The sharpened class might be unloaded if there is no class loader
2388 // contraint in place.
2389 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2390 // Sharpen the value type.
2391 result = TypeOopPtr::make_from_klass(sharpened_klass);
2392 if (null_free) {
2393 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2394 }
2395 }
2396 if (result != nullptr) {
2397 #ifndef PRODUCT
2398 if (C->print_intrinsics() || C->print_inlining()) {
2399 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2400 tty->print(" sharpened value: "); result->dump(); tty->cr();
2401 }
2402 #endif
2403 }
2404 return result;
2405 }
2406
2407 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2408 switch (kind) {
2409 case Relaxed:
2410 return MO_UNORDERED;
2411 case Opaque:
2412 return MO_RELAXED;
2413 case Acquire:
2414 return MO_ACQUIRE;
2503 #endif // ASSERT
2504 }
2505 #endif //PRODUCT
2506
2507 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2508
2509 Node* receiver = argument(0); // type: oop
2510
2511 // Build address expression.
2512 Node* heap_base_oop = top();
2513
2514 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2515 Node* base = argument(1); // type: oop
2516 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2517 Node* offset = argument(2); // type: long
2518 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2519 // to be plain byte offsets, which are also the same as those accepted
2520 // by oopDesc::field_addr.
2521 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2522 "fieldOffset must be byte-scaled");
2523
2524 if (base->is_InlineType()) {
2525 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2526 InlineTypeNode* vt = base->as_InlineType();
2527 if (offset->is_Con()) {
2528 long off = find_long_con(offset, 0);
2529 ciInlineKlass* vk = vt->type()->inline_klass();
2530 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2531 return false;
2532 }
2533
2534 ciField* field = vk->get_non_flat_field_by_offset(off);
2535 if (field != nullptr) {
2536 BasicType bt = type2field[field->type()->basic_type()];
2537 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2538 bt = T_OBJECT;
2539 }
2540 if (bt == type && !field->is_flat()) {
2541 Node* value = vt->field_value_by_offset(off, false);
2542 if (value->is_InlineType()) {
2543 value = value->as_InlineType()->adjust_scalarization_depth(this);
2544 }
2545 set_result(value);
2546 return true;
2547 }
2548 }
2549 }
2550 {
2551 // Re-execute the unsafe access if allocation triggers deoptimization.
2552 PreserveReexecuteState preexecs(this);
2553 jvms()->set_should_reexecute(true);
2554 vt = vt->buffer(this);
2555 }
2556 base = vt->get_oop();
2557 }
2558
2559 // 32-bit machines ignore the high half!
2560 offset = ConvL2X(offset);
2561
2562 // Save state and restore on bailout
2563 SavedState old_state(this);
2564
2565 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2566 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2567
2568 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2569 if (type != T_OBJECT) {
2570 decorators |= IN_NATIVE; // off-heap primitive access
2571 } else {
2572 return false; // off-heap oop accesses are not supported
2573 }
2574 } else {
2575 heap_base_oop = base; // on-heap or mixed access
2576 }
2577
2578 // Can base be null? Otherwise, always on-heap access.
2582 decorators |= IN_HEAP;
2583 }
2584
2585 Node* val = is_store ? argument(4) : nullptr;
2586
2587 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2588 if (adr_type == TypePtr::NULL_PTR) {
2589 return false; // off-heap access with zero address
2590 }
2591
2592 // Try to categorize the address.
2593 Compile::AliasType* alias_type = C->alias_type(adr_type);
2594 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2595
2596 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2597 alias_type->adr_type() == TypeAryPtr::RANGE) {
2598 return false; // not supported
2599 }
2600
2601 bool mismatched = false;
2602 BasicType bt = T_ILLEGAL;
2603 ciField* field = nullptr;
2604 if (adr_type->isa_instptr()) {
2605 const TypeInstPtr* instptr = adr_type->is_instptr();
2606 ciInstanceKlass* k = instptr->instance_klass();
2607 int off = instptr->offset();
2608 if (instptr->const_oop() != nullptr &&
2609 k == ciEnv::current()->Class_klass() &&
2610 instptr->offset() >= (k->size_helper() * wordSize)) {
2611 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2612 field = k->get_field_by_offset(off, true);
2613 } else {
2614 field = k->get_non_flat_field_by_offset(off);
2615 }
2616 if (field != nullptr) {
2617 bt = type2field[field->type()->basic_type()];
2618 }
2619 if (bt != alias_type->basic_type()) {
2620 // Type mismatch. Is it an access to a nested flat field?
2621 field = k->get_field_by_offset(off, false);
2622 if (field != nullptr) {
2623 bt = type2field[field->type()->basic_type()];
2624 }
2625 }
2626 assert(bt == alias_type->basic_type(), "should match");
2627 } else {
2628 bt = alias_type->basic_type();
2629 }
2630
2631 if (bt != T_ILLEGAL) {
2632 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2633 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2634 // Alias type doesn't differentiate between byte[] and boolean[]).
2635 // Use address type to get the element type.
2636 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2637 }
2638 if (is_reference_type(bt, true)) {
2639 // accessing an array field with getReference is not a mismatch
2640 bt = T_OBJECT;
2641 }
2642 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2643 // Don't intrinsify mismatched object accesses
2644 return false;
2645 }
2646 mismatched = (bt != type);
2647 } else if (alias_type->adr_type()->isa_oopptr()) {
2648 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2649 }
2650
2651 old_state.discard();
2652 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2653
2654 if (mismatched) {
2655 decorators |= C2_MISMATCHED;
2656 }
2657
2658 // First guess at the value type.
2659 const Type *value_type = Type::get_const_basic_type(type);
2660
2661 // Figure out the memory ordering.
2662 decorators |= mo_decorator_for_access_kind(kind);
2663
2664 if (!is_store) {
2665 if (type == T_OBJECT) {
2666 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2667 if (tjp != nullptr) {
2668 value_type = tjp;
2669 }
2670 }
2671 }
2672
2673 receiver = null_check(receiver);
2674 if (stopped()) {
2675 return true;
2676 }
2677 // Heap pointers get a null-check from the interpreter,
2678 // as a courtesy. However, this is not guaranteed by Unsafe,
2679 // and it is not possible to fully distinguish unintended nulls
2680 // from intended ones in this API.
2681
2682 if (!is_store) {
2683 Node* p = nullptr;
2684 // Try to constant fold a load from a constant field
2685
2686 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2687 // final or stable field
2688 p = make_constant_from_field(field, heap_base_oop);
2689 }
2690
2691 if (p == nullptr) { // Could not constant fold the load
2692 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2693 const TypeOopPtr* ptr = value_type->make_oopptr();
2694 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2695 // Load a non-flattened inline type from memory
2696 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2697 }
2698 // Normalize the value returned by getBoolean in the following cases
2699 if (type == T_BOOLEAN &&
2700 (mismatched ||
2701 heap_base_oop == top() || // - heap_base_oop is null or
2702 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2703 // and the unsafe access is made to large offset
2704 // (i.e., larger than the maximum offset necessary for any
2705 // field access)
2706 ) {
2707 IdealKit ideal = IdealKit(this);
2708 #define __ ideal.
2709 IdealVariable normalized_result(ideal);
2710 __ declarations_done();
2711 __ set(normalized_result, p);
2712 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2713 __ set(normalized_result, ideal.ConI(1));
2714 ideal.end_if();
2715 final_sync(ideal);
2716 p = __ value(normalized_result);
2717 #undef __
2721 p = gvn().transform(new CastP2XNode(nullptr, p));
2722 p = ConvX2UL(p);
2723 }
2724 // The load node has the control of the preceding MemBarCPUOrder. All
2725 // following nodes will have the control of the MemBarCPUOrder inserted at
2726 // the end of this method. So, pushing the load onto the stack at a later
2727 // point is fine.
2728 set_result(p);
2729 } else {
2730 if (bt == T_ADDRESS) {
2731 // Repackage the long as a pointer.
2732 val = ConvL2X(val);
2733 val = gvn().transform(new CastX2PNode(val));
2734 }
2735 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2736 }
2737
2738 return true;
2739 }
2740
2741 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2742 #ifdef ASSERT
2743 {
2744 ResourceMark rm;
2745 // Check the signatures.
2746 ciSignature* sig = callee()->signature();
2747 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2748 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2749 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2750 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2751 if (is_store) {
2752 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2753 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2754 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2755 } else {
2756 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2757 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2758 }
2759 }
2760 #endif // ASSERT
2761
2762 assert(kind == Relaxed, "Only plain accesses for now");
2763 if (callee()->is_static()) {
2764 // caller must have the capability!
2765 return false;
2766 }
2767 C->set_has_unsafe_access(true);
2768
2769 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2770 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2771 // parameter valueType is not a constant
2772 return false;
2773 }
2774 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2775 if (!mirror_type->is_inlinetype()) {
2776 // Dead code
2777 return false;
2778 }
2779 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2780
2781 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2782 if (layout_type == nullptr || !layout_type->is_con()) {
2783 // parameter layoutKind is not a constant
2784 return false;
2785 }
2786 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2787 layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2788 "invalid layoutKind %d", layout_type->get_con());
2789 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2790 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2791 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2792 "unexpected layoutKind %d", layout_type->get_con());
2793
2794 null_check(argument(0));
2795 if (stopped()) {
2796 return true;
2797 }
2798
2799 Node* base = must_be_not_null(argument(1), true);
2800 Node* offset = argument(2);
2801 const Type* base_type = _gvn.type(base);
2802
2803 Node* ptr;
2804 bool immutable_memory = false;
2805 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2806 if (base_type->isa_instptr()) {
2807 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2808 if (offset_type == nullptr || !offset_type->is_con()) {
2809 // Offset into a non-array should be a constant
2810 decorators |= C2_MISMATCHED;
2811 } else {
2812 int offset_con = checked_cast<int>(offset_type->get_con());
2813 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2814 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2815 if (field == nullptr) {
2816 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2817 decorators |= C2_MISMATCHED;
2818 } else {
2819 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2820 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2821 immutable_memory = field->is_strict() && field->is_final();
2822
2823 if (base->is_InlineType()) {
2824 assert(!is_store, "Cannot store into a non-larval value object");
2825 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2826 return true;
2827 }
2828 }
2829 }
2830
2831 if (base->is_InlineType()) {
2832 assert(!is_store, "Cannot store into a non-larval value object");
2833 base = base->as_InlineType()->buffer(this, true);
2834 }
2835 ptr = basic_plus_adr(base, ConvL2X(offset));
2836 } else if (base_type->isa_aryptr()) {
2837 decorators |= IS_ARRAY;
2838 if (layout == LayoutKind::REFERENCE) {
2839 if (!base_type->is_aryptr()->is_not_flat()) {
2840 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2841 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2842 replace_in_map(base, new_base);
2843 base = new_base;
2844 }
2845 ptr = basic_plus_adr(base, ConvL2X(offset));
2846 } else {
2847 if (UseArrayFlattening) {
2848 // Flat array must have an exact type
2849 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2850 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2851 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2852 replace_in_map(base, new_base);
2853 base = new_base;
2854 ptr = basic_plus_adr(base, ConvL2X(offset));
2855 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2856 if (ptr_type->field_offset().get() != 0) {
2857 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2858 }
2859 } else {
2860 uncommon_trap(Deoptimization::Reason_intrinsic,
2861 Deoptimization::Action_none);
2862 return true;
2863 }
2864 }
2865 } else {
2866 decorators |= C2_MISMATCHED;
2867 ptr = basic_plus_adr(base, ConvL2X(offset));
2868 }
2869
2870 if (is_store) {
2871 Node* value = argument(6);
2872 const Type* value_type = _gvn.type(value);
2873 if (!value_type->is_inlinetypeptr()) {
2874 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2875 Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2876 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2877 replace_in_map(value, new_value);
2878 value = new_value;
2879 }
2880
2881 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());
2882 if (layout == LayoutKind::REFERENCE) {
2883 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2884 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2885 } else {
2886 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2887 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2888 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2889 }
2890
2891 return true;
2892 } else {
2893 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2894 InlineTypeNode* result;
2895 if (layout == LayoutKind::REFERENCE) {
2896 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2897 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2898 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2899 } else {
2900 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2901 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2902 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2903 }
2904
2905 set_result(result);
2906 return true;
2907 }
2908 }
2909
2910 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2911 Node* receiver = argument(0);
2912 Node* value = argument(1);
2913
2914 const Type* type = gvn().type(value);
2915 if (!type->is_inlinetypeptr()) {
2916 C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2917 return false;
2918 }
2919
2920 null_check(receiver);
2921 if (stopped()) {
2922 return true;
2923 }
2924
2925 value = null_check(value);
2926 if (stopped()) {
2927 return true;
2928 }
2929
2930 ciInlineKlass* vk = type->inline_klass();
2931 Node* klass = makecon(TypeKlassPtr::make(vk));
2932 Node* obj = new_instance(klass);
2933 AllocateNode::Ideal_allocation(obj)->_larval = true;
2934
2935 assert(value->is_InlineType(), "must be an InlineTypeNode");
2936 Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2937 value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2938
2939 set_result(obj);
2940 return true;
2941 }
2942
2943 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2944 Node* receiver = argument(0);
2945 Node* buffer = argument(1);
2946
2947 const Type* type = gvn().type(buffer);
2948 if (!type->is_inlinetypeptr()) {
2949 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2950 return false;
2951 }
2952
2953 AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2954 if (alloc == nullptr) {
2955 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2956 return false;
2957 }
2958
2959 null_check(receiver);
2960 if (stopped()) {
2961 return true;
2962 }
2963
2964 // Unset the larval bit in the object header
2965 Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2966 Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2967 access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2968
2969 // We must ensure that the buffer is properly published
2970 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2971 assert(!type->maybe_null(), "result of an allocation should not be null");
2972 set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2973 return true;
2974 }
2975
2976 //----------------------------inline_unsafe_load_store----------------------------
2977 // This method serves a couple of different customers (depending on LoadStoreKind):
2978 //
2979 // LS_cmp_swap:
2980 //
2981 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2982 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2983 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2984 //
2985 // LS_cmp_swap_weak:
2986 //
2987 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2988 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2989 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2990 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2991 //
2992 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2993 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2994 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2995 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3158 }
3159 case LS_cmp_swap:
3160 case LS_cmp_swap_weak:
3161 case LS_get_add:
3162 break;
3163 default:
3164 ShouldNotReachHere();
3165 }
3166
3167 // Null check receiver.
3168 receiver = null_check(receiver);
3169 if (stopped()) {
3170 return true;
3171 }
3172
3173 int alias_idx = C->get_alias_index(adr_type);
3174
3175 if (is_reference_type(type)) {
3176 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3177
3178 if (oldval != nullptr && oldval->is_InlineType()) {
3179 // Re-execute the unsafe access if allocation triggers deoptimization.
3180 PreserveReexecuteState preexecs(this);
3181 jvms()->set_should_reexecute(true);
3182 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3183 }
3184 if (newval != nullptr && newval->is_InlineType()) {
3185 // Re-execute the unsafe access if allocation triggers deoptimization.
3186 PreserveReexecuteState preexecs(this);
3187 jvms()->set_should_reexecute(true);
3188 newval = newval->as_InlineType()->buffer(this)->get_oop();
3189 }
3190
3191 // Transformation of a value which could be null pointer (CastPP #null)
3192 // could be delayed during Parse (for example, in adjust_map_after_if()).
3193 // Execute transformation here to avoid barrier generation in such case.
3194 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3195 newval = _gvn.makecon(TypePtr::NULL_PTR);
3196
3197 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3198 // Refine the value to a null constant, when it is known to be null
3199 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3200 }
3201 }
3202
3203 Node* result = nullptr;
3204 switch (kind) {
3205 case LS_cmp_exchange: {
3206 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3207 oldval, newval, value_type, type, decorators);
3208 break;
3209 }
3210 case LS_cmp_swap_weak:
3239 insert_mem_bar(Op_MemBarCPUOrder);
3240 switch(id) {
3241 case vmIntrinsics::_loadFence:
3242 insert_mem_bar(Op_LoadFence);
3243 return true;
3244 case vmIntrinsics::_storeFence:
3245 insert_mem_bar(Op_StoreFence);
3246 return true;
3247 case vmIntrinsics::_storeStoreFence:
3248 insert_mem_bar(Op_StoreStoreFence);
3249 return true;
3250 case vmIntrinsics::_fullFence:
3251 insert_mem_bar(Op_MemBarVolatile);
3252 return true;
3253 default:
3254 fatal_unexpected_iid(id);
3255 return false;
3256 }
3257 }
3258
3259 // private native int arrayInstanceBaseOffset0(Object[] array);
3260 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3261 Node* array = argument(1);
3262 Node* klass_node = load_object_klass(array);
3263
3264 jint layout_con = Klass::_lh_neutral_value;
3265 Node* layout_val = get_layout_helper(klass_node, layout_con);
3266 int layout_is_con = (layout_val == nullptr);
3267
3268 Node* header_size = nullptr;
3269 if (layout_is_con) {
3270 int hsize = Klass::layout_helper_header_size(layout_con);
3271 header_size = intcon(hsize);
3272 } else {
3273 Node* hss = intcon(Klass::_lh_header_size_shift);
3274 Node* hsm = intcon(Klass::_lh_header_size_mask);
3275 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3276 header_size = _gvn.transform(new AndINode(header_size, hsm));
3277 }
3278 set_result(header_size);
3279 return true;
3280 }
3281
3282 // private native int arrayInstanceIndexScale0(Object[] array);
3283 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3284 Node* array = argument(1);
3285 Node* klass_node = load_object_klass(array);
3286
3287 jint layout_con = Klass::_lh_neutral_value;
3288 Node* layout_val = get_layout_helper(klass_node, layout_con);
3289 int layout_is_con = (layout_val == nullptr);
3290
3291 Node* element_size = nullptr;
3292 if (layout_is_con) {
3293 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3294 int elem_size = 1 << log_element_size;
3295 element_size = intcon(elem_size);
3296 } else {
3297 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3298 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3299 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3300 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3301 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3302 }
3303 set_result(element_size);
3304 return true;
3305 }
3306
3307 // private native int arrayLayout0(Object[] array);
3308 bool LibraryCallKit::inline_arrayLayout() {
3309 RegionNode* region = new RegionNode(2);
3310 Node* phi = new PhiNode(region, TypeInt::POS);
3311
3312 Node* array = argument(1);
3313 Node* klass_node = load_object_klass(array);
3314 generate_refArray_guard(klass_node, region);
3315 if (region->req() == 3) {
3316 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3317 }
3318
3319 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3320 Node* layout_kind_addr = basic_plus_adr(klass_node, layout_kind_offset);
3321 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3322
3323 region->init_req(1, control());
3324 phi->init_req(1, layout_kind);
3325
3326 set_control(_gvn.transform(region));
3327 set_result(_gvn.transform(phi));
3328 return true;
3329 }
3330
3331 // private native int[] getFieldMap0(Class <?> c);
3332 // int offset = c._klass._acmp_maps_offset;
3333 // return (int[])c.obj_field(offset);
3334 bool LibraryCallKit::inline_getFieldMap() {
3335 if (!UseAltSubstitutabilityMethod) {
3336 return false;
3337 }
3338
3339 Node* mirror = argument(1);
3340 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3341
3342 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3343 Node* field_map_offset_addr = basic_plus_adr(klass, field_map_offset_offset);
3344 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3345 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3346
3347 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3348 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3349 // TODO 8350865 Remove this
3350 val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3351 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3352
3353 set_result(map);
3354 return true;
3355 }
3356
3357 bool LibraryCallKit::inline_onspinwait() {
3358 insert_mem_bar(Op_OnSpinWait);
3359 return true;
3360 }
3361
3362 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3363 if (!kls->is_Con()) {
3364 return true;
3365 }
3366 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3367 if (klsptr == nullptr) {
3368 return true;
3369 }
3370 ciInstanceKlass* ik = klsptr->instance_klass();
3371 // don't need a guard for a klass that is already initialized
3372 return !ik->is_initialized();
3373 }
3374
3375 //----------------------------inline_unsafe_writeback0-------------------------
3376 // public native void Unsafe.writeback0(long address)
3455 Deoptimization::Action_make_not_entrant);
3456 }
3457 if (stopped()) {
3458 return true;
3459 }
3460 #endif //INCLUDE_JVMTI
3461
3462 Node* test = nullptr;
3463 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3464 // Note: The argument might still be an illegal value like
3465 // Serializable.class or Object[].class. The runtime will handle it.
3466 // But we must make an explicit check for initialization.
3467 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3468 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3469 // can generate code to load it as unsigned byte.
3470 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3471 Node* bits = intcon(InstanceKlass::fully_initialized);
3472 test = _gvn.transform(new SubINode(inst, bits));
3473 // The 'test' is non-zero if we need to take a slow path.
3474 }
3475 Node* obj = nullptr;
3476 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3477 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3478 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3479 } else {
3480 obj = new_instance(kls, test);
3481 }
3482 set_result(obj);
3483 return true;
3484 }
3485
3486 //------------------------inline_native_time_funcs--------------
3487 // inline code for System.currentTimeMillis() and System.nanoTime()
3488 // these have the same type and signature
3489 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3490 const TypeFunc* tf = OptoRuntime::void_long_Type();
3491 const TypePtr* no_memory_effects = nullptr;
3492 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3493 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3494 #ifdef ASSERT
3495 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3496 assert(value_top == top(), "second value must be top");
3497 #endif
3498 set_result(value);
3499 return true;
3500 }
3501
4276 Node* thread = _gvn.transform(new ThreadLocalNode());
4277 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4278 Node* thread_obj_handle
4279 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4280 thread_obj_handle = _gvn.transform(thread_obj_handle);
4281 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4282 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4283
4284 // Change the _monitor_owner_id of the JavaThread
4285 Node* tid = load_field_from_object(arr, "tid", "J");
4286 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4287 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4288
4289 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4290 return true;
4291 }
4292
4293 const Type* LibraryCallKit::scopedValueCache_type() {
4294 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4295 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4296 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4297
4298 // Because we create the scopedValue cache lazily we have to make the
4299 // type of the result BotPTR.
4300 bool xk = etype->klass_is_exact();
4301 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4302 return objects_type;
4303 }
4304
4305 Node* LibraryCallKit::scopedValueCache_helper() {
4306 Node* thread = _gvn.transform(new ThreadLocalNode());
4307 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4308 // We cannot use immutable_memory() because we might flip onto a
4309 // different carrier thread, at which point we'll need to use that
4310 // carrier thread's cache.
4311 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4312 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4313 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4314 }
4315
4316 //------------------------inline_native_scopedValueCache------------------
4317 bool LibraryCallKit::inline_native_scopedValueCache() {
4318 Node* cache_obj_handle = scopedValueCache_helper();
4319 const Type* objects_type = scopedValueCache_type();
4320 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4321
4457 }
4458 return kls;
4459 }
4460
4461 //--------------------(inline_native_Class_query helpers)---------------------
4462 // Use this for JVM_ACC_INTERFACE.
4463 // Fall through if (mods & mask) == bits, take the guard otherwise.
4464 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4465 ByteSize offset, const Type* type, BasicType bt) {
4466 // Branch around if the given klass has the given modifier bit set.
4467 // Like generate_guard, adds a new path onto the region.
4468 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4469 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4470 Node* mask = intcon(modifier_mask);
4471 Node* bits = intcon(modifier_bits);
4472 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4473 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4474 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4475 return generate_fair_guard(bol, region);
4476 }
4477
4478 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4479 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4480 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4481 }
4482
4483 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4484 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4485 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4486 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4487 }
4488
4489 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4490 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4491 }
4492
4493 //-------------------------inline_native_Class_query-------------------
4494 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4495 const Type* return_type = TypeInt::BOOL;
4496 Node* prim_return_value = top(); // what happens if it's a primitive class?
4497 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4583
4584
4585 case vmIntrinsics::_getSuperclass:
4586 // The rules here are somewhat unfortunate, but we can still do better
4587 // with random logic than with a JNI call.
4588 // Interfaces store null or Object as _super, but must report null.
4589 // Arrays store an intermediate super as _super, but must report Object.
4590 // Other types can report the actual _super.
4591 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4592 if (generate_array_guard(kls, region) != nullptr) {
4593 // A guard was added. If the guard is taken, it was an array.
4594 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4595 }
4596 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4597 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4598 if (generate_interface_guard(kls, region) != nullptr) {
4599 // A guard was added. If the guard is taken, it was an interface.
4600 phi->add_req(null());
4601 }
4602 // If we fall through, it's a plain class. Get its _super.
4603 if (!stopped()) {
4604 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4605 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4606 null_ctl = top();
4607 kls = null_check_oop(kls, &null_ctl);
4608 if (null_ctl != top()) {
4609 // If the guard is taken, Object.superClass is null (both klass and mirror).
4610 region->add_req(null_ctl);
4611 phi ->add_req(null());
4612 }
4613 if (!stopped()) {
4614 query_value = load_mirror_from_klass(kls);
4615 }
4616 }
4617 break;
4618
4619 default:
4620 fatal_unexpected_iid(id);
4621 break;
4622 }
4623
4624 // Fall-through is the normal case of a query to a real class.
4625 phi->init_req(1, query_value);
4626 region->init_req(1, control());
4627
4628 C->set_has_split_ifs(true); // Has chance for split-if optimization
4629 set_result(region, phi);
4630 return true;
4631 }
4632
4633
4634 //-------------------------inline_Class_cast-------------------
4635 bool LibraryCallKit::inline_Class_cast() {
4636 Node* mirror = argument(0); // Class
4637 Node* obj = argument(1);
4638 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4639 if (mirror_con == nullptr) {
4640 return false; // dead path (mirror->is_top()).
4641 }
4642 if (obj == nullptr || obj->is_top()) {
4643 return false; // dead path
4644 }
4645 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4646
4647 // First, see if Class.cast() can be folded statically.
4648 // java_mirror_type() returns non-null for compile-time Class constants.
4649 ciType* tm = mirror_con->java_mirror_type();
4650 if (tm != nullptr && tm->is_klass() &&
4651 tp != nullptr) {
4652 if (!tp->is_loaded()) {
4653 // Don't use intrinsic when class is not loaded.
4654 return false;
4655 } else {
4656 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4657 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4658 if (static_res == Compile::SSC_always_true) {
4659 // isInstance() is true - fold the code.
4660 set_result(obj);
4661 return true;
4662 } else if (static_res == Compile::SSC_always_false) {
4663 // Don't use intrinsic, have to throw ClassCastException.
4664 // If the reference is null, the non-intrinsic bytecode will
4665 // be optimized appropriately.
4666 return false;
4667 }
4668 }
4669 }
4670
4671 // Bailout intrinsic and do normal inlining if exception path is frequent.
4672 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4673 return false;
4674 }
4675
4676 // Generate dynamic checks.
4677 // Class.cast() is java implementation of _checkcast bytecode.
4678 // Do checkcast (Parse::do_checkcast()) optimizations here.
4679
4680 mirror = null_check(mirror);
4681 // If mirror is dead, only null-path is taken.
4682 if (stopped()) {
4683 return true;
4684 }
4685
4686 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4687 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4688 RegionNode* region = new RegionNode(PATH_LIMIT);
4689 record_for_igvn(region);
4690
4691 // Now load the mirror's klass metaobject, and null-check it.
4692 // If kls is null, we have a primitive mirror and
4693 // nothing is an instance of a primitive type.
4694 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4695
4696 Node* res = top();
4697 Node* io = i_o();
4698 Node* mem = merged_memory();
4699 if (!stopped()) {
4700
4701 Node* bad_type_ctrl = top();
4702 // Do checkcast optimizations.
4703 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4704 region->init_req(_bad_type_path, bad_type_ctrl);
4705 }
4706 if (region->in(_prim_path) != top() ||
4707 region->in(_bad_type_path) != top() ||
4708 region->in(_npe_path) != top()) {
4709 // Let Interpreter throw ClassCastException.
4710 PreserveJVMState pjvms(this);
4711 set_control(_gvn.transform(region));
4712 // Set IO and memory because gen_checkcast may override them when buffering inline types
4713 set_i_o(io);
4714 set_all_memory(mem);
4715 uncommon_trap(Deoptimization::Reason_intrinsic,
4716 Deoptimization::Action_maybe_recompile);
4717 }
4718 if (!stopped()) {
4719 set_result(res);
4720 }
4721 return true;
4722 }
4723
4724
4725 //--------------------------inline_native_subtype_check------------------------
4726 // This intrinsic takes the JNI calls out of the heart of
4727 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4728 bool LibraryCallKit::inline_native_subtype_check() {
4729 // Pull both arguments off the stack.
4730 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4731 args[0] = argument(0);
4732 args[1] = argument(1);
4733 Node* klasses[2]; // corresponding Klasses: superk, subk
4734 klasses[0] = klasses[1] = top();
4735
4736 enum {
4737 // A full decision tree on {superc is prim, subc is prim}:
4738 _prim_0_path = 1, // {P,N} => false
4739 // {P,P} & superc!=subc => false
4740 _prim_same_path, // {P,P} & superc==subc => true
4741 _prim_1_path, // {N,P} => false
4742 _ref_subtype_path, // {N,N} & subtype check wins => true
4743 _both_ref_path, // {N,N} & subtype check loses => false
4744 PATH_LIMIT
4745 };
4746
4747 RegionNode* region = new RegionNode(PATH_LIMIT);
4748 RegionNode* prim_region = new RegionNode(2);
4749 Node* phi = new PhiNode(region, TypeInt::BOOL);
4750 record_for_igvn(region);
4751 record_for_igvn(prim_region);
4752
4753 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4754 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4755 int class_klass_offset = java_lang_Class::klass_offset();
4756
4757 // First null-check both mirrors and load each mirror's klass metaobject.
4758 int which_arg;
4759 for (which_arg = 0; which_arg <= 1; which_arg++) {
4760 Node* arg = args[which_arg];
4761 arg = null_check(arg);
4762 if (stopped()) break;
4763 args[which_arg] = arg;
4764
4765 Node* p = basic_plus_adr(arg, class_klass_offset);
4766 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4767 klasses[which_arg] = _gvn.transform(kls);
4768 }
4769
4770 // Having loaded both klasses, test each for null.
4771 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4772 for (which_arg = 0; which_arg <= 1; which_arg++) {
4773 Node* kls = klasses[which_arg];
4774 Node* null_ctl = top();
4775 kls = null_check_oop(kls, &null_ctl, never_see_null);
4776 if (which_arg == 0) {
4777 prim_region->init_req(1, null_ctl);
4778 } else {
4779 region->init_req(_prim_1_path, null_ctl);
4780 }
4781 if (stopped()) break;
4782 klasses[which_arg] = kls;
4783 }
4784
4785 if (!stopped()) {
4786 // now we have two reference types, in klasses[0..1]
4787 Node* subk = klasses[1]; // the argument to isAssignableFrom
4788 Node* superk = klasses[0]; // the receiver
4789 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4790 region->set_req(_ref_subtype_path, control());
4791 }
4792
4793 // If both operands are primitive (both klasses null), then
4794 // we must return true when they are identical primitives.
4795 // It is convenient to test this after the first null klass check.
4796 // This path is also used if superc is a value mirror.
4797 set_control(_gvn.transform(prim_region));
4798 if (!stopped()) {
4799 // Since superc is primitive, make a guard for the superc==subc case.
4800 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4801 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4802 generate_fair_guard(bol_eq, region);
4803 if (region->req() == PATH_LIMIT+1) {
4804 // A guard was added. If the added guard is taken, superc==subc.
4805 region->swap_edges(PATH_LIMIT, _prim_same_path);
4806 region->del_req(PATH_LIMIT);
4807 }
4808 region->set_req(_prim_0_path, control()); // Not equal after all.
4809 }
4810
4811 // these are the only paths that produce 'true':
4812 phi->set_req(_prim_same_path, intcon(1));
4813 phi->set_req(_ref_subtype_path, intcon(1));
4814
4815 // pull together the cases:
4816 assert(region->req() == PATH_LIMIT, "sane region");
4817 for (uint i = 1; i < region->req(); i++) {
4818 Node* ctl = region->in(i);
4819 if (ctl == nullptr || ctl == top()) {
4820 region->set_req(i, top());
4821 phi ->set_req(i, top());
4822 } else if (phi->in(i) == nullptr) {
4823 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4824 }
4825 }
4826
4827 set_control(_gvn.transform(region));
4828 set_result(_gvn.transform(phi));
4829 return true;
4830 }
4831
4832 //---------------------generate_array_guard_common------------------------
4833 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4834
4835 if (stopped()) {
4836 return nullptr;
4837 }
4838
4839 // Like generate_guard, adds a new path onto the region.
4840 jint layout_con = 0;
4841 Node* layout_val = get_layout_helper(kls, layout_con);
4842 if (layout_val == nullptr) {
4843 bool query = 0;
4844 switch(kind) {
4845 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4846 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4847 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4848 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4849 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4850 default:
4851 ShouldNotReachHere();
4852 }
4853 if (!query) {
4854 return nullptr; // never a branch
4855 } else { // always a branch
4856 Node* always_branch = control();
4857 if (region != nullptr)
4858 region->add_req(always_branch);
4859 set_control(top());
4860 return always_branch;
4861 }
4862 }
4863 unsigned int value = 0;
4864 BoolTest::mask btest = BoolTest::illegal;
4865 switch(kind) {
4866 case RefArray:
4867 case NonRefArray: {
4868 value = Klass::_lh_array_tag_ref_value;
4869 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4870 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4871 break;
4872 }
4873 case TypeArray: {
4874 value = Klass::_lh_array_tag_type_value;
4875 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4876 btest = BoolTest::eq;
4877 break;
4878 }
4879 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4880 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4881 default:
4882 ShouldNotReachHere();
4883 }
4884 // Now test the correct condition.
4885 jint nval = (jint)value;
4886 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4887 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4888 Node* ctrl = generate_fair_guard(bol, region);
4889 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4890 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4891 // Keep track of the fact that 'obj' is an array to prevent
4892 // array specific accesses from floating above the guard.
4893 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4894 }
4895 return ctrl;
4896 }
4897
4898 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4899 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4900 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4901 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4902 assert(null_free || atomic, "nullable implies atomic");
4903 Node* componentType = argument(0);
4904 Node* length = argument(1);
4905 Node* init_val = null_free ? argument(2) : nullptr;
4906
4907 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4908 if (tp != nullptr) {
4909 ciInstanceKlass* ik = tp->instance_klass();
4910 if (ik == C->env()->Class_klass()) {
4911 ciType* t = tp->java_mirror_type();
4912 if (t != nullptr && t->is_inlinetype()) {
4913
4914 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4915 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4916
4917 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4918 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4919 return false;
4920 }
4921
4922 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4923 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4924 if (null_free) {
4925 if (init_val->is_InlineType()) {
4926 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4927 // Zeroing is enough because the init value is the all-zero value
4928 init_val = nullptr;
4929 } else {
4930 init_val = init_val->as_InlineType()->buffer(this);
4931 }
4932 }
4933 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4934 }
4935 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4936 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4937 assert(arytype->is_null_free() == null_free, "inconsistency");
4938 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4939 set_result(obj);
4940 return true;
4941 }
4942 }
4943 }
4944 }
4945 return false;
4946 }
4947
4948 // public static native boolean ValueClass::isFlatArray(Object array);
4949 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4950 // public static native boolean ValueClass::isAtomicArray(Object array);
4951 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4952 Node* array = argument(0);
4953
4954 Node* bol;
4955 switch(check) {
4956 case IsFlat:
4957 // TODO 8350865 Use the object version here instead of loading the klass
4958 // 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
4959 bol = flat_array_test(load_object_klass(array));
4960 break;
4961 case IsNullRestricted:
4962 bol = null_free_array_test(array);
4963 break;
4964 case IsAtomic:
4965 // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4966 // Enable TestIntrinsics::test87/88 once this is implemented
4967 // bol = null_free_atomic_array_test
4968 return false;
4969 default:
4970 ShouldNotReachHere();
4971 }
4972
4973 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4974 set_result(res);
4975 return true;
4976 }
4977
4978 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4979 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4980 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4981 RegionNode* region = new RegionNode(2);
4982 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4983
4984 if (type_array_guard) {
4985 generate_typeArray_guard(klass_node, region);
4986 if (region->req() == 3) {
4987 phi->add_req(klass_node);
4988 }
4989 }
4990 Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4991 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4992
4993 // Can be null if not initialized yet, just deopt
4994 Node* null_ctl = top();
4995 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4996
4997 region->init_req(1, control());
4998 phi->init_req(1, refined_klass);
4999
5000 set_control(_gvn.transform(region));
5001 return _gvn.transform(phi);
5002 }
5003
5004 // Load the non-refined array klass from an ObjArrayKlass.
5005 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5006 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5007 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5008 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5009 }
5010
5011 RegionNode* region = new RegionNode(2);
5012 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5013
5014 generate_typeArray_guard(klass_node, region);
5015 if (region->req() == 3) {
5016 phi->add_req(klass_node);
5017 }
5018 Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
5019 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5020
5021 region->init_req(1, control());
5022 phi->init_req(1, super_klass);
5023
5024 set_control(_gvn.transform(region));
5025 return _gvn.transform(phi);
5026 }
5027
5028 //-----------------------inline_native_newArray--------------------------
5029 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5030 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5031 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5032 Node* mirror;
5033 Node* count_val;
5034 if (uninitialized) {
5035 null_check_receiver();
5036 mirror = argument(1);
5037 count_val = argument(2);
5038 } else {
5039 mirror = argument(0);
5040 count_val = argument(1);
5041 }
5042
5043 mirror = null_check(mirror);
5044 // If mirror or obj is dead, only null-path is taken.
5045 if (stopped()) return true;
5046
5047 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5048 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5049 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5067 CallJavaNode* slow_call = nullptr;
5068 if (uninitialized) {
5069 // Generate optimized virtual call (holder class 'Unsafe' is final)
5070 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5071 } else {
5072 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5073 }
5074 Node* slow_result = set_results_for_java_call(slow_call);
5075 // this->control() comes from set_results_for_java_call
5076 result_reg->set_req(_slow_path, control());
5077 result_val->set_req(_slow_path, slow_result);
5078 result_io ->set_req(_slow_path, i_o());
5079 result_mem->set_req(_slow_path, reset_memory());
5080 }
5081
5082 set_control(normal_ctl);
5083 if (!stopped()) {
5084 // Normal case: The array type has been cached in the java.lang.Class.
5085 // The following call works fine even if the array type is polymorphic.
5086 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5087
5088 klass_node = load_default_refined_array_klass(klass_node);
5089
5090 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
5091 result_reg->init_req(_normal_path, control());
5092 result_val->init_req(_normal_path, obj);
5093 result_io ->init_req(_normal_path, i_o());
5094 result_mem->init_req(_normal_path, reset_memory());
5095
5096 if (uninitialized) {
5097 // Mark the allocation so that zeroing is skipped
5098 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5099 alloc->maybe_set_complete(&_gvn);
5100 }
5101 }
5102
5103 // Return the combined state.
5104 set_i_o( _gvn.transform(result_io) );
5105 set_all_memory( _gvn.transform(result_mem));
5106
5107 C->set_has_split_ifs(true); // Has chance for split-if optimization
5108 set_result(result_reg, result_val);
5109 return true;
5158 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5159 { PreserveReexecuteState preexecs(this);
5160 jvms()->set_should_reexecute(true);
5161
5162 array_type_mirror = null_check(array_type_mirror);
5163 original = null_check(original);
5164
5165 // Check if a null path was taken unconditionally.
5166 if (stopped()) return true;
5167
5168 Node* orig_length = load_array_length(original);
5169
5170 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5171 klass_node = null_check(klass_node);
5172
5173 RegionNode* bailout = new RegionNode(1);
5174 record_for_igvn(bailout);
5175
5176 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5177 // Bail out if that is so.
5178 // Inline type array may have object field that would require a
5179 // write barrier. Conservatively, go to slow path.
5180 // TODO 8251971: Optimize for the case when flat src/dst are later found
5181 // to not contain oops (i.e., move this check to the macro expansion phase).
5182 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5183 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5184 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5185 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5186 // Can src array be flat and contain oops?
5187 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5188 // Can dest array be flat and contain oops?
5189 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5190 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5191
5192 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5193
5194 if (not_objArray != nullptr) {
5195 // Improve the klass node's type from the new optimistic assumption:
5196 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5197 bool not_flat = !UseArrayFlattening;
5198 bool not_null_free = !Arguments::is_valhalla_enabled();
5199 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5200 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5201 refined_klass_node = _gvn.transform(cast);
5202 }
5203
5204 // Bail out if either start or end is negative.
5205 generate_negative_guard(start, bailout, &start);
5206 generate_negative_guard(end, bailout, &end);
5207
5208 Node* length = end;
5209 if (_gvn.type(start) != TypeInt::ZERO) {
5210 length = _gvn.transform(new SubINode(end, start));
5211 }
5212
5213 // Bail out if length is negative (i.e., if start > end).
5214 // Without this the new_array would throw
5215 // NegativeArraySizeException but IllegalArgumentException is what
5216 // should be thrown
5217 generate_negative_guard(length, bailout, &length);
5218
5219 // Handle inline type arrays
5220 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5221 if (!stopped()) {
5222 // TODO 8251971
5223 if (!orig_t->is_null_free()) {
5224 // Not statically known to be null free, add a check
5225 generate_fair_guard(null_free_array_test(original), bailout);
5226 }
5227 orig_t = _gvn.type(original)->isa_aryptr();
5228 if (orig_t != nullptr && orig_t->is_flat()) {
5229 // Src is flat, check that dest is flat as well
5230 if (exclude_flat) {
5231 // Dest can't be flat, bail out
5232 bailout->add_req(control());
5233 set_control(top());
5234 } else {
5235 generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5236 }
5237 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5238 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5239 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5240 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5241 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5242 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5243 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5244 if (orig_t != nullptr) {
5245 orig_t = orig_t->cast_to_not_flat();
5246 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5247 }
5248 }
5249 if (!can_validate) {
5250 // No validation. The subtype check emitted at macro expansion time will not go to the slow
5251 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5252 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5253 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5254 generate_fair_guard(null_free_array_test(original), bailout);
5255 }
5256 }
5257
5258 // Bail out if start is larger than the original length
5259 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5260 generate_negative_guard(orig_tail, bailout, &orig_tail);
5261
5262 if (bailout->req() > 1) {
5263 PreserveJVMState pjvms(this);
5264 set_control(_gvn.transform(bailout));
5265 uncommon_trap(Deoptimization::Reason_intrinsic,
5266 Deoptimization::Action_maybe_recompile);
5267 }
5268
5269 if (!stopped()) {
5270 // How many elements will we copy from the original?
5271 // The answer is MinI(orig_tail, length).
5272 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5273
5274 // Generate a direct call to the right arraycopy function(s).
5275 // We know the copy is disjoint but we might not know if the
5276 // oop stores need checking.
5277 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5283 // to the copyOf to be validated, including that the copy to the
5284 // new array won't trigger an ArrayStoreException. That subtype
5285 // check can be optimized if we know something on the type of
5286 // the input array from type speculation.
5287 if (_gvn.type(klass_node)->singleton()) {
5288 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5289 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5290
5291 int test = C->static_subtype_check(superk, subk);
5292 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5293 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5294 if (t_original->speculative_type() != nullptr) {
5295 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5296 }
5297 }
5298 }
5299
5300 bool validated = false;
5301 // Reason_class_check rather than Reason_intrinsic because we
5302 // want to intrinsify even if this traps.
5303 if (can_validate) {
5304 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5305
5306 if (not_subtype_ctrl != top()) {
5307 PreserveJVMState pjvms(this);
5308 set_control(not_subtype_ctrl);
5309 uncommon_trap(Deoptimization::Reason_class_check,
5310 Deoptimization::Action_make_not_entrant);
5311 assert(stopped(), "Should be stopped");
5312 }
5313 validated = true;
5314 }
5315
5316 if (!stopped()) {
5317 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5318
5319 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5320 load_object_klass(original), klass_node);
5321 if (!is_copyOfRange) {
5322 ac->set_copyof(validated);
5323 } else {
5324 ac->set_copyofrange(validated);
5325 }
5326 Node* n = _gvn.transform(ac);
5327 if (n == ac) {
5328 ac->connect_outputs(this);
5329 } else {
5330 assert(validated, "shouldn't transform if all arguments not validated");
5331 set_all_memory(n);
5332 }
5333 }
5334 }
5335 } // original reexecute is set back here
5336
5337 C->set_has_split_ifs(true); // Has chance for split-if optimization
5369
5370 //-----------------------generate_method_call----------------------------
5371 // Use generate_method_call to make a slow-call to the real
5372 // method if the fast path fails. An alternative would be to
5373 // use a stub like OptoRuntime::slow_arraycopy_Java.
5374 // This only works for expanding the current library call,
5375 // not another intrinsic. (E.g., don't use this for making an
5376 // arraycopy call inside of the copyOf intrinsic.)
5377 CallJavaNode*
5378 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5379 // When compiling the intrinsic method itself, do not use this technique.
5380 guarantee(callee() != C->method(), "cannot make slow-call to self");
5381
5382 ciMethod* method = callee();
5383 // ensure the JVMS we have will be correct for this call
5384 guarantee(method_id == method->intrinsic_id(), "must match");
5385
5386 const TypeFunc* tf = TypeFunc::make(method);
5387 if (res_not_null) {
5388 assert(tf->return_type() == T_OBJECT, "");
5389 const TypeTuple* range = tf->range_cc();
5390 const Type** fields = TypeTuple::fields(range->cnt());
5391 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5392 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5393 tf = TypeFunc::make(tf->domain_cc(), new_range);
5394 }
5395 CallJavaNode* slow_call;
5396 if (is_static) {
5397 assert(!is_virtual, "");
5398 slow_call = new CallStaticJavaNode(C, tf,
5399 SharedRuntime::get_resolve_static_call_stub(), method);
5400 } else if (is_virtual) {
5401 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5402 int vtable_index = Method::invalid_vtable_index;
5403 if (UseInlineCaches) {
5404 // Suppress the vtable call
5405 } else {
5406 // hashCode and clone are not a miranda methods,
5407 // so the vtable index is fixed.
5408 // No need to use the linkResolver to get it.
5409 vtable_index = method->vtable_index();
5410 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5411 "bad index %d", vtable_index);
5412 }
5413 slow_call = new CallDynamicJavaNode(tf,
5430 set_edges_for_java_call(slow_call);
5431 return slow_call;
5432 }
5433
5434
5435 /**
5436 * Build special case code for calls to hashCode on an object. This call may
5437 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5438 * slightly different code.
5439 */
5440 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5441 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5442 assert(!(is_virtual && is_static), "either virtual, special, or static");
5443
5444 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5445
5446 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5447 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5448 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5449 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5450 Node* obj = argument(0);
5451
5452 // Don't intrinsify hashcode on inline types for now.
5453 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5454 if (gvn().type(obj)->is_inlinetypeptr()) {
5455 return false;
5456 }
5457
5458 if (!is_static) {
5459 // Check for hashing null object
5460 obj = null_check_receiver();
5461 if (stopped()) return true; // unconditionally null
5462 result_reg->init_req(_null_path, top());
5463 result_val->init_req(_null_path, top());
5464 } else {
5465 // Do a null check, and return zero if null.
5466 // System.identityHashCode(null) == 0
5467 Node* null_ctl = top();
5468 obj = null_check_oop(obj, &null_ctl);
5469 result_reg->init_req(_null_path, null_ctl);
5470 result_val->init_req(_null_path, _gvn.intcon(0));
5471 }
5472
5473 // Unconditionally null? Then return right away.
5474 if (stopped()) {
5475 set_control( result_reg->in(_null_path));
5476 if (!stopped())
5477 set_result(result_val->in(_null_path));
5478 return true;
5479 }
5480
5481 // We only go to the fast case code if we pass a number of guards. The
5482 // paths which do not pass are accumulated in the slow_region.
5483 RegionNode* slow_region = new RegionNode(1);
5484 record_for_igvn(slow_region);
5485
5486 // If this is a virtual call, we generate a funny guard. We pull out
5487 // the vtable entry corresponding to hashCode() from the target object.
5488 // If the target method which we are calling happens to be the native
5489 // Object hashCode() method, we pass the guard. We do not need this
5490 // guard for non-virtual calls -- the caller is known to be the native
5491 // Object hashCode().
5492 if (is_virtual) {
5493 // After null check, get the object's klass.
5494 Node* obj_klass = load_object_klass(obj);
5495 generate_virtual_guard(obj_klass, slow_region);
5496 }
5497
5498 // Get the header out of the object, use LoadMarkNode when available
5499 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5500 // The control of the load must be null. Otherwise, the load can move before
5501 // the null check after castPP removal.
5502 Node* no_ctrl = nullptr;
5503 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5504
5505 if (!UseObjectMonitorTable) {
5506 // Test the header to see if it is safe to read w.r.t. locking.
5507 // We cannot use the inline type mask as this may check bits that are overriden
5508 // by an object monitor's pointer when inflating locking.
5509 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5510 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5511 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5512 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5513 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5514
5515 generate_slow_guard(test_monitor, slow_region);
5516 }
5517
5518 // Get the hash value and check to see that it has been properly assigned.
5519 // We depend on hash_mask being at most 32 bits and avoid the use of
5520 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5521 // vm: see markWord.hpp.
5522 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5523 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5524 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5525 // This hack lets the hash bits live anywhere in the mark object now, as long
5526 // as the shift drops the relevant bits into the low 32 bits. Note that
5527 // Java spec says that HashCode is an int so there's no point in capturing
5528 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5556 // this->control() comes from set_results_for_java_call
5557 result_reg->init_req(_slow_path, control());
5558 result_val->init_req(_slow_path, slow_result);
5559 result_io ->set_req(_slow_path, i_o());
5560 result_mem ->set_req(_slow_path, reset_memory());
5561 }
5562
5563 // Return the combined state.
5564 set_i_o( _gvn.transform(result_io) );
5565 set_all_memory( _gvn.transform(result_mem));
5566
5567 set_result(result_reg, result_val);
5568 return true;
5569 }
5570
5571 //---------------------------inline_native_getClass----------------------------
5572 // public final native Class<?> java.lang.Object.getClass();
5573 //
5574 // Build special case code for calls to getClass on an object.
5575 bool LibraryCallKit::inline_native_getClass() {
5576 Node* obj = argument(0);
5577 if (obj->is_InlineType()) {
5578 const Type* t = _gvn.type(obj);
5579 if (t->maybe_null()) {
5580 null_check(obj);
5581 }
5582 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5583 return true;
5584 }
5585 obj = null_check_receiver();
5586 if (stopped()) return true;
5587 set_result(load_mirror_from_klass(load_object_klass(obj)));
5588 return true;
5589 }
5590
5591 //-----------------inline_native_Reflection_getCallerClass---------------------
5592 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5593 //
5594 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5595 //
5596 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5597 // in that it must skip particular security frames and checks for
5598 // caller sensitive methods.
5599 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5600 #ifndef PRODUCT
5601 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5602 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5603 }
5604 #endif
5605
5987 // not cloneable or finalizer => slow path to out-of-line Object.clone
5988 //
5989 // The general case has two steps, allocation and copying.
5990 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5991 //
5992 // Copying also has two cases, oop arrays and everything else.
5993 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5994 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5995 //
5996 // These steps fold up nicely if and when the cloned object's klass
5997 // can be sharply typed as an object array, a type array, or an instance.
5998 //
5999 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
6000 PhiNode* result_val;
6001
6002 // Set the reexecute bit for the interpreter to reexecute
6003 // the bytecode that invokes Object.clone if deoptimization happens.
6004 { PreserveReexecuteState preexecs(this);
6005 jvms()->set_should_reexecute(true);
6006
6007 Node* obj = argument(0);
6008 obj = null_check_receiver();
6009 if (stopped()) return true;
6010
6011 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
6012 if (obj_type->is_inlinetypeptr()) {
6013 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
6014 // no identity.
6015 set_result(obj);
6016 return true;
6017 }
6018
6019 // If we are going to clone an instance, we need its exact type to
6020 // know the number and types of fields to convert the clone to
6021 // loads/stores. Maybe a speculative type can help us.
6022 if (!obj_type->klass_is_exact() &&
6023 obj_type->speculative_type() != nullptr &&
6024 obj_type->speculative_type()->is_instance_klass() &&
6025 !obj_type->speculative_type()->is_inlinetype()) {
6026 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6027 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6028 !spec_ik->has_injected_fields()) {
6029 if (!obj_type->isa_instptr() ||
6030 obj_type->is_instptr()->instance_klass()->has_subklass()) {
6031 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6032 }
6033 }
6034 }
6035
6036 // Conservatively insert a memory barrier on all memory slices.
6037 // Do not let writes into the original float below the clone.
6038 insert_mem_bar(Op_MemBarCPUOrder);
6039
6040 // paths into result_reg:
6041 enum {
6042 _slow_path = 1, // out-of-line call to clone method (virtual or not)
6043 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
6044 _array_path, // plain array allocation, plus arrayof_long_arraycopy
6045 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
6046 PATH_LIMIT
6047 };
6048 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6049 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6050 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
6051 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6052 record_for_igvn(result_reg);
6053
6054 Node* obj_klass = load_object_klass(obj);
6055 // We only go to the fast case code if we pass a number of guards.
6056 // The paths which do not pass are accumulated in the slow_region.
6057 RegionNode* slow_region = new RegionNode(1);
6058 record_for_igvn(slow_region);
6059
6060 Node* array_obj = obj;
6061 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6062 if (array_ctl != nullptr) {
6063 // It's an array.
6064 PreserveJVMState pjvms(this);
6065 set_control(array_ctl);
6066
6067 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6068 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6069 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6070 obj_type->can_be_inline_array() &&
6071 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6072 // Flat inline type array may have object field that would require a
6073 // write barrier. Conservatively, go to slow path.
6074 generate_fair_guard(flat_array_test(obj_klass), slow_region);
6075 }
6076
6077 if (!stopped()) {
6078 Node* obj_length = load_array_length(array_obj);
6079 Node* array_size = nullptr; // Size of the array without object alignment padding.
6080 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6081
6082 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6083 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6084 // If it is an oop array, it requires very special treatment,
6085 // because gc barriers are required when accessing the array.
6086 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6087 if (is_obja != nullptr) {
6088 PreserveJVMState pjvms2(this);
6089 set_control(is_obja);
6090 // Generate a direct call to the right arraycopy function(s).
6091 // Clones are always tightly coupled.
6092 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6093 ac->set_clone_oop_array();
6094 Node* n = _gvn.transform(ac);
6095 assert(n == ac, "cannot disappear");
6096 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6097
6098 result_reg->init_req(_objArray_path, control());
6099 result_val->init_req(_objArray_path, alloc_obj);
6100 result_i_o ->set_req(_objArray_path, i_o());
6101 result_mem ->set_req(_objArray_path, reset_memory());
6102 }
6103 }
6104 // Otherwise, there are no barriers to worry about.
6105 // (We can dispense with card marks if we know the allocation
6106 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
6107 // causes the non-eden paths to take compensating steps to
6108 // simulate a fresh allocation, so that no further
6109 // card marks are required in compiled code to initialize
6110 // the object.)
6111
6112 if (!stopped()) {
6113 copy_to_clone(obj, alloc_obj, array_size, true);
6114
6115 // Present the results of the copy.
6116 result_reg->init_req(_array_path, control());
6117 result_val->init_req(_array_path, alloc_obj);
6118 result_i_o ->set_req(_array_path, i_o());
6119 result_mem ->set_req(_array_path, reset_memory());
6120 }
6121 }
6122 }
6123
6124 if (!stopped()) {
6125 // It's an instance (we did array above). Make the slow-path tests.
6126 // If this is a virtual call, we generate a funny guard. We grab
6127 // the vtable entry corresponding to clone() from the target object.
6128 // If the target method which we are calling happens to be the
6129 // Object clone() method, we pass the guard. We do not need this
6130 // guard for non-virtual calls; the caller is known to be the native
6131 // Object clone().
6132 if (is_virtual) {
6133 generate_virtual_guard(obj_klass, slow_region);
6134 }
6135
6136 // The object must be easily cloneable and must not have a finalizer.
6137 // Both of these conditions may be checked in a single test.
6138 // We could optimize the test further, but we don't care.
6139 generate_misc_flags_guard(obj_klass,
6140 // Test both conditions:
6141 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6142 // Must be cloneable but not finalizer:
6143 KlassFlags::_misc_is_cloneable_fast,
6235 set_jvms(sfpt->jvms());
6236 _reexecute_sp = jvms()->sp();
6237
6238 return saved_jvms;
6239 }
6240 }
6241 }
6242 return nullptr;
6243 }
6244
6245 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6246 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6247 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6248 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6249 uint size = alloc->req();
6250 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6251 old_jvms->set_map(sfpt);
6252 for (uint i = 0; i < size; i++) {
6253 sfpt->init_req(i, alloc->in(i));
6254 }
6255 int adjustment = 1;
6256 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6257 if (ary_klass_ptr->is_null_free()) {
6258 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6259 // also requires the componentType and initVal on stack for re-execution.
6260 // Re-create and push the componentType.
6261 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6262 ciInstance* instance = klass->component_mirror_instance();
6263 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6264 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6265 adjustment++;
6266 }
6267 // re-push array length for deoptimization
6268 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6269 if (ary_klass_ptr->is_null_free()) {
6270 // Re-create and push the initVal.
6271 Node* init_val = alloc->in(AllocateNode::InitValue);
6272 if (init_val == nullptr) {
6273 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6274 } else if (UseCompressedOops) {
6275 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6276 }
6277 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6278 adjustment++;
6279 }
6280 old_jvms->set_sp(old_jvms->sp() + adjustment);
6281 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6282 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6283 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6284 old_jvms->set_should_reexecute(true);
6285
6286 sfpt->set_i_o(map()->i_o());
6287 sfpt->set_memory(map()->memory());
6288 sfpt->set_control(map()->control());
6289 return sfpt;
6290 }
6291
6292 // In case of a deoptimization, we restart execution at the
6293 // allocation, allocating a new array. We would leave an uninitialized
6294 // array in the heap that GCs wouldn't expect. Move the allocation
6295 // after the traps so we don't allocate the array if we
6296 // deoptimize. This is possible because tightly_coupled_allocation()
6297 // guarantees there's no observer of the allocated array at this point
6298 // and the control flow is simple enough.
6299 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6300 int saved_reexecute_sp, uint new_idx) {
6301 if (saved_jvms_before_guards != nullptr && !stopped()) {
6302 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6303
6304 assert(alloc != nullptr, "only with a tightly coupled allocation");
6305 // restore JVM state to the state at the arraycopy
6306 saved_jvms_before_guards->map()->set_control(map()->control());
6307 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6308 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6309 // If we've improved the types of some nodes (null check) while
6310 // emitting the guards, propagate them to the current state
6311 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6312 set_jvms(saved_jvms_before_guards);
6313 _reexecute_sp = saved_reexecute_sp;
6314
6315 // Remove the allocation from above the guards
6316 CallProjections* callprojs = alloc->extract_projections(true);
6317 InitializeNode* init = alloc->initialization();
6318 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6319 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6320 init->replace_mem_projs_by(alloc_mem, C);
6321
6322 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6323 // the allocation (i.e. is only valid if the allocation succeeds):
6324 // 1) replace CastIINode with AllocateArrayNode's length here
6325 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6326 //
6327 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6328 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6329 Node* init_control = init->proj_out(TypeFunc::Control);
6330 Node* alloc_length = alloc->Ideal_length();
6331 #ifdef ASSERT
6332 Node* prev_cast = nullptr;
6333 #endif
6334 for (uint i = 0; i < init_control->outcnt(); i++) {
6335 Node* init_out = init_control->raw_out(i);
6336 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6337 #ifdef ASSERT
6338 if (prev_cast == nullptr) {
6339 prev_cast = init_out;
6341 if (prev_cast->cmp(*init_out) == false) {
6342 prev_cast->dump();
6343 init_out->dump();
6344 assert(false, "not equal CastIINode");
6345 }
6346 }
6347 #endif
6348 C->gvn_replace_by(init_out, alloc_length);
6349 }
6350 }
6351 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6352
6353 // move the allocation here (after the guards)
6354 _gvn.hash_delete(alloc);
6355 alloc->set_req(TypeFunc::Control, control());
6356 alloc->set_req(TypeFunc::I_O, i_o());
6357 Node *mem = reset_memory();
6358 set_all_memory(mem);
6359 alloc->set_req(TypeFunc::Memory, mem);
6360 set_control(init->proj_out_or_null(TypeFunc::Control));
6361 set_i_o(callprojs->fallthrough_ioproj);
6362
6363 // Update memory as done in GraphKit::set_output_for_allocation()
6364 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6365 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6366 if (ary_type->isa_aryptr() && length_type != nullptr) {
6367 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6368 }
6369 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6370 int elemidx = C->get_alias_index(telemref);
6371 // Need to properly move every memory projection for the Initialize
6372 #ifdef ASSERT
6373 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6374 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6375 #endif
6376 auto move_proj = [&](ProjNode* proj) {
6377 int alias_idx = C->get_alias_index(proj->adr_type());
6378 assert(alias_idx == Compile::AliasIdxRaw ||
6379 alias_idx == elemidx ||
6380 alias_idx == mark_idx ||
6381 alias_idx == klass_idx, "should be raw memory or array element type");
6691 top_src = src_type->isa_aryptr();
6692 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6693 src_spec = true;
6694 }
6695 if (!has_dest) {
6696 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6697 dest_type = _gvn.type(dest);
6698 top_dest = dest_type->isa_aryptr();
6699 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6700 dest_spec = true;
6701 }
6702 }
6703 }
6704
6705 if (has_src && has_dest && can_emit_guards) {
6706 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6707 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6708 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6709 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6710
6711 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6712 // If both arrays are object arrays then having the exact types
6713 // for both will remove the need for a subtype check at runtime
6714 // before the call and may make it possible to pick a faster copy
6715 // routine (without a subtype check on every element)
6716 // Do we have the exact type of src?
6717 bool could_have_src = src_spec;
6718 // Do we have the exact type of dest?
6719 bool could_have_dest = dest_spec;
6720 ciKlass* src_k = nullptr;
6721 ciKlass* dest_k = nullptr;
6722 if (!src_spec) {
6723 src_k = src_type->speculative_type_not_null();
6724 if (src_k != nullptr && src_k->is_array_klass()) {
6725 could_have_src = true;
6726 }
6727 }
6728 if (!dest_spec) {
6729 dest_k = dest_type->speculative_type_not_null();
6730 if (dest_k != nullptr && dest_k->is_array_klass()) {
6731 could_have_dest = true;
6732 }
6733 }
6734 if (could_have_src && could_have_dest) {
6735 // If we can have both exact types, emit the missing guards
6736 if (could_have_src && !src_spec) {
6737 src = maybe_cast_profiled_obj(src, src_k, true);
6738 src_type = _gvn.type(src);
6739 top_src = src_type->isa_aryptr();
6740 }
6741 if (could_have_dest && !dest_spec) {
6742 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6743 dest_type = _gvn.type(dest);
6744 top_dest = dest_type->isa_aryptr();
6745 }
6746 }
6747 }
6748 }
6749
6750 ciMethod* trap_method = method();
6751 int trap_bci = bci();
6752 if (saved_jvms_before_guards != nullptr) {
6753 trap_method = alloc->jvms()->method();
6754 trap_bci = alloc->jvms()->bci();
6755 }
6756
6757 bool negative_length_guard_generated = false;
6758
6759 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6760 can_emit_guards && !src->is_top() && !dest->is_top()) {
6761 // validate arguments: enables transformation the ArrayCopyNode
6762 validated = true;
6763
6764 RegionNode* slow_region = new RegionNode(1);
6765 record_for_igvn(slow_region);
6766
6767 // (1) src and dest are arrays.
6768 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6769 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6770
6771 // (2) src and dest arrays must have elements of the same BasicType
6772 // done at macro expansion or at Ideal transformation time
6773
6774 // (4) src_offset must not be negative.
6775 generate_negative_guard(src_offset, slow_region);
6776
6777 // (5) dest_offset must not be negative.
6778 generate_negative_guard(dest_offset, slow_region);
6779
6780 // (7) src_offset + length must not exceed length of src.
6781 generate_limit_guard(src_offset, length,
6782 load_array_length(src),
6783 slow_region);
6784
6785 // (8) dest_offset + length must not exceed length of dest.
6786 generate_limit_guard(dest_offset, length,
6787 load_array_length(dest),
6788 slow_region);
6789
6790 // (6) length must not be negative.
6791 // This is also checked in generate_arraycopy() during macro expansion, but
6792 // we also have to check it here for the case where the ArrayCopyNode will
6793 // be eliminated by Escape Analysis.
6794 if (EliminateAllocations) {
6795 generate_negative_guard(length, slow_region);
6796 negative_length_guard_generated = true;
6797 }
6798
6799 // (9) each element of an oop array must be assignable
6800 Node* dest_klass = load_object_klass(dest);
6801 Node* refined_dest_klass = dest_klass;
6802 if (src != dest) {
6803 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6804 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6805 slow_region->add_req(not_subtype_ctrl);
6806 }
6807
6808 // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6809 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6810 Node* src_klass = load_object_klass(src);
6811 Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6812 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6813 Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6814 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6815
6816 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6817 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6818 prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6819
6820 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6821 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6822 generate_fair_guard(tst, slow_region);
6823
6824 // TODO 8350865 This is too strong
6825 generate_fair_guard(flat_array_test(src), slow_region);
6826 generate_fair_guard(flat_array_test(dest), slow_region);
6827
6828 {
6829 PreserveJVMState pjvms(this);
6830 set_control(_gvn.transform(slow_region));
6831 uncommon_trap(Deoptimization::Reason_intrinsic,
6832 Deoptimization::Action_make_not_entrant);
6833 assert(stopped(), "Should be stopped");
6834 }
6835
6836 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6837 if (dest_klass_t == nullptr) {
6838 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6839 // are in a dead path.
6840 uncommon_trap(Deoptimization::Reason_intrinsic,
6841 Deoptimization::Action_make_not_entrant);
6842 return true;
6843 }
6844
6845 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6846 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6847 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6848 }
6849
6850 if (stopped()) {
6851 return true;
6852 }
6853
6854 Node* dest_klass = load_object_klass(dest);
6855 dest_klass = load_non_refined_array_klass(dest_klass);
6856
6857 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6858 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6859 // so the compiler has a chance to eliminate them: during macro expansion,
6860 // we have to set their control (CastPP nodes are eliminated).
6861 load_object_klass(src), dest_klass,
6862 load_array_length(src), load_array_length(dest));
6863
6864 ac->set_arraycopy(validated);
6865
6866 Node* n = _gvn.transform(ac);
6867 if (n == ac) {
6868 ac->connect_outputs(this);
6869 } else {
6870 assert(validated, "shouldn't transform if all arguments not validated");
6871 set_all_memory(n);
6872 }
6873 clear_upper_avx();
6874
6875
6876 return true;
6877 }
6878
6879
6880 // Helper function which determines if an arraycopy immediately follows
6881 // an allocation, with no intervening tests or other escapes for the object.
|