diff --git a/make/RunTests.gmk b/make/RunTests.gmk index 051be9021d7c..20ad612ecee5 100644 --- a/make/RunTests.gmk +++ b/make/RunTests.gmk @@ -526,6 +526,7 @@ define SetupRunGtestTestBody $$(call MakeDir, $$($1_TEST_RESULTS_DIR) $$($1_TEST_SUPPORT_DIR)) $$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/gtest, \ $$(CD) $$($1_TEST_SUPPORT_DIR) && \ + $(if $(call isTargetOs, aix), LIBPATH=$$(TEST_IMAGE_DIR)/hotspot/gtest/$$($1_VARIANT):$$$$LIBPATH) \ $$(FIXPATH) $$(TEST_IMAGE_DIR)/hotspot/gtest/$$($1_VARIANT)/gtestLauncher \ -jdk $(JDK_UNDER_TEST) $$($1_GTEST_FILTER) \ --gtest_output=xml:$$($1_TEST_RESULTS_DIR)/gtest.xml \ @@ -545,7 +546,7 @@ define SetupRunGtestTestBody $$(subst $$(TOPDIR)/, , $$($1_TEST_RESULTS_DIR)))) $$(if $$(wildcard $$($1_RESULT_FILE)), \ $$(eval $1_RUN := $$(shell $$(AWK) \ - '/==========.* tests? from .* test (cases?|suites?) ran/ { print $$$$2 }' \ + '/\==========.* tests? from .* test (cases?|suites?) ran/ { print $$$$2 }' \ $$($1_RESULT_FILE))) \ $$(if $$($1_RUN), , $$(eval $1_RUN := 0)) \ $$(eval $1_PASSED := $$(shell $$(AWK) '/\[ PASSED \] .* tests?./ \ diff --git a/make/hotspot/lib/CompileGtest.gmk b/make/hotspot/lib/CompileGtest.gmk index 3a5fac345973..86a49a793d32 100644 --- a/make/hotspot/lib/CompileGtest.gmk +++ b/make/hotspot/lib/CompileGtest.gmk @@ -84,6 +84,7 @@ $(eval $(call SetupJdkLibrary, BUILD_GTEST_LIBGTEST, \ -I$(GTEST_FRAMEWORK_SRC)/googlemock \ -I$(GTEST_FRAMEWORK_SRC)/googlemock/include, \ CFLAGS_macosx := -DGTEST_OS_MAC=1, \ + CFLAGS_aix := -DGTEST_HAS_PTHREAD=1, \ OPTIMIZATION := $(JVM_OPTIMIZATION), \ COPY_DEBUG_SYMBOLS := $(GTEST_COPY_DEBUG_SYMBOLS), \ ZIP_EXTERNAL_DEBUG_SYMBOLS := false, \ @@ -114,6 +115,7 @@ $(eval $(call SetupJdkLibrary, BUILD_GTEST_LIBJVM, \ -I$(GTEST_FRAMEWORK_SRC)/googlemock/include \ $(addprefix -I, $(GTEST_TEST_SRC)), \ CFLAGS_macosx := -DGTEST_OS_MAC=1, \ + CFLAGS_aix := -DGTEST_HAS_PTHREAD=1, \ DISABLED_WARNINGS_gcc := $(DISABLED_WARNINGS_gcc) \ undef stringop-overflow, \ DISABLED_WARNINGS_gcc_test_metaspace_misc.cpp := unused-const-variable, \ diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index 738556a6f1d2..3845b30e2ad4 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -1768,11 +1768,6 @@ int ConstantTable::calculate_table_base_offset() const { return 0; // absolute addressing, no offset } -bool MachConstantBaseNode::requires_postalloc_expand() const { return false; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - ShouldNotReachHere(); -} - void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { // Empty encoding } @@ -1969,7 +1964,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r assert(src_lo != OptoReg::Bad && dst_lo != OptoReg::Bad, "must move at least 1 register"); - if (src_hi != OptoReg::Bad && !bottom_type()->isa_pvectmask()) { + if (src_hi != OptoReg::Bad && !bottom_type()->is_pvectmask()) { assert((src_lo&1)==0 && src_lo+1==src_hi && (dst_lo&1)==0 && dst_lo+1==dst_hi, "expected aligned-adjacent pairs"); @@ -1984,7 +1979,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r int src_offset = ra_->reg2offset(src_lo); int dst_offset = ra_->reg2offset(dst_lo); - if (bottom_type()->isa_vect() && !bottom_type()->isa_pvectmask()) { + if (bottom_type()->is_vect() && !bottom_type()->is_pvectmask()) { uint ireg = ideal_reg(); DEBUG_ONLY(int algm = MIN2(RegMask::num_registers(ireg), (int)Matcher::stack_alignment_in_slots()) * VMRegImpl::stack_slot_size); assert((src_lo_rc != rc_stack) || is_aligned(src_offset, algm), "unaligned vector spill sp offset %d (src)", src_offset); @@ -2132,7 +2127,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r } else { st->print("%s", Matcher::regName[dst_lo]); } - if (bottom_type()->isa_vect() && !bottom_type()->isa_pvectmask()) { + if (bottom_type()->is_vect() && !bottom_type()->is_pvectmask()) { int vsize = 0; switch (ideal_reg()) { case Op_VecD: @@ -2626,11 +2621,7 @@ Assembler::Condition to_assembler_cond(BoolTest::mask cond) { // Binary src (Replicate con) static bool is_valid_sve_arith_imm_pattern(Node* n, Node* m) { - if (n == nullptr || m == nullptr) { - return false; - } - - if (UseSVE == 0 || m->Opcode() != Op_Replicate) { + if (n == nullptr || UseSVE == 0 || !Node::is_exact(m)) { return false; } @@ -2640,7 +2631,7 @@ static bool is_valid_sve_arith_imm_pattern(Node* n, Node* m) { } const Type* t = imm_node->bottom_type(); - if (!(t->isa_int() || t->isa_long())) { + if (!(t->is_int() || t->is_long())) { return false; } @@ -2649,7 +2640,7 @@ static bool is_valid_sve_arith_imm_pattern(Node* n, Node* m) { case Op_OrV: case Op_XorV: { Assembler::SIMD_RegVariant T = Assembler::elemType_to_regVariant(Matcher::vector_element_basic_type(n)); - uint64_t value = t->isa_long() ? (uint64_t)imm_node->get_long() : (uint64_t)imm_node->get_int(); + uint64_t value = t->is_long() ? (uint64_t)imm_node->get_long() : (uint64_t)imm_node->get_int(); return Assembler::operand_valid_for_sve_logical_immediate(Assembler::regVariant_to_elemBits(T), value); } case Op_AddVB: @@ -2666,11 +2657,7 @@ static bool is_valid_sve_arith_imm_pattern(Node* n, Node* m) { // (XorV src (Replicate m1)) static bool is_vector_bitwise_not_pattern(Node* n, Node* m) { - if (n != nullptr && m != nullptr) { - return n->Opcode() == Op_XorV && - VectorNode::is_all_ones_vector(m); - } - return false; + return Node::is_exact(n) && m != nullptr && VectorNode::is_all_ones_vector(m); } // Returns true if (n, m) matches "(XorVMask vm2 (MaskAll m1))" and that XorVMask @@ -2681,12 +2668,9 @@ static bool is_vector_bitwise_not_pattern(Node* n, Node* m) { // Limitation: the "andNot" rule still cannot be matched if "m" has other // uses outside this pattern. static bool is_vector_mask_not_operand_in_andnot_pattern(Node* n, Node* m) { - if (n == nullptr || m == nullptr) { - return false; - } - - if (VectorNode::is_all_ones_vector(m) && - n->Opcode() == Op_XorVMask && + if (m != nullptr && + Node::is_exact(n) && + VectorNode::is_all_ones_vector(m) && n->outcnt() == 1 && n->unique_out()->Opcode() == Op_AndVMask) { // If another input of the AndVMask is also a mask-not pattern that would @@ -8287,8 +8271,8 @@ instruct encodeHeapOop_not_null(iRegNNoSp dst, iRegP src, rFlagsReg cr) %{ %} instruct decodeHeapOop(iRegPNoSp dst, iRegN src, rFlagsReg cr) %{ - predicate(n->bottom_type()->is_ptr()->ptr() != TypePtr::NotNull && - n->bottom_type()->is_ptr()->ptr() != TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() != TypePtr::NotNull && + n->bottom_type()->as_ptr()->ptr() != TypePtr::Constant); match(Set dst (DecodeN src)); ins_cost(INSN_COST * 3); format %{ "decode_heap_oop $dst, $src" %} @@ -8301,8 +8285,8 @@ instruct decodeHeapOop(iRegPNoSp dst, iRegN src, rFlagsReg cr) %{ %} instruct decodeHeapOop_not_null(iRegPNoSp dst, iRegN src, rFlagsReg cr) %{ - predicate(n->bottom_type()->is_ptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_ptr()->ptr() == TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() == TypePtr::NotNull || + n->bottom_type()->as_ptr()->ptr() == TypePtr::Constant); match(Set dst (DecodeN src)); ins_cost(INSN_COST * 3); format %{ "decode_heap_oop_not_null $dst, $src" %} @@ -8388,7 +8372,7 @@ instruct castII_checked(iRegI dst, rFlagsReg cr) format %{ "# castII_checked of $dst" %} ins_encode %{ - __ verify_int_in_range(_idx, bottom_type()->is_int(), $dst$$Register, rscratch1); + __ verify_int_in_range(_idx, bottom_type()->as_int(), $dst$$Register, rscratch1); %} ins_pipe(pipe_slow); %} @@ -8416,7 +8400,7 @@ instruct castII_checked_nosp(iRegINoSp dst, rFlagsReg cr) format %{ "# castII_checked of $dst" %} ins_encode %{ - __ verify_int_in_range(_idx, bottom_type()->is_int(), $dst$$Register, rscratch1); + __ verify_int_in_range(_idx, bottom_type()->as_int(), $dst$$Register, rscratch1); %} ins_pipe(pipe_slow); %} @@ -8441,7 +8425,7 @@ instruct castLL_checked(iRegL dst, rFlagsReg cr) format %{ "# castLL_checked of $dst" %} ins_encode %{ - __ verify_long_in_range(_idx, bottom_type()->is_long(), $dst$$Register, rscratch1); + __ verify_long_in_range(_idx, bottom_type()->as_long(), $dst$$Register, rscratch1); %} ins_pipe(pipe_slow); %} diff --git a/src/hotspot/cpu/aarch64/aarch64_vector.ad b/src/hotspot/cpu/aarch64/aarch64_vector.ad index d02caeba6fbc..6d2d2b623811 100644 --- a/src/hotspot/cpu/aarch64/aarch64_vector.ad +++ b/src/hotspot/cpu/aarch64/aarch64_vector.ad @@ -412,6 +412,87 @@ source %{ return match_rule_supported_vector(opcode, vlen, bt); } + // Determine whether the given multiply-add/sub-structured node is a profitable + // vector MLA/MLS candidate. + // + // A multiply-add/sub-structured node is NOT considered a profitable MLA/MLS + // candidate if forming an MLA/MLS would likely extend a dependency chain, e.g. + // + // add_input MulVL MulVL add_input + // \ / \ / + // AddVL/SubVL AddVL + // + // - The "add_input" itself is (or feeds from) another multiply-add/sub-structured + // node or a multiply node. + // + // Exceptions: + // If the "add_input" is identical to one of the multiply operands, then fusing + // does not introduce an additional dependency edge and is allowed. + // + // The main idea behind this change is to improve parallelism between the two inputs + // of AddVL. When "add_input" is MulVL or MLA and has no dependency on MulVL + // (the other input of AddVL), we can benefit from executing add_input and MulVL + // in parallel. However, this parallelism depends on hardware scheduling behavior + // and available resources, so it does not apply uniformly across all microarchitectures. + // Therefore, AvoidMLAChain is applied selectively. + bool Matcher::is_multiply_accumulate_candidate(const Node* n) { + if (n->Opcode() != Op_AddVL && n->Opcode() != Op_SubVL) { + return true; + } + // Only apply the chain-length heuristic to 128-bit vectors. + if (!AvoidMLAChain || Matcher::vector_length_in_bytes(n) != 16) { + return true; + } + + Node* in1 = nullptr; + Node* in2 = nullptr; + if (n->is_predicated_vector()) { + // Masked AD rules use (AddVL/SubVL (Binary src1 src2) pg). + assert(n->in(1)->Opcode() == Op_Binary, ""); + in1 = n->in(1)->in(1); + in2 = n->in(1)->in(2); + } else { + in1 = n->in(1); + in2 = n->in(2); + } + + // Exception: + // If the "add_input" is already needed to compute the "mul", the + // multiply-add/sub-structured node is still considered a profitable vector + // MLA/MLS candidate: + // + // add_input ... ... add_input + // \ \ / \ / / + // \ MulVL MulVL / + // \ / \ / + // AddVL/SubVL AddVL + if (VectorNode::is_unpredicated_vector_long_multiply(in1)) { + if (in2 == in1->in(1) || in2 == in1->in(2)) { + return true; + } + } + if (VectorNode::is_unpredicated_vector_long_multiply(in2)) { + if (in1 == in2->in(1) || in1 == in2->in(2)) { + return true; + } + } + + // If both inputs are already long-mul(-add/sub) patterns, fusing again tends + // to lengthen chains. + if (VectorNode::is_vector_long_mul_or_muladdsub(in1) && + VectorNode::is_vector_long_mul_or_muladdsub(in2)) { + return false; + } + + // If an input is a Phi, check whether *its* incoming values are long-mul patterns. + if (VectorNode::phi_has_vector_long_mul_or_muladdsub_input(in1) || + VectorNode::phi_has_vector_long_mul_or_muladdsub_input(in2)) { + return false; + } + + return true; + } + bool Matcher::vector_needs_partial_operations(Node* node, const TypeVect* vt) { // 1. Only SVE requires partial vector operations. // 2. The vector size in bytes must be smaller than MaxVectorSize. @@ -476,11 +557,11 @@ source %{ // On architectures that do not support predicate, masks are stored in // general vector registers (TypeVect) with sizes ranging from TypeVectA // to TypeVectX based on the vector size in bytes. - assert(vt->isa_pvectmask() == nullptr, "mask type is not matched"); + assert(!vt->is_pvectmask(), "mask type is not matched"); return false; } - assert(vt->isa_pvectmask() != nullptr, "expected TypePVectMask on SVE"); + assert(vt->is_pvectmask(), "expected TypePVectMask on SVE"); switch (opcode) { case Op_VectorMaskToLong: case Op_VectorLongToMask: @@ -2972,7 +3053,7 @@ instruct vmla(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmlaL(vReg dst_src1, vReg src2, vReg src3) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (AddVL dst_src1 (MulVL src2 src3))); format %{ "vmlaL $dst_src1, $src2, $src3" %} ins_encode %{ @@ -2984,7 +3065,7 @@ instruct vmlaL(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmla_masked(vReg dst_src1, vReg src2, vReg src3, pRegGov pg) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (AddVB (Binary dst_src1 (MulVB src2 src3)) pg)); match(Set dst_src1 (AddVS (Binary dst_src1 (MulVS src2 src3)) pg)); match(Set dst_src1 (AddVI (Binary dst_src1 (MulVI src2 src3)) pg)); @@ -3063,7 +3144,7 @@ instruct vmls(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmlsL(vReg dst_src1, vReg src2, vReg src3) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (SubVL dst_src1 (MulVL src2 src3))); format %{ "vmlsL $dst_src1, $src2, $src3" %} ins_encode %{ @@ -3075,7 +3156,7 @@ instruct vmlsL(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmls_masked(vReg dst_src1, vReg src2, vReg src3, pRegGov pg) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (SubVB (Binary dst_src1 (MulVB src2 src3)) pg)); match(Set dst_src1 (SubVS (Binary dst_src1 (MulVS src2 src3)) pg)); match(Set dst_src1 (SubVI (Binary dst_src1 (MulVI src2 src3)) pg)); diff --git a/src/hotspot/cpu/aarch64/aarch64_vector_ad.m4 b/src/hotspot/cpu/aarch64/aarch64_vector_ad.m4 index ab2c3326a9b9..5efa1d7aa312 100644 --- a/src/hotspot/cpu/aarch64/aarch64_vector_ad.m4 +++ b/src/hotspot/cpu/aarch64/aarch64_vector_ad.m4 @@ -402,6 +402,87 @@ source %{ return match_rule_supported_vector(opcode, vlen, bt); } + // Determine whether the given multiply-add/sub-structured node is a profitable + // vector MLA/MLS candidate. + // + // A multiply-add/sub-structured node is NOT considered a profitable MLA/MLS + // candidate if forming an MLA/MLS would likely extend a dependency chain, e.g. + // + // add_input MulVL MulVL add_input + // \ / \ / + // AddVL/SubVL AddVL + // + // - The "add_input" itself is (or feeds from) another multiply-add/sub-structured + // node or a multiply node. + // + // Exceptions: + // If the "add_input" is identical to one of the multiply operands, then fusing + // does not introduce an additional dependency edge and is allowed. + // + // The main idea behind this change is to improve parallelism between the two inputs + // of AddVL. When "add_input" is MulVL or MLA and has no dependency on MulVL + // (the other input of AddVL), we can benefit from executing add_input and MulVL + // in parallel. However, this parallelism depends on hardware scheduling behavior + // and available resources, so it does not apply uniformly across all microarchitectures. + // Therefore, AvoidMLAChain is applied selectively. + bool Matcher::is_multiply_accumulate_candidate(const Node* n) { + if (n->Opcode() != Op_AddVL && n->Opcode() != Op_SubVL) { + return true; + } + // Only apply the chain-length heuristic to 128-bit vectors. + if (!AvoidMLAChain || Matcher::vector_length_in_bytes(n) != 16) { + return true; + } + + Node* in1 = nullptr; + Node* in2 = nullptr; + if (n->is_predicated_vector()) { + // Masked AD rules use (AddVL/SubVL (Binary src1 src2) pg). + assert(n->in(1)->Opcode() == Op_Binary, ""); + in1 = n->in(1)->in(1); + in2 = n->in(1)->in(2); + } else { + in1 = n->in(1); + in2 = n->in(2); + } + + // Exception: + // If the "add_input" is already needed to compute the "mul", the + // multiply-add/sub-structured node is still considered a profitable vector + // MLA/MLS candidate: + // + // add_input ... ... add_input + // \ \ / \ / / + // \ MulVL MulVL / + // \ / \ / + // AddVL/SubVL AddVL + if (VectorNode::is_unpredicated_vector_long_multiply(in1)) { + if (in2 == in1->in(1) || in2 == in1->in(2)) { + return true; + } + } + if (VectorNode::is_unpredicated_vector_long_multiply(in2)) { + if (in1 == in2->in(1) || in1 == in2->in(2)) { + return true; + } + } + + // If both inputs are already long-mul(-add/sub) patterns, fusing again tends + // to lengthen chains. + if (VectorNode::is_vector_long_mul_or_muladdsub(in1) && + VectorNode::is_vector_long_mul_or_muladdsub(in2)) { + return false; + } + + // If an input is a Phi, check whether *its* incoming values are long-mul patterns. + if (VectorNode::phi_has_vector_long_mul_or_muladdsub_input(in1) || + VectorNode::phi_has_vector_long_mul_or_muladdsub_input(in2)) { + return false; + } + + return true; + } + bool Matcher::vector_needs_partial_operations(Node* node, const TypeVect* vt) { // 1. Only SVE requires partial vector operations. // 2. The vector size in bytes must be smaller than MaxVectorSize. @@ -466,11 +547,11 @@ source %{ // On architectures that do not support predicate, masks are stored in // general vector registers (TypeVect) with sizes ranging from TypeVectA // to TypeVectX based on the vector size in bytes. - assert(vt->isa_pvectmask() == nullptr, "mask type is not matched"); + assert(!vt->is_pvectmask(), "mask type is not matched"); return false; } - assert(vt->isa_pvectmask() != nullptr, "expected TypePVectMask on SVE"); + assert(vt->is_pvectmask(), "expected TypePVectMask on SVE"); switch (opcode) { case Op_VectorMaskToLong: case Op_VectorLongToMask: @@ -1585,7 +1666,7 @@ instruct vmla(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmlaL(vReg dst_src1, vReg src2, vReg src3) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (AddVL dst_src1 (MulVL src2 src3))); format %{ "vmlaL $dst_src1, $src2, $src3" %} ins_encode %{ @@ -1597,7 +1678,7 @@ instruct vmlaL(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmla_masked(vReg dst_src1, vReg src2, vReg src3, pRegGov pg) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (AddVB (Binary dst_src1 (MulVB src2 src3)) pg)); match(Set dst_src1 (AddVS (Binary dst_src1 (MulVS src2 src3)) pg)); match(Set dst_src1 (AddVI (Binary dst_src1 (MulVI src2 src3)) pg)); @@ -1676,7 +1757,7 @@ instruct vmls(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmlsL(vReg dst_src1, vReg src2, vReg src3) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (SubVL dst_src1 (MulVL src2 src3))); format %{ "vmlsL $dst_src1, $src2, $src3" %} ins_encode %{ @@ -1688,7 +1769,7 @@ instruct vmlsL(vReg dst_src1, vReg src2, vReg src3) %{ %} instruct vmls_masked(vReg dst_src1, vReg src2, vReg src3, pRegGov pg) %{ - predicate(UseSVE > 0); + predicate(UseSVE > 0 && Matcher::is_multiply_accumulate_candidate(n)); match(Set dst_src1 (SubVB (Binary dst_src1 (MulVB src2 src3)) pg)); match(Set dst_src1 (SubVS (Binary dst_src1 (MulVS src2 src3)) pg)); match(Set dst_src1 (SubVI (Binary dst_src1 (MulVI src2 src3)) pg)); diff --git a/src/hotspot/cpu/aarch64/gc/g1/g1_aarch64.ad b/src/hotspot/cpu/aarch64/gc/g1/g1_aarch64.ad index c68b8797b0c5..7d96b1944914 100644 --- a/src/hotspot/cpu/aarch64/gc/g1/g1_aarch64.ad +++ b/src/hotspot/cpu/aarch64/gc/g1/g1_aarch64.ad @@ -73,18 +73,14 @@ static void write_barrier_post(MacroAssembler* masm, %} -// TODO 8350865 (same applies to g1StoreLSpecialTwoOops) -// - Do not set/overwrite barrier data here, also handle G1C2BarrierPostNotNull -// - Move this into the .m4? instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI0 off, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem (Binary src off))); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr); ins_cost(INSN_COST); format %{ "str $src, $mem\t# g1StoreLSpecialOneOopOff0" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); write_barrier_pre(masm, this, $mem$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -95,8 +91,15 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI0 off, iRegP __ str($src$$Register, $mem$$Register); // Extract the narrow oop field value - __ ubfm($tmp1$$Register, $src$$Register, 0, 31); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ ubfm($tmp1$$Register, $src$$Register, 0, 31); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } + write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -108,16 +111,16 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI0 off, iRegP instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, iRegPNoSp tmp4, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem (Binary src off))); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, KILL cr); ins_cost(INSN_COST); format %{ "str $src, $mem\t# g1StoreLSpecialOneOopOff4" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - // Adjust address to point to narrow oop - __ add($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & G1C2BarrierPre) != 0 || (barrier_data() & G1C2BarrierPost) != 0) { + __ add($tmp4$$Register, $mem$$Register, 4); + } write_barrier_pre(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -128,8 +131,14 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iReg __ str($src$$Register, $mem$$Register); // Shift long value to extract the narrow oop field value - __ lsr($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ lsr($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $tmp4$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -141,14 +150,12 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iReg instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, iRegPNoSp tmp4, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem src)); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, KILL cr); ins_cost(INSN_COST); format %{ "str $src, $mem\t# g1StoreLSpecialTwoOops" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - write_barrier_pre(masm, this, $mem$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -156,7 +163,9 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe $tmp3$$Register /* tmp2 */, RegSet::of($mem$$Register, $src$$Register) /* preserve */); // Adjust address to point to the second narrow oop in the long value - __ add($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & G1C2BarrierPre) != 0 || (barrier_data() & G1C2BarrierPost) != 0) { + __ add($tmp4$$Register, $mem$$Register, 4); + } write_barrier_pre(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -167,8 +176,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe __ str($src$$Register, $mem$$Register); // Zero-extend first narrow oop to long - __ ubfm($tmp1$$Register, $src$$Register, 0, 31); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ ubfm($tmp1$$Register, $src$$Register, 0, 31); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -176,8 +191,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe $tmp3$$Register /* tmp2 */); // Shift long value to extract the second narrow oop field value - __ lsr($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ lsr($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $tmp4$$Register /* store_addr */, $tmp1$$Register /* new_val */, diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp index 51d3959e4753..84e92e2551f6 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp @@ -702,7 +702,7 @@ void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, Mac void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval, Register newval, Register addr, Register tmp1, Register tmp2, Register tmp3, bool is_acquire) { - bool is_narrow = node->bottom_type()->isa_narrowoop(); + bool is_narrow = node->bottom_type()->is_narrowoop(); ShenandoahBarrierStubC2::load_store_pre(masm, node, addr, tmp1, tmp2, tmp3, is_narrow); diff --git a/src/hotspot/cpu/aarch64/globals_aarch64.hpp b/src/hotspot/cpu/aarch64/globals_aarch64.hpp index eb19d08134c8..d77a6d05ad38 100644 --- a/src/hotspot/cpu/aarch64/globals_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/globals_aarch64.hpp @@ -102,6 +102,8 @@ define_pd_global(intx, InlineSmallCode, 1000); "Use SIMD SHA3 instructions for SHA3 intrinsic") \ product(bool, AvoidUnalignedAccesses, false, \ "Avoid generating unaligned memory accesses") \ + product(bool, AvoidMLAChain, false, DIAGNOSTIC, \ + "Avoid long dependency chains formed by MLA instructions") \ product(bool, UseLSE, false, \ "Use LSE instructions") \ product(uint, UseSVE, 0, \ diff --git a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp index fd131038a6e9..26d75b94bf2e 100644 --- a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp @@ -313,6 +313,12 @@ void VM_Version::initialize() { if (FLAG_IS_DEFAULT(AlwaysMergeDMB)) { FLAG_SET_DEFAULT(AlwaysMergeDMB, false); } + // Avoiding fused multiply-add instruction chains and generating + // separate SVE multiply and add instructions can improve + // instruction-level parallelism and overall performance. + if (FLAG_IS_DEFAULT(AvoidMLAChain)) { + FLAG_SET_DEFAULT(AvoidMLAChain, true); + } } if (supports_feature(CPU_FP) || supports_feature(CPU_ASIMD)) { diff --git a/src/hotspot/cpu/arm/arm.ad b/src/hotspot/cpu/arm/arm.ad index 391c95c3b677..8d4c0d68623d 100644 --- a/src/hotspot/cpu/arm/arm.ad +++ b/src/hotspot/cpu/arm/arm.ad @@ -218,11 +218,6 @@ int ConstantTable::calculate_table_base_offset() const { return offset; } -bool MachConstantBaseNode::requires_postalloc_expand() const { return false; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - ShouldNotReachHere(); -} - void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { Compile* C = ra_->C; ConstantTable& constant_table = C->output()->constant_table(); @@ -434,7 +429,7 @@ uint MachSpillCopyNode::implementation( C2_MacroAssembler *masm, return size; // Self copy, no move #ifdef TODO - if (bottom_type()->isa_vect() != nullptr) { + if (bottom_type()->is_vect()) { } #endif diff --git a/src/hotspot/cpu/arm/arm_32.ad b/src/hotspot/cpu/arm/arm_32.ad index 87ffc46e67a9..678249866a7b 100644 --- a/src/hotspot/cpu/arm/arm_32.ad +++ b/src/hotspot/cpu/arm/arm_32.ad @@ -501,7 +501,7 @@ operand immIRotn() %{ %} operand immPRot() %{ - predicate(n->get_ptr() == 0 || (AsmOperand::is_rotated_imm(n->get_ptr()) && ((ConPNode*)n)->type()->is_ptr()->reloc() == relocInfo::none)); + predicate(n->get_ptr() == 0 || (AsmOperand::is_rotated_imm(n->get_ptr()) && ((ConPNode*)n)->type()->as_ptr()->reloc() == relocInfo::none)); match(ConP); diff --git a/src/hotspot/cpu/ppc/gc/g1/g1_ppc.ad b/src/hotspot/cpu/ppc/gc/g1/g1_ppc.ad index 6368842dcede..52eb4c09ff53 100644 --- a/src/hotspot/cpu/ppc/gc/g1/g1_ppc.ad +++ b/src/hotspot/cpu/ppc/gc/g1/g1_ppc.ad @@ -96,8 +96,6 @@ static void post_write_barrier(MacroAssembler* masm, %} -// TODO 8350865 (same applies to g1StoreLSpecialTwoOops) -// - Do not set/overwrite barrier data here, also handle G1C2BarrierPostNotNull instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLsrc src, immI_0 off, iRegPdst tmp1, iRegPdst tmp2, iRegPdst tmp3, flagsRegCR0 cr0) %{ predicate(UseG1GC); @@ -106,7 +104,6 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLsrc src, immI_0 off, iRegP ins_cost(2 * MEMORY_REF_COST); format %{ "std $mem, $src\t# g1StoreLSpecialOneOopOff0" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); pre_write_barrier(masm, this, $mem$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -116,13 +113,15 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLsrc src, immI_0 off, iRegP __ std($src$$Register, 0, $mem$$Register); - extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 0); - __ decode_heap_oop($tmp1$$Register); - post_write_barrier(masm, this, - $mem$$Register /* store_addr */, - $tmp1$$Register /* new_val */, - $tmp2$$Register /* tmp1 */, - $tmp3$$Register /* tmp2 */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 0); + post_write_barrier(masm, this, + $mem$$Register /* store_addr */, + $tmp1$$Register /* new_val */, + $tmp2$$Register /* tmp1 */, + $tmp3$$Register /* tmp2 */, + true /* decode_new_val */); + } %} ins_pipe(pipe_class_default); %} @@ -135,10 +134,10 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLsrc src, immI_4 off, iRegP ins_cost(2 * MEMORY_REF_COST); format %{ "std $mem, $src\t# g1StoreLSpecialOneOopOff4" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - - // Adjust address to point to the narrow oop at offset 4. - __ addi($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & G1C2BarrierPre) != 0 || (barrier_data() & G1C2BarrierPost) != 0) { + // Adjust address to point to the narrow oop at offset 4 if a barrier is needed. + __ addi($tmp4$$Register, $mem$$Register, 4); + } pre_write_barrier(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -148,13 +147,15 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLsrc src, immI_4 off, iRegP __ std($src$$Register, 0, $mem$$Register); - extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 4); - __ decode_heap_oop($tmp1$$Register); - post_write_barrier(masm, this, - $tmp4$$Register /* store_addr */, - $tmp1$$Register /* new_val */, - $tmp2$$Register /* tmp1 */, - $tmp3$$Register /* tmp2 */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 4); + post_write_barrier(masm, this, + $tmp4$$Register /* store_addr */, + $tmp1$$Register /* new_val */, + $tmp2$$Register /* tmp1 */, + $tmp3$$Register /* tmp2 */, + true /* decode_new_val */); + } %} ins_pipe(pipe_class_default); %} @@ -167,8 +168,6 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLsrc src, iRegPdst tmp1, iRegP ins_cost(2 * MEMORY_REF_COST); format %{ "std $mem, $src\t# g1StoreLSpecialTwoOops" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - // Issue 2 pre-barriers for oops at offset 0 and 4 pre_write_barrier(masm, this, $mem$$Register /* obj */, @@ -176,7 +175,9 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLsrc src, iRegPdst tmp1, iRegP $tmp2$$Register /* tmp1 */, $tmp3$$Register /* tmp2 */, RegSet::of($mem$$Register, $src$$Register) /* preserve */); - __ addi($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & G1C2BarrierPre) != 0 || (barrier_data() & G1C2BarrierPost) != 0) { + __ addi($tmp4$$Register, $mem$$Register, 4); + } pre_write_barrier(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -186,21 +187,23 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLsrc src, iRegPdst tmp1, iRegP __ std($src$$Register, 0, $mem$$Register); - extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 0); - __ decode_heap_oop($tmp1$$Register); - post_write_barrier(masm, this, - $mem$$Register /* store_addr */, - $tmp1$$Register /* new_val */, - $tmp2$$Register /* tmp1 */, - $tmp3$$Register /* tmp2 */); - - extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 4); - __ decode_heap_oop($tmp1$$Register); - post_write_barrier(masm, this, - $tmp4$$Register /* store_addr */, - $tmp1$$Register /* new_val */, - $tmp2$$Register /* tmp1 */, - $tmp3$$Register /* tmp2 */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 0); + post_write_barrier(masm, this, + $mem$$Register /* store_addr */, + $tmp1$$Register /* new_val */, + $tmp2$$Register /* tmp1 */, + $tmp3$$Register /* tmp2 */, + true /* decode_new_val */); + + extract_narrow_oop(masm, $tmp1$$Register, $src$$Register, 4); + post_write_barrier(masm, this, + $tmp4$$Register /* store_addr */, + $tmp1$$Register /* new_val */, + $tmp2$$Register /* tmp1 */, + $tmp3$$Register /* tmp2 */, + true /* decode_new_val */); + } %} ins_pipe(pipe_class_default); %} diff --git a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp index cc45d60f3295..baeff520d73e 100644 --- a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp +++ b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp @@ -945,7 +945,7 @@ void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, Mac } void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval, Register newval, Register addr, Register tmp1, Register tmp2) { - bool is_narrow = node->bottom_type()->isa_narrowoop(); + bool is_narrow = node->bottom_type()->is_narrowoop(); ShenandoahBarrierStubC2::load_store_pre(masm, node, addr, preval, tmp1, tmp2, is_narrow); diff --git a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp index 1bb1290ff252..85311e1702cc 100644 --- a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp @@ -118,12 +118,6 @@ class MacroAssembler: public Assembler { bool add_relocation = true, bool emit_dummy_addr = false) { calculate_address_from_global_toc(dst, target(addr), hi16, lo16, add_relocation, emit_dummy_addr, false); } - inline void calculate_address_from_global_toc_hi16only(Register dst, address addr) { - calculate_address_from_global_toc(dst, addr, true, false); - }; - inline void calculate_address_from_global_toc_lo16only(Register dst, address addr) { - calculate_address_from_global_toc(dst, addr, false, true); - }; inline static bool is_calculate_address_from_global_toc_at(address a, address bound); // Returns address of first instruction in sequence. diff --git a/src/hotspot/cpu/ppc/ppc.ad b/src/hotspot/cpu/ppc/ppc.ad index 6fc9aa0919a5..b14471333d73 100644 --- a/src/hotspot/cpu/ppc/ppc.ad +++ b/src/hotspot/cpu/ppc/ppc.ad @@ -1336,35 +1336,21 @@ int ConstantTable::calculate_table_base_offset() const { return 0; // absolute addressing, no offset } -bool MachConstantBaseNode::requires_postalloc_expand() const { return true; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - iRegLdstOper *op_dst = new iRegLdstOper(); - MachNode *m1 = new loadToc_hiNode(); - MachNode *m2 = new loadToc_loNode(); - - m1->add_req(nullptr); - m2->add_req(nullptr, m1); - m1->_opnds[0] = op_dst; - m2->_opnds[0] = op_dst; - m2->_opnds[1] = op_dst; - ra_->set_pair(m1->_idx, ra_->get_reg_second(this), ra_->get_reg_first(this)); - ra_->set_pair(m2->_idx, ra_->get_reg_second(this), ra_->get_reg_first(this)); - nodes->push(m1); - nodes->push(m2); -} - void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { - // Is postalloc expanded. - ShouldNotReachHere(); + Register dst = as_Register(ra_->get_encode(this)); + __ calculate_address_from_global_toc(dst, __ method_toc()); } uint MachConstantBaseNode::size(PhaseRegAlloc* ra_) const { - return 0; + return 8; } #ifndef PRODUCT void MachConstantBaseNode::format(PhaseRegAlloc* ra_, outputStream* st) const { - st->print("-- \t// MachConstantBaseNode (empty encoding)"); + char reg_str[128]; + ra_->dump_register(this, reg_str, sizeof(reg_str)); + st->print("ADDIS %s, R29, DISP.hi \t// MachConstantBaseNode: load TOC hi\n\t" + "ADDI %s, %s, DISP.lo \t// load TOC lo", reg_str, reg_str, reg_str); } #endif @@ -1696,7 +1682,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r if (src_lo == dst_lo && src_hi == dst_hi) return size; // Self copy, no move. - if (bottom_type()->isa_vect() != nullptr && ideal_reg() == Op_VecX) { + if (bottom_type()->is_vect() && ideal_reg() == Op_VecX) { int src_offset = ra_->reg2offset(src_lo); int dst_offset = ra_->reg2offset(dst_lo); DEBUG_ONLY(int algm = MIN2(RegMask::num_registers(ideal_reg()), (int)Matcher::stack_alignment_in_slots()) * VMRegImpl::stack_slot_size); @@ -2565,7 +2551,7 @@ loadConLNodesTuple loadConLNodesTuple_create(PhaseRegAlloc *ra_, Node *toc, immL nodes._large_lo = m2; nodes._small = nullptr; nodes._last = nodes._large_lo; - assert(m2->bottom_type()->isa_long(), "must be long"); + assert(m2->bottom_type()->is_long(), "must be long"); } else { loadConLNode *m2 = new loadConLNode(); @@ -2588,7 +2574,7 @@ loadConLNodesTuple loadConLNodesTuple_create(PhaseRegAlloc *ra_, Node *toc, immL nodes._large_lo = nullptr; nodes._small = m2; nodes._last = nodes._small; - assert(m2->bottom_type()->isa_long(), "must be long"); + assert(m2->bottom_type()->is_long(), "must be long"); } return nodes; @@ -2660,7 +2646,7 @@ loadConLReplicatedNodesTuple loadConLReplicatedNodesTuple_create(Compile *C, Pha nodes._replicated = m4; nodes._small = nullptr; nodes._last = nodes._replicated; - assert(m2->bottom_type()->isa_long(), "must be long"); + assert(m2->bottom_type()->is_long(), "must be long"); } else { loadConLNode *m2 = new loadConLNode(); mtvsrdNode *m3 = new mtvsrdNode(); @@ -2697,7 +2683,7 @@ loadConLReplicatedNodesTuple loadConLReplicatedNodesTuple_create(Compile *C, Pha nodes._moved = m3; nodes._replicated = m4; nodes._last = nodes._replicated; - assert(m2->bottom_type()->isa_long(), "must be long"); + assert(m2->bottom_type()->is_long(), "must be long"); } return nodes; @@ -2721,7 +2707,7 @@ encode %{ // some asserts assert(nodes->length() >= 1, "must have created at least 1 node"); - assert(loadConLNodes._last->bottom_type()->isa_long(), "must be long"); + assert(loadConLNodes._last->bottom_type()->is_long(), "must be long"); %} enc_class enc_load_long_constP(iRegLdst dst, immP src, iRegLdst toc) %{ @@ -2828,7 +2814,7 @@ encode %{ nodes->push(m1); nodes->push(m2); - assert(m2->bottom_type()->isa_ptr(), "must be ptr"); + assert(m2->bottom_type()->is_ptr(), "must be ptr"); } else { loadConPNode *m2 = new loadConPNode(); @@ -2844,7 +2830,7 @@ encode %{ ra_->set_pair(m2->_idx, ra_->get_reg_second(this), ra_->get_reg_first(this)); nodes->push(m2); - assert(m2->bottom_type()->isa_ptr(), "must be ptr"); + assert(m2->bottom_type()->is_ptr(), "must be ptr"); } %} @@ -3022,7 +3008,7 @@ encode %{ if (loadConLNodes._last) nodes->push(loadConLNodes._last); assert(nodes->length() >= 1, "must have created at least 1 node"); - assert(loadConLNodes._last->bottom_type()->isa_long(), "must be long"); + assert(loadConLNodes._last->bottom_type()->is_long(), "must be long"); %} enc_class postalloc_expand_load_replF_constant_vsx(vecX dst, immF src, iRegLdst toc, iRegLdst tmp) %{ @@ -5320,33 +5306,6 @@ instruct loadD_unaligned(regD dst, memory mem) %{ //----------Constants-------------------------------------------------------- -// Load MachConstantTableBase: add hi offset to global toc. -// TODO: Handle hidden register r29 in bundler! -instruct loadToc_hi(iRegLdst dst) %{ - effect(DEF dst); - ins_cost(DEFAULT_COST); - - format %{ "ADDIS $dst, R29, DISP.hi \t// load TOC hi" %} - size(4); - ins_encode %{ - __ calculate_address_from_global_toc_hi16only($dst$$Register, __ method_toc()); - %} - ins_pipe(pipe_class_default); -%} - -// Load MachConstantTableBase: add lo offset to global toc. -instruct loadToc_lo(iRegLdst dst, iRegLdst src) %{ - effect(DEF dst, USE src); - ins_cost(DEFAULT_COST); - - format %{ "ADDI $dst, $src, DISP.lo \t// load TOC lo" %} - size(4); - ins_encode %{ - __ calculate_address_from_global_toc_lo16only($dst$$Register, __ method_toc()); - %} - ins_pipe(pipe_class_default); -%} - // Load 16-bit integer constant 0xssss???? instruct loadConI16(iRegIdst dst, immI16 src) %{ match(Set dst src); @@ -6110,8 +6069,8 @@ instruct encodeP_narrow_oop_shift_0(iRegNdst dst, iRegPsrc src) %{ // shift != 0, base != 0 instruct decodeN(iRegPdst dst, iRegNsrc src, flagsRegCR0 cr0) %{ match(Set dst (DecodeN src)); - predicate((n->bottom_type()->is_oopptr()->ptr() != TypePtr::NotNull && - n->bottom_type()->is_oopptr()->ptr() != TypePtr::Constant) && + predicate((n->bottom_type()->as_oopptr()->ptr() != TypePtr::NotNull && + n->bottom_type()->as_oopptr()->ptr() != TypePtr::Constant) && CompressedOops::shift() != 0 && CompressedOops::base() != nullptr); ins_cost(4 * DEFAULT_COST); // Should be more expensive than decodeN_Disjoint_isel. @@ -6145,8 +6104,8 @@ instruct decodeN_nullBase(iRegPdst dst, iRegNsrc src) %{ instruct decodeN_Disjoint_notNull(iRegPdst dst, iRegNsrc src) %{ match(Set dst (DecodeN src)); effect(TEMP_DEF dst); - predicate((n->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_oopptr()->ptr() == TypePtr::Constant) && + predicate((n->bottom_type()->as_oopptr()->ptr() == TypePtr::NotNull || + n->bottom_type()->as_oopptr()->ptr() == TypePtr::Constant) && CompressedOops::base_disjoint()); ins_cost(DEFAULT_COST); @@ -6162,8 +6121,8 @@ instruct decodeN_Disjoint_notNull(iRegPdst dst, iRegNsrc src) %{ instruct decodeN_Disjoint_isel(iRegPdst dst, iRegNsrc src, flagsReg crx) %{ match(Set dst (DecodeN src)); effect(TEMP_DEF dst, TEMP crx); - predicate((n->bottom_type()->is_oopptr()->ptr() != TypePtr::NotNull && - n->bottom_type()->is_oopptr()->ptr() != TypePtr::Constant) && + predicate((n->bottom_type()->as_oopptr()->ptr() != TypePtr::NotNull && + n->bottom_type()->as_oopptr()->ptr() != TypePtr::Constant) && CompressedOops::base_disjoint()); ins_cost(3 * DEFAULT_COST); // Has a lower latency than decodeN because of a better ILP. @@ -6180,8 +6139,8 @@ instruct decodeN_Disjoint_isel(iRegPdst dst, iRegNsrc src, flagsReg crx) %{ // src != 0, shift != 0, base != 0 instruct decodeN_notNull_addBase(iRegPdst dst, iRegNsrc src) %{ match(Set dst (DecodeN src)); - predicate((n->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_oopptr()->ptr() == TypePtr::Constant) && + predicate((n->bottom_type()->as_oopptr()->ptr() == TypePtr::NotNull || + n->bottom_type()->as_oopptr()->ptr() == TypePtr::Constant) && CompressedOops::shift() != 0 && CompressedOops::base() != nullptr); ins_cost(2 * DEFAULT_COST); @@ -8080,7 +8039,7 @@ instruct lShiftL_regI_immGE32(iRegLdst dst, iRegIorL2I src1, uimmI6_ge32 src2) % // Shift amounts >= 32 are handled by lShiftL_regI_immGE32. instruct scaledPositiveI2L_lShiftL_convI2L_reg_imm6(iRegLdst dst, iRegIorL2I src1, uimmI5 src2) %{ match(Set dst (LShiftL (ConvI2L src1) src2)); - predicate(((ConvI2LNode*)(_kids[0]->_leaf))->type()->is_long()->is_positive_int()); + predicate(((ConvI2LNode*)(_kids[0]->_leaf))->type()->as_long()->is_positive_int()); format %{ "SLDI $dst, i2l(positive_int($src1)), $src2" %} size(4); @@ -10774,7 +10733,7 @@ instruct indexOf_imm1_char_U(iRegIdst result, iRegPsrc haystack, iRegIorL2I hayc ins_encode %{ immPOper *needleOper = (immPOper *)$needleImm; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr; #ifdef VM_LITTLE_ENDIAN @@ -10807,7 +10766,7 @@ instruct indexOf_imm1_char_L(iRegIdst result, iRegPsrc haystack, iRegIorL2I hayc ins_encode %{ immPOper *needleOper = (immPOper *)$needleImm; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, @@ -10833,7 +10792,7 @@ instruct indexOf_imm1_char_UL(iRegIdst result, iRegPsrc haystack, iRegIorL2I hay ins_encode %{ immPOper *needleOper = (immPOper *)$needleImm; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, @@ -10852,15 +10811,15 @@ instruct indexOf_imm1_U(iRegIdst result, iRegPsrc haystack, iRegIorL2I haycnt, effect(USE_KILL needle, TEMP tmp1, TEMP tmp2, KILL cr0, KILL cr1, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::UU && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(180); format %{ "String IndexOf SCL1 $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $needle, $tmp1, $tmp2, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); guarantee(needle_values, "sanity"); jchar chr; #ifdef VM_LITTLE_ENDIAN @@ -10886,15 +10845,15 @@ instruct indexOf_imm1_L(iRegIdst result, iRegPsrc haystack, iRegIorL2I haycnt, effect(USE_KILL needle, TEMP tmp1, TEMP tmp2, KILL cr0, KILL cr1, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::LL && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(180); format %{ "String IndexOf SCL1 $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $needle, $tmp1, $tmp2, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); guarantee(needle_values, "sanity"); jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, @@ -10913,15 +10872,15 @@ instruct indexOf_imm1_UL(iRegIdst result, iRegPsrc haystack, iRegIorL2I haycnt, effect(USE_KILL needle, TEMP tmp1, TEMP tmp2, KILL cr0, KILL cr1, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::UL && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(180); format %{ "String IndexOf SCL1 $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $needle, $tmp1, $tmp2, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); guarantee(needle_values, "sanity"); jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, @@ -10979,15 +10938,15 @@ instruct indexOf_imm_U(iRegIdst result, iRegPsrc haystack, rscratch1RegI haycnt, TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, TEMP tmp5, KILL cr0, KILL cr1, KILL cr6, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::UU && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(250); format %{ "String IndexOf SCL $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $tmp1, $tmp2, $tmp3, $tmp4, $tmp5, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); __ string_indexof($result$$Register, $haystack$$Register, $haycnt$$Register, @@ -11006,15 +10965,15 @@ instruct indexOf_imm_L(iRegIdst result, iRegPsrc haystack, rscratch1RegI haycnt, TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, TEMP tmp5, KILL cr0, KILL cr1, KILL cr6, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::LL && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(250); format %{ "String IndexOf SCL $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $tmp1, $tmp2, $tmp3, $tmp4, $tmp5, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); __ string_indexof($result$$Register, $haystack$$Register, $haycnt$$Register, @@ -11033,15 +10992,15 @@ instruct indexOf_imm_UL(iRegIdst result, iRegPsrc haystack, rscratch1RegI haycnt TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, TEMP tmp5, KILL cr0, KILL cr1, KILL cr6, KILL ctr); // Required for EA: check if it is still a type_array. predicate(((StrIndexOfNode*)n)->encoding() == StrIntrinsicNode::UL && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop() && - n->in(3)->in(1)->bottom_type()->is_aryptr()->const_oop()->is_type_array()); + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop() && + n->in(3)->in(1)->bottom_type()->as_aryptr()->const_oop()->is_type_array()); ins_cost(250); format %{ "String IndexOf SCL $haystack[0..$haycnt], $needle[0..$needlecntImm]" " -> $result \t// KILL $haycnt, $tmp1, $tmp2, $tmp3, $tmp4, $tmp5, $cr0, $cr1" %} ins_encode %{ Node *ndl = in(operand_index($needle)); // The node that defines needle. - ciTypeArray* needle_values = ndl->bottom_type()->is_aryptr()->const_oop()->as_type_array(); + ciTypeArray* needle_values = ndl->bottom_type()->as_aryptr()->const_oop()->as_type_array(); __ string_indexof($result$$Register, $haystack$$Register, $haycnt$$Register, diff --git a/src/hotspot/cpu/riscv/c1_CodeStubs_riscv.cpp b/src/hotspot/cpu/riscv/c1_CodeStubs_riscv.cpp index 9b877ba31e4f..0faf47d00d50 100644 --- a/src/hotspot/cpu/riscv/c1_CodeStubs_riscv.cpp +++ b/src/hotspot/cpu/riscv/c1_CodeStubs_riscv.cpp @@ -395,7 +395,7 @@ void ArrayCopyStub::emit_code(LIR_Assembler* ce) { relocInfo::static_call_type); address call = __ reloc_call(resolve); if (call == nullptr) { - ce->bailout("reloc call address stub overflow"); + ce->bailout("address stub overflow"); return; } ce->add_call_info_here(info()); diff --git a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp index c0674051b15d..ffb3394b3bb6 100644 --- a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp @@ -1483,7 +1483,7 @@ void LIR_Assembler::call(LIR_OpJavaCall* op, relocInfo::relocType rtype) { Assembler::IncompressibleScope scope(_masm); address call = __ reloc_call(Address(op->addr(), rtype)); if (call == nullptr) { - bailout("reloc call address stub overflow"); + bailout("address stub overflow"); return; } add_call_info(code_offset(), op->info(), op->maybe_return_as_fields()); @@ -1494,7 +1494,7 @@ void LIR_Assembler::ic_call(LIR_OpJavaCall* op) { Assembler::IncompressibleScope scope(_masm); address call = __ ic_call(op->addr()); if (call == nullptr) { - bailout("reloc call address stub overflow"); + bailout("address stub overflow"); return; } add_call_info(code_offset(), op->info(), op->maybe_return_as_fields()); @@ -1515,7 +1515,7 @@ void LIR_Assembler::emit_static_call_stub() { __ relocate(static_stub_Relocation::spec(call_pc)); __ emit_static_call_stub(); - assert(__ offset() - start + CompiledDirectCall::to_trampoline_stub_size() + assert(__ offset() - start + MacroAssembler::max_address_stub_size() <= call_stub_size(), "stub too big"); __ end_a_stub(); } diff --git a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.hpp b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.hpp index b952800b4bae..f2c4ab625d1e 100644 --- a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.hpp @@ -78,7 +78,7 @@ friend class ArrayCopyStub; enum { // call stub: CompiledDirectCall::to_interp_stub_size() + - // CompiledDirectCall::to_trampoline_stub_size() + // MacroAssembler::max_address_stub_size() _call_stub_size = 11 * MacroAssembler::instruction_size + 1 * MacroAssembler::instruction_size + wordSize, // See emit_exception_handler for detail diff --git a/src/hotspot/cpu/riscv/compiledIC_riscv.cpp b/src/hotspot/cpu/riscv/compiledIC_riscv.cpp index a86e65ab5808..aae31f3887ae 100644 --- a/src/hotspot/cpu/riscv/compiledIC_riscv.cpp +++ b/src/hotspot/cpu/riscv/compiledIC_riscv.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2018, Red Hat Inc. All rights reserved. * Copyright (c) 2020, 2021, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -68,9 +68,8 @@ int CompiledDirectCall::to_interp_stub_size() { } int CompiledDirectCall::to_trampoline_stub_size() { - // We count size of target address and an additional alignment nop. - // Reloc call address stubs are always word aligned. - return MacroAssembler::max_reloc_call_address_stub_size(); + // RISC-V doesn't use trampolines. + return 0; } // Relocation entries for call stub, compiled java to interpreter. diff --git a/src/hotspot/cpu/riscv/gc/g1/g1_riscv.ad b/src/hotspot/cpu/riscv/gc/g1/g1_riscv.ad index 9242d0f11bb2..a324fb771186 100644 --- a/src/hotspot/cpu/riscv/gc/g1/g1_riscv.ad +++ b/src/hotspot/cpu/riscv/gc/g1/g1_riscv.ad @@ -74,20 +74,15 @@ static void write_barrier_post(MacroAssembler* masm, %} - -// TODO 8350865 (same applies to g1StoreLSpecialTwoOops) -// - Do not set/overwrite barrier data here, also handle G1C2BarrierPostNotNull - instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI_0 off, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem (Binary src off))); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr); ins_cost(STORE_COST); format %{ "sd $src, $mem\t# g1StoreLSpecialOneOopOff0" %} ins_encode %{ guarantee($mem$$disp == 0, "impossible encoding"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); write_barrier_pre(masm, this, $mem$$Register /* obj */, @@ -99,8 +94,14 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI_0 off, iReg __ sd($src$$Register, Address($mem$$Register)); // Extract the narrow oop field value - __ zext($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ zext($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -112,17 +113,18 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegLNoSp src, immI_0 off, iReg instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, iRegPNoSp tmp4, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem (Binary src off))); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, KILL cr); ins_cost(STORE_COST); format %{ "sd $src, $mem\t# g1StoreLSpecialOneOopOff4" %} ins_encode %{ guarantee($mem$$disp == 0, "impossible encoding"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); // Adjust address to point to narrow oop - __ add($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & (G1C2BarrierPre | G1C2BarrierPost)) != 0) { + __ add($tmp4$$Register, $mem$$Register, 4); + } write_barrier_pre(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -133,8 +135,14 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iReg __ sd($src$$Register, Address($mem$$Register)); // Shift long value to extract the narrow oop field value and zero-extend it - __ srli($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ srli($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $tmp4$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -146,14 +154,13 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegLNoSp src, immI_4 off, iReg instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRegPNoSp tmp2, iRegPNoSp tmp3, iRegPNoSp tmp4, rFlagsReg cr) %{ - predicate(UseG1GC); + predicate(UseG1GC && !needs_releasing_store(n)); match(Set mem (StoreLSpecial mem src)); effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, TEMP tmp4, KILL cr); ins_cost(STORE_COST); format %{ "sd $src, $mem\t# g1StoreLSpecialTwoOops" %} ins_encode %{ guarantee($mem$$disp == 0, "impossible encoding"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); write_barrier_pre(masm, this, $mem$$Register /* obj */, @@ -162,7 +169,9 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe $tmp3$$Register /* tmp2 */, RegSet::of($mem$$Register, $src$$Register) /* preserve */); // Adjust address to point to the second narrow oop in the long value - __ add($tmp4$$Register, $mem$$Register, 4); + if ((barrier_data() & (G1C2BarrierPre | G1C2BarrierPost)) != 0) { + __ add($tmp4$$Register, $mem$$Register, 4); + } write_barrier_pre(masm, this, $tmp4$$Register /* obj */, $tmp1$$Register /* pre_val */, @@ -173,8 +182,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe __ sd($src$$Register, Address($mem$$Register)); // Zero-extend first narrow oop to long - __ zext($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ zext($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -182,8 +197,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegLNoSp src, iRegPNoSp tmp1, iRe $tmp3$$Register /* tmp2 */); // Shift long value to extract the second narrow oop field value - __ srli($tmp1$$Register, $src$$Register, 32); - __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ srli($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp1$$Register, $tmp1$$Register); + } else { + __ decode_heap_oop_not_null($tmp1$$Register, $tmp1$$Register); + } + } write_barrier_post(masm, this, $tmp4$$Register /* store_addr */, $tmp1$$Register /* new_val */, diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp index 40489bd32cb8..329e0c3d3b20 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp @@ -716,7 +716,7 @@ void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, Mac void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval, Register newval, Register addr, Register tmp1, Register tmp2, Register tmp3, bool is_acquire) { - const bool is_narrow = node->bottom_type()->isa_narrowoop(); + const bool is_narrow = node->bottom_type()->is_narrowoop(); ShenandoahBarrierStubC2::load_store_pre(masm, node, Address(addr, 0), tmp1, tmp2, tmp3, is_narrow); diff --git a/src/hotspot/cpu/riscv/globals_riscv.hpp b/src/hotspot/cpu/riscv/globals_riscv.hpp index 96442eff8835..cc6dc276ec4f 100644 --- a/src/hotspot/cpu/riscv/globals_riscv.hpp +++ b/src/hotspot/cpu/riscv/globals_riscv.hpp @@ -95,9 +95,9 @@ define_pd_global(bool, ValueTypeReturnedAsFields, false); "Extend i for r and o for w in the pred/succ flags of fence") \ product(bool, AvoidUnalignedAccesses, true, \ "Avoid generating unaligned memory accesses") \ - product(bool, UseRVA20U64, true, "Use RVA20U64 profile") \ - product(bool, UseRVA22U64, false, EXPERIMENTAL, "Use RVA22U64 profile") \ - product(bool, UseRVA23U64, false, EXPERIMENTAL, "Use RVA23U64 profile") \ + product(bool, UseRVA20U64, false, DIAGNOSTIC, "Use RVA20U64 profile") \ + product(bool, UseRVA22U64, false, DIAGNOSTIC, "Use RVA22U64 profile") \ + product(bool, UseRVA23U64, false, DIAGNOSTIC, "Use RVA23U64 profile") \ product(bool, UseRVC, false, DIAGNOSTIC, "Use RVC instructions") \ product(bool, UseRVV, false, DIAGNOSTIC, "Use RVV instructions") \ product(bool, UseZba, false, DIAGNOSTIC, "Use Zba instructions") \ diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp index a939102ba13b..7044eb64f061 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp @@ -5864,7 +5864,7 @@ address MacroAssembler::reloc_call(Address entry, Register tmp) { address target = entry.target(); if (!in_scratch_emit_size()) { - address stub = emit_reloc_call_address_stub(offset(), target); + address stub = emit_address_stub(offset(), target); if (stub == nullptr) { postcond(pc() == badAddress); return nullptr; // CodeCache is full @@ -5878,8 +5878,7 @@ address MacroAssembler::reloc_call(Address entry, Register tmp) { } #endif - // The relocation created while emitting the stub will ensure this - // call instruction is subsequently patched to call the stub. + // Relocation patches the auipc/ld pair to load the destination from the address stub. relocate(entry.rspec(), [&] { auipc(tmp, 0); ld(tmp, Address(tmp, 0)); @@ -5940,8 +5939,7 @@ int MacroAssembler::ic_check(int end_alignment) { return uep_offset; } -// Emit an address stub for a call to a target which is too far away. -// Note that we only put the target address of the call in the stub. +// Emit an address-only stub holding the destination of a relocatable call. // // code sequences: // @@ -5953,8 +5951,8 @@ int MacroAssembler::ic_check(int end_alignment) { // alignment nop // target address -address MacroAssembler::emit_reloc_call_address_stub(int insts_call_instruction_offset, address dest) { - address stub = start_a_stub(max_reloc_call_address_stub_size()); +address MacroAssembler::emit_address_stub(int insts_call_instruction_offset, address dest) { + address stub = start_a_stub(max_address_stub_size()); if (stub == nullptr) { return nullptr; // CodeBuffer::expand failed } @@ -5981,7 +5979,7 @@ address MacroAssembler::emit_reloc_call_address_stub(int insts_call_instruction_ return stub_start_addr; } -int MacroAssembler::max_reloc_call_address_stub_size() { +int MacroAssembler::max_address_stub_size() { // Max stub size: alignment nop, target address. return 1 * MacroAssembler::instruction_size + wordSize; } diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp index 62267fe51676..78ca6f21664d 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp @@ -525,8 +525,8 @@ class MacroAssembler: public Assembler { return false; } - address emit_reloc_call_address_stub(int insts_call_instruction_offset, address target); - static int max_reloc_call_address_stub_size(); + address emit_address_stub(int insts_call_instruction_offset, address target); + static int max_address_stub_size(); void emit_static_call_stub(); static int static_call_stub_size(); @@ -1402,8 +1402,8 @@ INSN(sd_release, sd, sd_rl); // address stub: // <64-bit destination address> // - // To change the destination we simply atomically store the new - // address in the stub section. + // Retargeting atomically updates the address slot and may replace the final + // jalr with jal, or vice versa, via optimize_call(). // There is a benign race in that the other thread might observe the old // 64-bit destination address before it observes the new address. That does // not matter because the destination method has been invalidated, so there @@ -1754,9 +1754,8 @@ INSN(sd_release, sd, sd_rl); int* receiver_offset); #ifdef ASSERT - // Template short-hand support to clean-up after a failed call to trampoline - // call generation (see trampoline_call() below), when a set of Labels must - // be reset (before returning). + // Reset labels that would otherwise remain unbound when returning + // after a failed reloc_call(). template void reset_labels(Label& lbl, More&... more) { lbl.reset(); reset_labels(more...); diff --git a/src/hotspot/cpu/riscv/nativeInst_riscv.cpp b/src/hotspot/cpu/riscv/nativeInst_riscv.cpp index bbfa11144cbd..a81f12ca0727 100644 --- a/src/hotspot/cpu/riscv/nativeInst_riscv.cpp +++ b/src/hotspot/cpu/riscv/nativeInst_riscv.cpp @@ -144,9 +144,8 @@ address NativeCall::stub_address_destination_at(address src) { return dest; } -// Returns the address stub of this reloc call, or nullptr if the call does not -// have an address stub yet, which is the case while code is being emitted into -// a CodeBuffer. +// Return the call's address stub, or nullptr if the call is still unlinked +// and no nmethod relocations are available to locate the stub. address NativeCall::stub_address() const { address call_addr = instruction_address(); assert(NativeCall::is_at(call_addr), "unexpected code at call site"); @@ -167,8 +166,7 @@ address NativeCall::stub_address() const { // relocation info. See Relocation::pd_set_call_destination. CodeBlob *code = CodeCache::find_blob(call_addr); if (code == nullptr || !code->is_nmethod()) { - // Code is still living in a CodeBuffer, there is no relocation info to - // search and nothing to patch yet. + // An unlinked call's stub cannot be found without nmethod relocations. return nullptr; } diff --git a/src/hotspot/cpu/riscv/relocInfo_riscv.cpp b/src/hotspot/cpu/riscv/relocInfo_riscv.cpp index 2c6ed1f9a413..9cfec70e9935 100644 --- a/src/hotspot/cpu/riscv/relocInfo_riscv.cpp +++ b/src/hotspot/cpu/riscv/relocInfo_riscv.cpp @@ -98,8 +98,8 @@ address Relocation::pd_call_destination(address orig_addr) { void Relocation::pd_set_call_destination(address x) { assert(is_call(), "should be a call here"); if (NativeCall::is_at(addr())) { - // Nothing to do while code is still living in a CodeBuffer, where the call - // does not have an address stub yet. See NativeCall::stub_address(). + // An unlinked CodeBuffer call's address stub cannot be found without + // nmethod relocation information. See NativeCall::stub_address(). if (x != nullptr) { NativeCall* call = nativeCall_at(addr()); call->set_destination(x); diff --git a/src/hotspot/cpu/riscv/riscv.ad b/src/hotspot/cpu/riscv/riscv.ad index d2ea2447089b..e0bc84775c62 100644 --- a/src/hotspot/cpu/riscv/riscv.ad +++ b/src/hotspot/cpu/riscv/riscv.ad @@ -1034,7 +1034,7 @@ class CallStubImpl { // This doesn't need to be accurate to the byte, but it // must be larger than or equal to the real size of the stub. static uint size_call_stub() { - return MacroAssembler::max_reloc_call_address_stub_size(); + return MacroAssembler::max_address_stub_size(); } // Number of relocations needed by a call stub. @@ -1454,11 +1454,6 @@ int ConstantTable::calculate_table_base_offset() const { return 0; // absolute addressing, no offset } -bool MachConstantBaseNode::requires_postalloc_expand() const { return false; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - ShouldNotReachHere(); -} - void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { // Empty encoding } @@ -1648,7 +1643,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r assert(src_lo != OptoReg::Bad && dst_lo != OptoReg::Bad, "must move at least 1 register"); - if (src_hi != OptoReg::Bad && !bottom_type()->isa_pvectmask()) { + if (src_hi != OptoReg::Bad && !bottom_type()->is_pvectmask()) { assert((src_lo & 1) == 0 && src_lo + 1 == src_hi && (dst_lo & 1) == 0 && dst_lo + 1 == dst_hi, "expected aligned-adjacent pairs"); @@ -1667,8 +1662,8 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r // address also needs t0 to materialize an offset outside the 12-bit range. if (src_lo_rc == rc_stack && dst_lo_rc == rc_stack) { int last_dst_offset = dst_offset; - if (bottom_type()->isa_vect() != nullptr) { - if (!bottom_type()->isa_pvectmask()) { + if (bottom_type()->is_vect()) { + if (!bottom_type()->is_pvectmask()) { assert(ideal_reg() == Op_VecA, "Must be Op_VecA"); int vector_reg_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE); last_dst_offset += vector_reg_size_in_bytes - 8; @@ -1688,8 +1683,8 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r } } - if (bottom_type()->isa_vect() != nullptr && masm != nullptr) { - if (!bottom_type()->isa_pvectmask()) { + if (bottom_type()->is_vect() && masm != nullptr) { + if (!bottom_type()->is_pvectmask()) { assert(ideal_reg() == Op_VecA, "Must be Op_VecA"); int vector_reg_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE); if (src_lo_rc == rc_stack && dst_lo_rc == rc_stack) { @@ -1812,11 +1807,11 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r } else { st->print("%s", Matcher::regName[dst_lo]); } - if (bottom_type()->isa_vect() && !bottom_type()->isa_pvectmask()) { + if (bottom_type()->is_vect() && !bottom_type()->is_pvectmask()) { assert(ideal_reg() == Op_VecA, "Must be Op_VecA"); int vsize = Matcher::scalable_vector_reg_size(T_BYTE) * 8; st->print("\t# vector spill size = %d", vsize); - } else if (bottom_type()->isa_pvectmask()) { + } else if (bottom_type()->is_pvectmask()) { assert(ideal_reg() == Op_RegVectMask, "Must be Op_RegVectMask"); assert(Matcher::supports_scalable_vector(), "bad register type for spill"); int vsize = Matcher::scalable_predicate_reg_slots() * 32; @@ -2229,10 +2224,10 @@ bool size_fits_all_mem_uses(AddPNode* addp, int shift) { assert_cond(addp != nullptr); for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) { Node* u = addp->fast_out(i); - if (u != nullptr && u->is_Mem()) { - int opsize = u->as_Mem()->memory_size(); + if (MemNode* u_mem = Node::isa(u); u_mem != nullptr) { + int opsize = u_mem->memory_size(); assert(opsize > 0, "unexpected memory operand size"); - if (u->as_Mem()->memory_size() != (1 << shift)) { + if (u_mem->memory_size() != (1 << shift)) { return false; } } @@ -2242,11 +2237,7 @@ bool size_fits_all_mem_uses(AddPNode* addp, int shift) { // Binary src (Replicate scalar/immediate) static bool is_vector_scalar_binary_pattern(Node* n, Node* m) { - if (n == nullptr || m == nullptr) { - return false; - } - - if (m->Opcode() != Op_Replicate) { + if (n == nullptr || !Node::is_exact(m)) { return false; } @@ -2276,11 +2267,8 @@ static bool is_vector_scalar_binary_pattern(Node* n, Node* m) { // (XorV src (Replicate m1)) // (XorVMask src (MaskAll m1)) static bool is_vector_bitwise_not_pattern(Node* n, Node* m) { - if (n != nullptr && m != nullptr) { - return (n->Opcode() == Op_XorV || n->Opcode() == Op_XorVMask) && - VectorNode::is_all_ones_vector(m); - } - return false; + return (Node::is_exact(n) || Node::is_exact(n)) && + m != nullptr && VectorNode::is_all_ones_vector(m); } // 'n' is the current user of input 'm', which is being considered for cloning. @@ -9612,8 +9600,8 @@ instruct encodeHeapOop_not_null(iRegNNoSp dst, iRegP src) %{ %} instruct decodeHeapOop(iRegPNoSp dst, iRegN src) %{ - predicate(n->bottom_type()->is_ptr()->ptr() != TypePtr::NotNull && - n->bottom_type()->is_ptr()->ptr() != TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() != TypePtr::NotNull && + n->bottom_type()->as_ptr()->ptr() != TypePtr::Constant); match(Set dst (DecodeN src)); ins_cost(ALU_COST); @@ -9627,8 +9615,8 @@ instruct decodeHeapOop(iRegPNoSp dst, iRegN src) %{ %} instruct decodeHeapOop_not_null(iRegPNoSp dst, iRegN src) %{ - predicate(n->bottom_type()->is_ptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_ptr()->ptr() == TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() == TypePtr::NotNull || + n->bottom_type()->as_ptr()->ptr() == TypePtr::Constant); match(Set dst (DecodeN src)); ins_cost(ALU_COST); diff --git a/src/hotspot/cpu/riscv/riscv_v.ad b/src/hotspot/cpu/riscv/riscv_v.ad index 8cfea2af528a..b576053239d4 100644 --- a/src/hotspot/cpu/riscv/riscv_v.ad +++ b/src/hotspot/cpu/riscv/riscv_v.ad @@ -272,7 +272,7 @@ source %{ bool Matcher::mask_op_prefers_predicate(int opcode, const TypeVect* vt) { // Prefer predicate if the mask type is "TypePVectMask". - return vt->isa_pvectmask() != nullptr; + return vt->is_pvectmask(); } %} diff --git a/src/hotspot/cpu/riscv/vm_version_riscv.cpp b/src/hotspot/cpu/riscv/vm_version_riscv.cpp index d5ad325c4608..5b5d26542709 100644 --- a/src/hotspot/cpu/riscv/vm_version_riscv.cpp +++ b/src/hotspot/cpu/riscv/vm_version_riscv.cpp @@ -25,6 +25,7 @@ */ #include "classfile/vmIntrinsics.hpp" +#include "runtime/flags/jvmFlagAccess.hpp" #include "runtime/java.hpp" #include "runtime/os.inline.hpp" #include "runtime/vm_version.hpp" @@ -55,29 +56,102 @@ uint32_t VM_Version::_initial_vector_length = 0; VM_Version::AtomicAccessMode VM_Version::_atomic_access_mode = AtomicAccessMode::RVWMO; VM_Version::AtomicCasMode VM_Version::_atomic_cas_mode = AtomicCasMode::BASELINE; -#define DEF_RV_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ -VM_Version::ext_##PRETTY##RVExtFeatureValue VM_Version::ext_##PRETTY; +#define DEF_RV_EXT_DEPENDENCIES(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) \ +VM_Version::RVExtFeatureValue* const VM_Version::_ext_##PRETTY##_dependencies[] = { __VA_ARGS__ }; +RV_EXT_FEATURE_FLAGS(DEF_RV_EXT_DEPENDENCIES) +#undef DEF_RV_EXT_DEPENDENCIES + +#define DEF_RV_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) \ +VM_Version::RVExtFeatureValue VM_Version::ext_##PRETTY( \ + #PRETTY, LINUX_BIT, RVExtFeatureSet::CPU_##ext_##PRETTY, FSTRING, FLAG, _ext_##PRETTY##_dependencies); RV_EXT_FEATURE_FLAGS(DEF_RV_EXT_FEATURE) #undef DEF_RV_EXT_FEATURE -#define DEF_RV_NON_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ -VM_Version::PRETTY##RVNonExtFeatureValue VM_Version::PRETTY; +#define DEF_RV_NON_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING) \ +VM_Version::RVNonExtFeatureValue VM_Version::PRETTY(#PRETTY, LINUX_BIT, FSTRING); RV_NON_EXT_FEATURE_FLAGS(DEF_RV_NON_EXT_FEATURE) #undef DEF_RV_NON_EXT_FEATURE -#define ADD_RV_EXT_FEATURE_IN_LIST(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ - &VM_Version::ext_##PRETTY, -#define ADD_RV_NON_EXT_FEATURE_IN_LIST(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ - &VM_Version::PRETTY, - VM_Version::RVFeatureValue* VM_Version::_feature_list[] = { - RV_EXT_FEATURE_FLAGS(ADD_RV_EXT_FEATURE_IN_LIST) - RV_NON_EXT_FEATURE_FLAGS(ADD_RV_NON_EXT_FEATURE_IN_LIST) - nullptr}; +#define ADD_RV_EXT_FEATURE_IN_LIST(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) \ + &VM_Version::ext_##PRETTY, +#define ADD_RV_NON_EXT_FEATURE_IN_LIST(PRETTY, LINUX_BIT, FSTRING) \ + &VM_Version::PRETTY, +VM_Version::RVFeatureValue* const VM_Version::_feature_list[] = { + RV_EXT_FEATURE_FLAGS(ADD_RV_EXT_FEATURE_IN_LIST) + RV_NON_EXT_FEATURE_FLAGS(ADD_RV_NON_EXT_FEATURE_IN_LIST) + nullptr +}; +VM_Version::RVExtFeatureValue* const VM_Version::_ext_feature_list[] = { + RV_EXT_FEATURE_FLAGS(ADD_RV_EXT_FEATURE_IN_LIST) +}; #undef ADD_RV_NON_EXT_FEATURE_IN_LIST #undef ADD_RV_EXT_FEATURE_IN_LIST -VM_Version::RVExtFeatures* VM_Version::_rv_ext_features = new VM_Version::RVExtFeatures(); -VM_Version::RVExtFeatures VM_Version::_rv_ext_features_disabled_by_aot_cache; +VM_Version::RVExtFeatureSet VM_Version::_rv_ext_features; +VM_Version::RVExtFeatureSet VM_Version::_rv_ext_features_disabled_by_aot_cache; + +void VM_Version::RVExtFeatureValue::update_flag() { + if (_flag == INVALID_JVMFlagsEnum) { + return; + } + + JVMFlag* flag = JVMFlag::flag_from_enum(_flag); + if (!feature_enabled()) { + bool value = false; + JVMFlag::Error result = JVMFlagAccess::set_bool(flag, &value, JVMFlagOrigin::ERGONOMIC); + guarantee(result == JVMFlag::SUCCESS, "Could not disable unsupported extension flag"); + return; + } + + DEBUG_ONLY(verify_deps()); + if (!flag->is_default() && !flag->get_bool()) { + disable_feature(); + return; + } + + // Direct writes preserve the flag origin, matching FLAG_SET_DEFAULT. + if (deps_all_enabled()) { + if (flag->is_default()) { + flag->write(true); + } + return; + } + + flag->write(false); + disable_feature(); + stringStream ss; + ss.print("missing dependent extension(s): "); + deps_string(ss); + log_disabled(ss.as_string(true)); +} + +bool VM_Version::RVExtFeatureValue::deps_all_enabled() const { + for (RVExtFeatureValue* const* dep = _dependencies; *dep != nullptr; ++dep) { + if (!(*dep)->feature_enabled()) { + return false; + } + } + return true; +} + +void VM_Version::RVExtFeatureValue::deps_string(stringStream& ss) const { + const char* sep = ""; + for (RVExtFeatureValue* const* dep = _dependencies; *dep != nullptr; ++dep) { + ss.print("%s%s (%s)", sep, (*dep)->pretty(), (*dep)->feature_enabled() ? "enabled" : "disabled"); + sep = ", "; + } +} + +#ifdef ASSERT +void VM_Version::RVExtFeatureValue::verify_deps() const { + for (RVExtFeatureValue* const* dep = _dependencies; *dep != nullptr; ++dep) { + assert(cpu_feature_index() >= 0, "must"); + assert((*dep)->cpu_feature_index() >= 0, "must"); + // Dependencies must precede their users so flag updates can run in one pass. + assert(cpu_feature_index() > (*dep)->cpu_feature_index(), "Invalid"); + } +} +#endif // ASSERT void VM_Version::useRVA20U64Profile() { RV_USE_RVA20U64; @@ -92,6 +166,7 @@ void VM_Version::useRVA23U64Profile() { } void VM_Version::initialize() { + static_assert(ARRAY_SIZE(_ext_feature_list) == RVExtFeatureSet::CPU_FEATURE_COUNT); common_initialize(); #ifdef COMPILER2 c2_initialize(); @@ -142,7 +217,7 @@ void VM_Version::common_initialize() { FLAG_SET_DEFAULT(UseSignumIntrinsic, true); } - if (UseRVC && !ext_c.enabled()) { + if (UseRVC && !ext_c.feature_enabled()) { warning("RVC is not supported on this CPU"); FLAG_SET_DEFAULT(UseRVC, false); @@ -553,23 +628,23 @@ bool VM_Version::is_intrinsic_supported(vmIntrinsicID id) { } int VM_Version::cpu_features_size() { - return sizeof(RVExtFeatures); + return sizeof(RVExtFeatureSet); } void VM_Version::store_cpu_features(void* buf) { assert(is_aligned(buf, cpu_features_alignment()), "sanity check"); - memcpy(buf, RVExtFeatures::current(), sizeof(RVExtFeatures)); + memcpy(buf, RVExtFeatureSet::current(), sizeof(RVExtFeatureSet)); } void VM_Version::get_cpu_features_disabled_by_aot_cache(void* buf) { assert(is_aligned(buf, cpu_features_alignment()), "sanity check"); - memcpy(buf, &_rv_ext_features_disabled_by_aot_cache, sizeof(RVExtFeatures)); + memcpy(buf, &_rv_ext_features_disabled_by_aot_cache, sizeof(RVExtFeatureSet)); } bool VM_Version::verify_aot_code_cache_features(void* features_buffer) { assert(is_aligned(features_buffer, cpu_features_alignment()), "sanity check"); - RVExtFeatures* features_to_test = (RVExtFeatures*)features_buffer; - return RVExtFeatures::current()->verify_aot_code_cache_features(features_to_test); + RVExtFeatureSet* features_to_test = (RVExtFeatureSet*)features_buffer; + return RVExtFeatureSet::current()->verify_aot_code_cache_features(features_to_test); } // Print one feature using the same spelling as features_string(): single letter @@ -585,10 +660,10 @@ void VM_Version::print_feature_name(stringStream& ss, RVFeatureValue* feature) { } } -void VM_Version::insert_features_names(RVExtFeatures* features, stringStream& ss) { +void VM_Version::insert_features_names(RVExtFeatureSet* features, stringStream& ss) { const char* sep = ""; int i = 0; - while (i < RVExtFeatures::MAX_CPU_FEATURE_INDEX) { + while (i < RVExtFeatureSet::CPU_FEATURE_COUNT) { if (features->support_feature(i)) { ss.print("%s", sep); print_feature_name(ss, _feature_list[i]); @@ -600,18 +675,18 @@ void VM_Version::insert_features_names(RVExtFeatures* features, stringStream& ss void VM_Version::get_cpu_features_name(void* features_buffer, stringStream& ss) { assert(is_aligned(features_buffer, cpu_features_alignment()), "sanity check"); - RVExtFeatures* features = (RVExtFeatures*)features_buffer; + RVExtFeatureSet* features = (RVExtFeatureSet*)features_buffer; insert_features_names(features, ss); } void VM_Version::get_missing_features_name(void* features_set1, void* features_set2, stringStream& ss) { assert(is_aligned(features_set1, cpu_features_alignment()), "sanity check"); assert(is_aligned(features_set2, cpu_features_alignment()), "sanity check"); - RVExtFeatures* rv_ext_features_set1 = (RVExtFeatures*)features_set1; - RVExtFeatures* rv_ext_features_set2 = (RVExtFeatures*)features_set2; + RVExtFeatureSet* rv_ext_features_set1 = (RVExtFeatureSet*)features_set1; + RVExtFeatureSet* rv_ext_features_set2 = (RVExtFeatureSet*)features_set2; const char* sep = ""; int i = 0; - while (i < RVExtFeatures::MAX_CPU_FEATURE_INDEX) { + while (i < RVExtFeatureSet::CPU_FEATURE_COUNT) { if (rv_ext_features_set1->support_feature(i) && !rv_ext_features_set2->support_feature(i)) { ss.print("%s", sep); print_feature_name(ss, _feature_list[i]); diff --git a/src/hotspot/cpu/riscv/vm_version_riscv.hpp b/src/hotspot/cpu/riscv/vm_version_riscv.hpp index c7463d3fd76a..c8a1dd1783e9 100644 --- a/src/hotspot/cpu/riscv/vm_version_riscv.hpp +++ b/src/hotspot/cpu/riscv/vm_version_riscv.hpp @@ -32,7 +32,6 @@ #include "runtime/arguments.hpp" #include "runtime/globals_extension.hpp" #include "utilities/globalDefinitions.hpp" -#include "utilities/ostream.hpp" #include "utilities/sizes.hpp" class RiscvHwprobe; @@ -68,7 +67,7 @@ class VM_Version : public Abstract_VM_Version { C950_MARCHID = 0x8000000009241600ULL, }; - class RVExtFeatures; + class RVExtFeatureSet; class RVFeatureValue { const char* const _pretty; @@ -84,140 +83,43 @@ class VM_Version : public Abstract_VM_Version { const char* pretty() { return _pretty; } uint64_t feature_bit() { return _linux_feature_bit; } bool feature_string() { return _feature_string; } - virtual bool enabled() = 0; - virtual void update_flag() = 0; + virtual bool feature_enabled() = 0; virtual void log_enabled() = 0; }; - #define UPDATE_DEFAULT(flag) \ - void update_flag() { \ - if (!enabled()) { \ - FLAG_SET_ERGO(flag, false); \ - return; \ - } \ - if (FLAG_IS_DEFAULT(flag)) { \ - FLAG_SET_DEFAULT(flag, true); \ - } else { \ - /* Sync CPU features with flags */ \ - if (!flag) { \ - disable_feature(); \ - } \ - } \ - } \ - - #define UPDATE_DEFAULT_DEP(flag, dep0, ...) \ - void update_flag() { \ - if (!enabled()) { \ - FLAG_SET_ERGO(flag, false); \ - return; \ - } \ - DEBUG_ONLY(verify_deps(dep0, ##__VA_ARGS__)); \ - if (FLAG_IS_DEFAULT(flag)) { \ - if (deps_all_enabled(dep0, ##__VA_ARGS__)) { \ - FLAG_SET_DEFAULT(flag, true); \ - } else { \ - FLAG_SET_DEFAULT(flag, false); \ - /* Sync CPU features with flags */ \ - disable_feature(); \ - stringStream ss; \ - ss.print("missing dependent extension(s): "); \ - deps_string(ss, dep0, ##__VA_ARGS__); \ - log_disabled(ss.as_string(true)); \ - } \ - } else { \ - /* Sync CPU features with flags */ \ - if (!flag) { \ - disable_feature(); \ - } else if (!deps_all_enabled(dep0, ##__VA_ARGS__)) { \ - FLAG_SET_DEFAULT(flag, false); \ - /* Sync CPU features with flags */ \ - disable_feature(); \ - stringStream ss; \ - ss.print("missing dependent extension(s): "); \ - deps_string(ss, dep0, ##__VA_ARGS__); \ - log_disabled(ss.as_string(true)); \ - } \ - } \ - } \ - - #define NO_UPDATE_DEFAULT \ - void update_flag() {} \ - - class RVExtFeatureValue : public RVFeatureValue { const uint32_t _cpu_feature_index; + const JVMFlagsEnum _flag; + RVExtFeatureValue* const* const _dependencies; + + bool deps_all_enabled() const; + void deps_string(stringStream& ss) const; +#ifdef ASSERT + void verify_deps() const; +#endif // ASSERT public: - RVExtFeatureValue(const char* pretty, int linux_bit_num, uint32_t cpu_feature_index, bool fstring) : + RVExtFeatureValue(const char* pretty, int linux_bit_num, uint32_t cpu_feature_index, bool fstring, + JVMFlagsEnum flag, RVExtFeatureValue* const* dependencies) : RVFeatureValue(pretty, linux_bit_num, fstring), - _cpu_feature_index(cpu_feature_index) { + _cpu_feature_index(cpu_feature_index), _flag(flag), _dependencies(dependencies) { } - int cpu_feature_index() { + int cpu_feature_index() const { // Can be used to check, for example, v is declared before Zvfh in RV_EXT_FEATURE_FLAGS. return _cpu_feature_index; } - bool enabled() { - return RVExtFeatures::current()->support_feature(_cpu_feature_index); + bool feature_enabled() { + return RVExtFeatureSet::current()->support_feature(_cpu_feature_index); } void enable_feature(int64_t value = 0) { - RVExtFeatures::current()->set_feature(_cpu_feature_index); + RVExtFeatureSet::current()->set_feature(_cpu_feature_index); } void disable_feature() { - RVExtFeatures::current()->clear_feature(_cpu_feature_index); + RVExtFeatureSet::current()->clear_feature(_cpu_feature_index); } + void update_flag(); void log_enabled(); void log_disabled(const char* reason); - - protected: - bool deps_all_enabled(RVExtFeatureValue* dep0, ...) { - assert(dep0 != nullptr, "must not"); - - va_list va; - va_start(va, dep0); - RVExtFeatureValue* next = dep0; - bool enabled = true; - while (next != nullptr && enabled) { - enabled = next->enabled(); - next = va_arg(va, RVExtFeatureValue*); - } - va_end(va); - return enabled; - } - - void deps_string(stringStream& ss, RVExtFeatureValue* dep0, ...) { - assert(dep0 != nullptr, "must not"); - ss.print("%s (%s)", dep0->pretty(), dep0->enabled() ? "enabled" : "disabled"); - - va_list va; - va_start(va, dep0); - RVExtFeatureValue* next = nullptr; - while ((next = va_arg(va, RVExtFeatureValue*)) != nullptr) { - ss.print(", %s (%s)", next->pretty(), next->enabled() ? "enabled" : "disabled"); - } - va_end(va); - } - -#ifdef ASSERT - void verify_deps(RVExtFeatureValue* dep0, ...) { - assert(dep0 != nullptr, "must not"); - assert(cpu_feature_index() >= 0, "must"); - - va_list va; - va_start(va, dep0); - RVExtFeatureValue* next = dep0; - while (next != nullptr) { - assert(next->cpu_feature_index() >= 0, "must"); - // We only need to check depenency relationship for extension flags. - // The dependant ones must be declared before this, for example, v must be declared - // before Zvfh in RV_EXT_FEATURE_FLAGS. The reason is in setup_cpu_available_features - // we need to make sure v is `update_flag`ed before Zvfh, so Zvfh is `update_flag`ed - // based on v. - assert(cpu_feature_index() > next->cpu_feature_index(), "Invalid"); - next = va_arg(va, RVExtFeatureValue*); - } - va_end(va); - } -#endif // ASSERT }; class RVNonExtFeatureValue : public RVFeatureValue { @@ -229,7 +131,7 @@ class VM_Version : public Abstract_VM_Version { RVFeatureValue(pretty, linux_bit_num, fstring), _value(DEFAULT_VALUE) { } - bool enabled() { return _value != DEFAULT_VALUE; } + bool feature_enabled() { return _value != DEFAULT_VALUE; } void enable_feature(int64_t value) { assert(value != DEFAULT_VALUE, "Sanity"); _value = value; @@ -246,91 +148,86 @@ class VM_Version : public Abstract_VM_Version { // Note: the order matters, depender should be after their dependee. E.g. ext_V before ext_Zvbb. // // Fields description in `decl`: - // declaration name, extension name, bit value from linux, feature string?, mapped flag) - #define RV_EXT_FEATURE_FLAGS(decl) \ - /* A Atomic Instructions */ \ - decl(a , ('A' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* C Compressed Instructions */ \ - decl(c , ('C' - 'A'), true , UPDATE_DEFAULT(UseRVC)) \ - /* D Single-Precision Floating-Point */ \ - decl(d , ('D' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* F Single-Precision Floating-Point */ \ - decl(f , ('F' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* H Hypervisor */ \ - decl(h , ('H' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* I RV64I */ \ - decl(i , ('I' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* M Integer Multiplication and Division */ \ - decl(m , ('M' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* Q Quad-Precision Floating-Point */ \ - decl(q , ('Q' - 'A'), true , NO_UPDATE_DEFAULT) \ - /* V Vector */ \ - decl(v , ('V' - 'A'), true , UPDATE_DEFAULT(UseRVV)) \ - \ - /* ----------------------- Other extensions ----------------------- */ \ - \ - /* Atomic compare-and-swap (CAS) instructions */ \ - decl(Zacas , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZacas)) \ - /* Byte and Halfword Atomic Memory instructions */ \ - decl(Zabha , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZabha)) \ - /* Load-acquire and store-release instructions */ \ - decl(Zalasr , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZalasr)) \ - /* Wait-on-Reservation-Set instructions */ \ - decl(Zawrs , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZawrs)) \ - /* Zba Address generation instructions */ \ - decl(Zba , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZba)) \ - /* Zbb Basic bit-manipulation */ \ - decl(Zbb , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZbb)) \ - /* Zbc Carry-less multiplication */ \ - decl(Zbc , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZbc)) \ - /* Bitmanip instructions for Cryptography */ \ - decl(Zbkb , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZbkb)) \ - /* Zbs Single-bit instructions */ \ - decl(Zbs , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZbs)) \ - /* Zcb Simple code-size saving instructions */ \ - decl(Zcb , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZcb)) \ - /* Additional Floating-Point instructions */ \ - decl(Zfa , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZfa)) \ - /* Zfh Half-Precision Floating-Point instructions */ \ - decl(Zfh , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZfh)) \ - /* Zfhmin Minimal Half-Precision Floating-Point instructions */ \ - decl(Zfhmin , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZfhmin)) \ - /* Zicbop Cache Block Prefetch Operations */ \ - decl(Zicbop , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZicbop)) \ - /* Ziccid Instruction/Data Coherence and Consistency */ \ - decl(Ziccid , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZiccid)) \ - /* Base Counters and Timers */ \ - decl(Zicntr , RV_NO_FLAG_BIT, true , NO_UPDATE_DEFAULT) \ - /* Zicond Conditional operations */ \ - decl(Zicond , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZicond)) \ - /* Zicsr Control and Status Register (CSR) Instructions */ \ - decl(Zicsr , RV_NO_FLAG_BIT, true , NO_UPDATE_DEFAULT) \ - /* Zifencei Instruction-Fetch Fence */ \ - decl(Zifencei , RV_NO_FLAG_BIT, true , NO_UPDATE_DEFAULT) \ - /* Zihintpause Pause instruction HINT */ \ - decl(Zihintpause , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZihintpause)) \ - /* Total Store Ordering */ \ - decl(Ztso , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT(UseZtso)) \ - /* Vector Basic Bit-manipulation */ \ - decl(Zvbb , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvbb, &ext_v, nullptr)) \ - /* Vector Carryless Multiplication */ \ - decl(Zvbc , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvbc, &ext_v, nullptr)) \ - /* Vector Extension for Half-Precision Floating-Point */ \ - decl(Zvfh , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvfh, &ext_v, &ext_Zfhmin, nullptr)) \ - /* Vector Extension for Minimal Half-Precision Floating-Point */ \ - decl(Zvfhmin , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvfhmin, &ext_v, nullptr)) \ - /* Shorthand for Zvkned + Zvknhb + Zvkb + Zvkt */ \ - decl(Zvkn , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvkn, &ext_v, nullptr)) \ - /* Zvkg crypto extension for ghash and gcm */ \ - decl(Zvkg , RV_NO_FLAG_BIT, true , UPDATE_DEFAULT_DEP(UseZvkg, &ext_v, nullptr)) \ - - #define DECLARE_RV_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ - struct ext_##PRETTY##RVExtFeatureValue : public RVExtFeatureValue { \ - ext_##PRETTY##RVExtFeatureValue() : \ - RVExtFeatureValue(#PRETTY, LINUX_BIT, RVExtFeatures::CPU_##ext_##PRETTY, FSTRING) {} \ - FLAGF; \ - }; \ - static ext_##PRETTY##RVExtFeatureValue ext_##PRETTY; \ + // declaration name, bit value from linux, feature string?, mapped flag, dependencies (null terminated) + #define RV_EXT_FEATURE_FLAGS(decl) \ + /* A Atomic Instructions */ \ + decl(a , ('A' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* C Compressed Instructions */ \ + decl(c , ('C' - 'A'), true , FLAG_MEMBER_ENUM(UseRVC), nullptr) \ + /* D Single-Precision Floating-Point */ \ + decl(d , ('D' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* F Single-Precision Floating-Point */ \ + decl(f , ('F' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* H Hypervisor */ \ + decl(h , ('H' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* I RV64I */ \ + decl(i , ('I' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* M Integer Multiplication and Division */ \ + decl(m , ('M' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* Q Quad-Precision Floating-Point */ \ + decl(q , ('Q' - 'A'), true , INVALID_JVMFlagsEnum, nullptr) \ + /* V Vector */ \ + decl(v , ('V' - 'A'), true , FLAG_MEMBER_ENUM(UseRVV), nullptr) \ + \ + /* ----------------------- Other extensions ----------------------- */ \ + \ + /* Atomic compare-and-swap (CAS) instructions */ \ + decl(Zacas , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZacas), nullptr) \ + /* Byte and Halfword Atomic Memory instructions */ \ + decl(Zabha , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZabha), nullptr) \ + /* Load-acquire and store-release instructions */ \ + decl(Zalasr , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZalasr), nullptr) \ + /* Wait-on-Reservation-Set instructions */ \ + decl(Zawrs , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZawrs), nullptr) \ + /* Zba Address generation instructions */ \ + decl(Zba , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZba), nullptr) \ + /* Zbb Basic bit-manipulation */ \ + decl(Zbb , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZbb), nullptr) \ + /* Zbc Carry-less multiplication */ \ + decl(Zbc , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZbc), nullptr) \ + /* Bitmanip instructions for Cryptography */ \ + decl(Zbkb , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZbkb), nullptr) \ + /* Zbs Single-bit instructions */ \ + decl(Zbs , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZbs), nullptr) \ + /* Zcb Simple code-size saving instructions */ \ + decl(Zcb , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZcb), nullptr) \ + /* Additional Floating-Point instructions */ \ + decl(Zfa , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZfa), nullptr) \ + /* Zfh Half-Precision Floating-Point instructions */ \ + decl(Zfh , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZfh), nullptr) \ + /* Zfhmin Minimal Half-Precision Floating-Point instructions */ \ + decl(Zfhmin , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZfhmin), nullptr) \ + /* Zicbop Cache Block Prefetch Operations */ \ + decl(Zicbop , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZicbop), nullptr) \ + /* Ziccid Instruction/Data Coherence and Consistency */ \ + decl(Ziccid , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZiccid), nullptr) \ + /* Base Counters and Timers */ \ + decl(Zicntr , RV_NO_FLAG_BIT, true , INVALID_JVMFlagsEnum, nullptr) \ + /* Zicond Conditional operations */ \ + decl(Zicond , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZicond), nullptr) \ + /* Zicsr Control and Status Register (CSR) Instructions */ \ + decl(Zicsr , RV_NO_FLAG_BIT, true , INVALID_JVMFlagsEnum, nullptr) \ + /* Zifencei Instruction-Fetch Fence */ \ + decl(Zifencei , RV_NO_FLAG_BIT, true , INVALID_JVMFlagsEnum, nullptr) \ + /* Zihintpause Pause instruction HINT */ \ + decl(Zihintpause , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZihintpause), nullptr) \ + /* Total Store Ordering */ \ + decl(Ztso , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZtso), nullptr) \ + /* Vector Basic Bit-manipulation */ \ + decl(Zvbb , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvbb), &ext_v, nullptr) \ + /* Vector Carryless Multiplication */ \ + decl(Zvbc , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvbc), &ext_v, nullptr) \ + /* Vector Extension for Half-Precision Floating-Point */ \ + decl(Zvfh , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvfh), &ext_v, &ext_Zfhmin, nullptr) \ + /* Vector Extension for Minimal Half-Precision Floating-Point */ \ + decl(Zvfhmin , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvfhmin), &ext_v, nullptr) \ + /* Shorthand for Zvkned + Zvknhb + Zvkb + Zvkt */ \ + decl(Zvkn , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvkn), &ext_v, nullptr) \ + /* Zvkg crypto extension for ghash and gcm */ \ + decl(Zvkg , RV_NO_FLAG_BIT, true , FLAG_MEMBER_ENUM(UseZvkg), &ext_v, nullptr) \ + + #define DECLARE_RV_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) \ + static RVExtFeatureValue ext_##PRETTY; RV_EXT_FEATURE_FLAGS(DECLARE_RV_EXT_FEATURE) #undef DECLARE_RV_EXT_FEATURE @@ -339,43 +236,38 @@ class VM_Version : public Abstract_VM_Version { // #define RV_NON_EXT_FEATURE_FLAGS(decl) \ /* Id for microarch. Mvendorid plus marchid uniquely identify the microarch. */ \ - decl(marchid , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(marchid , RV_NO_FLAG_BIT, false) \ /* A unique encoding of the version of the processor implementation. */ \ - decl(mimpid , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(mimpid , RV_NO_FLAG_BIT, false) \ /* Manufactory JEDEC id encoded, ISA vol 2 3.1.2.. */ \ - decl(mvendorid , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(mvendorid , RV_NO_FLAG_BIT, false) \ /* SATP bits (number of virtual addr bits) mbare, sv39, sv48, sv57, sv64 */ \ - decl(satp_mode , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(satp_mode , RV_NO_FLAG_BIT, false) \ /* Performance of misaligned scalar accesses (unknown, emulated, slow, fast, unsupported) */ \ - decl(unaligned_scalar , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(unaligned_scalar , RV_NO_FLAG_BIT, false) \ /* Performance of misaligned vector accesses (unknown, unspported, slow, fast) */ \ - decl(unaligned_vector , RV_NO_FLAG_BIT, false, NO_UPDATE_DEFAULT) \ + decl(unaligned_vector , RV_NO_FLAG_BIT, false) \ - #define DECLARE_RV_NON_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING, FLAGF) \ - struct PRETTY##RVNonExtFeatureValue : public RVNonExtFeatureValue { \ - PRETTY##RVNonExtFeatureValue() : \ - RVNonExtFeatureValue(#PRETTY, LINUX_BIT, FSTRING) {} \ - FLAGF; \ - }; \ - static PRETTY##RVNonExtFeatureValue PRETTY; \ + #define DECLARE_RV_NON_EXT_FEATURE(PRETTY, LINUX_BIT, FSTRING) \ + static RVNonExtFeatureValue PRETTY; RV_NON_EXT_FEATURE_FLAGS(DECLARE_RV_NON_EXT_FEATURE) #undef DECLARE_RV_NON_EXT_FEATURE private: // Utility for AOT CPU feature store/check. - class RVExtFeatures : public CHeapObj { + class RVExtFeatureSet : public CHeapObj { public: enum RVFeatureIndex { - #define DECLARE_RV_FEATURE_ENUM(PRETTY, LINUX_BIT, FSTRING, FLAGF) CPU_##ext_##PRETTY, + #define DECLARE_RV_FEATURE_ENUM(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) CPU_##ext_##PRETTY, RV_EXT_FEATURE_FLAGS(DECLARE_RV_FEATURE_ENUM) - MAX_CPU_FEATURE_INDEX + CPU_FEATURE_COUNT #undef DECLARE_RV_FEATURE_ENUM }; private: - uint64_t _features_bitmap[(MAX_CPU_FEATURE_INDEX / BitsPerLong) + 1]; - static_assert(sizeof(_features_bitmap) * BitsPerByte >= MAX_CPU_FEATURE_INDEX); + uint64_t _features_bitmap[(CPU_FEATURE_COUNT / BitsPerLong) + 1]; + static_assert(sizeof(_features_bitmap) * BitsPerByte >= CPU_FEATURE_COUNT); // Number of 8-byte elements in _features_bitmap. constexpr static int element_count() { @@ -393,16 +285,16 @@ class VM_Version : public Abstract_VM_Version { } static RVFeatureIndex convert(uint32_t index) { - assert(index < MAX_CPU_FEATURE_INDEX, "must"); + assert(index < CPU_FEATURE_COUNT, "must"); return (RVFeatureIndex)index; } public: - static RVExtFeatures* current() { - return _rv_ext_features; + static RVExtFeatureSet* current() { + return &_rv_ext_features; } - RVExtFeatures() { + RVExtFeatureSet() { for (int i = 0; i < element_count(); i++) { _features_bitmap[i] = 0; } @@ -426,7 +318,7 @@ class VM_Version : public Abstract_VM_Version { return (_features_bitmap[idx] & feature_bit(f)) != 0; } - bool verify_aot_code_cache_features(RVExtFeatures* features_to_test) const { + bool verify_aot_code_cache_features(RVExtFeatureSet* features_to_test) const { for (int i = 0; i < element_count(); i++) { if (_features_bitmap[i] != features_to_test->_features_bitmap[i]) { return false; @@ -436,7 +328,7 @@ class VM_Version : public Abstract_VM_Version { } // Is this a super set of features_to_test? - bool super_set_of(RVExtFeatures* features_to_test) { + bool super_set_of(RVExtFeatureSet* features_to_test) { for (int i = 0; i < element_count(); i++) { if ((_features_bitmap[i] | features_to_test->_features_bitmap[i]) != _features_bitmap[i]) { return false; @@ -446,8 +338,8 @@ class VM_Version : public Abstract_VM_Version { } // Returns features present in this but not in features_to_test - RVExtFeatures features_not_in(RVExtFeatures* features_to_test) { - RVExtFeatures result; + RVExtFeatureSet features_not_in(RVExtFeatureSet* features_to_test) { + RVExtFeatureSet result; for (int i = 0; i < element_count(); i++) { result._features_bitmap[i] = _features_bitmap[i] & (~(features_to_test->_features_bitmap[i])); } @@ -529,10 +421,21 @@ class VM_Version : public Abstract_VM_Version { MISALIGNED_VECTOR_UNSUPPORTED = 4 }; - // Null terminated list - static RVFeatureValue* _feature_list[]; - static RVExtFeatures* _rv_ext_features; - static RVExtFeatures _rv_ext_features_disabled_by_aot_cache; + #define DECLARE_RV_EXT_DEPENDENCIES(PRETTY, LINUX_BIT, FSTRING, FLAG, ...) \ + static RVExtFeatureValue* const _ext_##PRETTY##_dependencies[]; + + RV_EXT_FEATURE_FLAGS(DECLARE_RV_EXT_DEPENDENCIES) + #undef DECLARE_RV_EXT_DEPENDENCIES + + // Null-terminated; the extension prefix must match _ext_feature_list. + static RVFeatureValue* const _feature_list[]; + // Indexed by RVExtFeatureSet::RVFeatureIndex; not null-terminated. + static RVExtFeatureValue* const _ext_feature_list[]; + + // Mutable runtime feature set, not a snapshot of raw hardware capabilities. + static RVExtFeatureSet _rv_ext_features; + // Features removed by AOT cache restrictions, retained for diagnostics. + static RVExtFeatureSet _rv_ext_features_disabled_by_aot_cache; // Enables features in _feature_list static void setup_cpu_available_features(); @@ -595,7 +498,7 @@ class VM_Version : public Abstract_VM_Version { // RISCV64 supports fast class initialization checks static bool supports_fast_class_init_checks() { return true; } - static bool supports_fencei_barrier() { return ext_Zifencei.enabled(); } + static bool supports_fencei_barrier() { return ext_Zifencei.feature_enabled(); } // Zfhmin only provides half-precision load/store/convert instructions, // Zfh additionally provides half-precision arithmetic. Either one is @@ -621,11 +524,11 @@ class VM_Version : public Abstract_VM_Version { static bool verify_aot_code_cache_features(void* features_buffer); static void get_cpu_features_name(void* features_buffer, stringStream& ss); static void get_missing_features_name(void* features_set1, void* features_set2, stringStream& ss); - static int cpu_features_alignment() { return alignof(RVExtFeatures); } + static int cpu_features_alignment() { return alignof(RVExtFeatureSet); } private: static void print_feature_name(stringStream& ss, RVFeatureValue* feature); - static void insert_features_names(RVExtFeatures* features, stringStream& ss); + static void insert_features_names(RVExtFeatureSet* features, stringStream& ss); }; #endif // CPU_RISCV_VM_VERSION_RISCV_HPP diff --git a/src/hotspot/cpu/s390/gc/g1/g1_s390.ad b/src/hotspot/cpu/s390/gc/g1/g1_s390.ad index 0371a6fdf4a9..e108c8fc1724 100644 --- a/src/hotspot/cpu/s390/gc/g1/g1_s390.ad +++ b/src/hotspot/cpu/s390/gc/g1/g1_s390.ad @@ -73,10 +73,6 @@ static void write_barrier_post(MacroAssembler* masm, %} // source - -// TODO 8350865 (same applies to g1StoreLSpecialTwoOops) -// - Do not set/overwrite barrier data here, also handle G1C2BarrierPostNotNull - instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegL src, immI_0 off, iRegL tmp1, iRegL tmp2, iRegL tmp3, flagsReg cr) %{ predicate(UseG1GC); match(Set mem (StoreLSpecial mem (Binary src off))); @@ -85,7 +81,6 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegL src, immI_0 off, iRegL tm format %{ "STG $src,$mem\t # g1StoreLSpecialOneOopOff0" %} ins_encode %{ __ block_comment("g1StoreLSpecialOneOopOff0 {"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); write_barrier_pre(masm, this, $mem$$Register /* obj */, @@ -97,8 +92,14 @@ instruct g1StoreLSpecialOneOopOff0(indirect mem, iRegL src, immI_0 off, iRegL tm // Extract the narrow oop at offset 0: on big-endian s390x the field at // memory offset 0 occupies the HIGH 32 bits of the 64-bit register. - __ z_srlg($tmp1$$Register, $src$$Register, 32); - __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ z_srlg($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + } else { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, false /* maybe_null */); + } + } write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -117,7 +118,6 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegL src, immI_4 off, iRegL tm format %{ "STG $src,$mem\t # g1StoreLSpecialOneOopOff4" %} ins_encode %{ __ block_comment("g1StoreLSpecialOneOopOff4 {"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); __ z_la($tmp1$$Register, Address($mem$$Register, 4)); write_barrier_pre(masm, this, @@ -130,8 +130,14 @@ instruct g1StoreLSpecialOneOopOff4(indirect mem, iRegL src, immI_4 off, iRegL tm // Extract the narrow oop at offset 4: on big-endian s390x the field at // memory offset 4 occupies the LOW 32 bits of the 64-bit register. - __ z_llgfr($tmp2$$Register, $src$$Register); - __ oop_decoder($tmp2$$Register, $tmp2$$Register, true /* maybe_null */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ z_llgfr($tmp2$$Register, $src$$Register); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ oop_decoder($tmp2$$Register, $tmp2$$Register, true /* maybe_null */); + } else { + __ oop_decoder($tmp2$$Register, $tmp2$$Register, false /* maybe_null */); + } + } write_barrier_post(masm, this, $tmp1$$Register /* store_addr */, $tmp2$$Register /* new_val */, @@ -150,7 +156,6 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegL src, iRegL tmp1, iRegL tmp2, format %{ "STG $src,$mem\t # g1StoreLSpecialTwoOops" %} ins_encode %{ __ block_comment("g1StoreLSpecialTwoOops {"); - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); write_barrier_pre(masm, this, $mem$$Register /* obj */, @@ -167,8 +172,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegL src, iRegL tmp1, iRegL tmp2, __ z_stg($src$$Register, Address($mem$$Register, 0)); // Oop at offset 0: high 32 bits of register -> memory address mem+0. - __ z_srlg($tmp1$$Register, $src$$Register, 32); - __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ z_srlg($tmp1$$Register, $src$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + } else { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, false /* maybe_null */); + } + } write_barrier_post(masm, this, $mem$$Register /* store_addr */, $tmp1$$Register /* new_val */, @@ -176,8 +187,14 @@ instruct g1StoreLSpecialTwoOops(indirect mem, iRegL src, iRegL tmp1, iRegL tmp2, $tmp3$$Register /* tmp2 */); // Oop at offset 4: low 32 bits of register -> memory address mem+4. - __ z_llgfr($tmp1$$Register, $src$$Register); - __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ z_llgfr($tmp1$$Register, $src$$Register); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, true /* maybe_null */); + } else { + __ oop_decoder($tmp1$$Register, $tmp1$$Register, false /* maybe_null */); + } + } write_barrier_post(masm, this, $tmp4$$Register /* store_addr */, $tmp1$$Register /* new_val */, diff --git a/src/hotspot/cpu/s390/s390.ad b/src/hotspot/cpu/s390/s390.ad index bd0104708408..4696d62db13d 100644 --- a/src/hotspot/cpu/s390/s390.ad +++ b/src/hotspot/cpu/s390/s390.ad @@ -1077,11 +1077,6 @@ int ConstantTable::calculate_table_base_offset() const { return 0; // absolute addressing, no offset } -bool MachConstantBaseNode::requires_postalloc_expand() const { return false; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - ShouldNotReachHere(); -} - // Even with PC-relative TOC addressing, we still need this node. // Float loads/stores do not support PC-relative addresses. void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { @@ -1347,7 +1342,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler *masm, PhaseRegAlloc *r const char *mnemo = nullptr; unsigned long opc = 0; - if (bottom_type()->isa_vect() != nullptr && ideal_reg() == Op_VecX) { + if (bottom_type()->is_vect() && ideal_reg() == Op_VecX) { if (src_lo_rc == rc_stack && dst_lo_rc == rc_stack) { if (masm != nullptr) { __ z_mvc(Address(Z_SP, 0, dst_offset), Address(Z_SP, 0, src_offset), 16); @@ -4978,7 +4973,7 @@ instruct decodeN_NN(iRegP dst, iRegN src, flagsReg cr) %{ match(Set dst (DecodeN src)); effect(KILL cr); predicate((n->bottom_type()->make_ptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_oopptr()->ptr() == TypePtr::Constant) && + n->bottom_type()->as_oopptr()->ptr() == TypePtr::Constant) && (CompressedOops::base()== nullptr || !ExpandLoadingBaseDecode_NN)); ins_cost(MEMORY_REF_COST+2 * DEFAULT_COST); // TODO: s390 port size(VARIABLE_SIZE); @@ -5045,7 +5040,7 @@ instruct decodeN_Ex(iRegP dst, iRegN src, flagsReg cr) %{ instruct decodeN_NN_Ex(iRegP dst, iRegN src, flagsReg cr) %{ match(Set dst (DecodeN src)); predicate((n->bottom_type()->make_ptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_oopptr()->ptr() == TypePtr::Constant) && + n->bottom_type()->as_oopptr()->ptr() == TypePtr::Constant) && CompressedOops::base() != nullptr && ExpandLoadingBaseDecode_NN); ins_cost(MEMORY_REF_COST+2 * DEFAULT_COST); // TODO: s390 port size(VARIABLE_SIZE); @@ -10519,7 +10514,7 @@ instruct indexOf_imm1_U(iRegP haystack, iRegI haycnt, immP needle, immI_1 needle format %{ "String IndexOf UL [0..$haycnt]($haystack), [0]($needle) -> $result" %} ins_encode %{ immPOper *needleOper = (immPOper *)$needle; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr; #ifdef VM_LITTLE_ENDIAN @@ -10544,7 +10539,7 @@ instruct indexOf_imm1_L(iRegP haystack, iRegI haycnt, immP needle, immI_1 needle format %{ "String IndexOf L [0..$haycnt]($haystack), [0]($needle) -> $result" %} ins_encode %{ immPOper *needleOper = (immPOper *)$needle; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, @@ -10563,7 +10558,7 @@ instruct indexOf_imm1_UL(iRegP haystack, iRegI haycnt, immP needle, immI_1 needl format %{ "String IndexOf UL [0..$haycnt]($haystack), [0]($needle) -> $result" %} ins_encode %{ immPOper *needleOper = (immPOper *)$needle; - const TypeOopPtr *t = needleOper->type()->isa_oopptr(); + const TypeOopPtr* t = needleOper->type()->as_oopptr(); ciTypeArray* needle_values = t->const_oop()->as_type_array(); // Pointer to live char * jchar chr = (jchar)needle_values->element_value(0).as_byte(); __ string_indexof_char($result$$Register, diff --git a/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp b/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp index 4e164a9dab47..7080e850b836 100644 --- a/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp @@ -1369,6 +1369,88 @@ void C2_MacroAssembler::varshiftbw(int opcode, XMMRegister dst, XMMRegister src, vpackusdw(dst, dst, vtmp, 0); } +// vgf2p8affineqb with immediate 0 sets each result bit to the parity of +// the source byte ANDed with one matrix byte. Nothing is added afterwards. +// The most significant matrix byte builds result bit 0, and each following +// byte builds the next higher result bit. A matrix byte equal to 1<> (8*n) +// result bit k = source bit (k-n) if k >= n, else 0 +// +// That is a logical left shift by n. An arithmetic right shift is A_srl(n) +// with source bit 7 copied into the n result bits the logical shift clears. +// Those are result bits (8-n)..7, built by the n least significant matrix +// bytes, and source bit 7 is the mask 0x80. OR that mask into those n bytes: +// +// A_sra(n) = A_srl(n) | (low n bytes each equal to 0x80) +// +// A count of 0 leaves I for all three. The stub holds one matrix per count in +// 0..31, the Java int shift mask. A Vector API byte shift is already in 0..7. +// Counts 8..31 empty a byte: the logical matrices are 0 and the arithmetic +// right matrices fill the sign bit. +// +// Check A_srl(2). I << 16 = 0x0408102040800000, bytes 0x04, 0x08, 0x10, 0x20, +// 0x40, 0x80, 0x00, 0x00 from the MSB: source bits 2, 3, 4, 5, 6, 7 and then +// two zeros. AND the source with 0x04 and take the parity to write source +// bit 2 into result bit 0. 0x08 writes source bit 3 into result bit 1, and +// so on through 0x80, which writes source bit 7 into result bit 5. The two +// 0x00 bytes write 0 into result bits 6 and 7. For source 0b10110000 the +// result is 0b00101100. +void C2_MacroAssembler::vshiftb_gfni(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, + Register rtmp, Register rbase, int vlen_enc) { + assert(VM_Version::supports_gfni(), "required"); + assert_different_registers(dst, src); + int kind = 0; + if (opcode == Op_URShiftVB) { + kind = 1; + } else if (opcode == Op_RShiftVB) { + kind = 2; + } else { + assert(opcode == Op_LShiftVB, "%s", NodeClassNames[opcode]); + } + movdl(rtmp, shift); +#ifdef ASSERT + // Preserve flags so the rule does not need KILL cr. + Label count_in_range; + pushf(); + cmpl(rtmp, 31); + jcc(Assembler::belowEqual, count_in_range); + popf(); + stop("byte shift count out of 0..31"); + bind(count_in_range); + popf(); +#endif + // One matrix per count in 0..31. + const int mats_per_kind = 32; + lea(rbase, ExternalAddress(StubRoutines::x86::vector_byte_shift_gfni_matrix())); + Address matrix(rbase, rtmp, Address::times_8, kind * mats_per_kind * BytesPerLong); + if (vlen_enc == Assembler::AVX_128bit) { + movddup(dst, matrix); + } else { + vpbroadcastq(dst, matrix, vlen_enc); + } + vgf2p8affineqb(dst, src, dst, 0, vlen_enc); +} + // Variable shift src by shift using vtmp and scratch as TEMPs giving byte result in dst void C2_MacroAssembler::evarshiftb(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len, XMMRegister vtmp) { assert(opcode == Op_LShiftVB || diff --git a/src/hotspot/cpu/x86/c2_MacroAssembler_x86.hpp b/src/hotspot/cpu/x86/c2_MacroAssembler_x86.hpp index 761879cbc9ca..5ba00b1771f3 100644 --- a/src/hotspot/cpu/x86/c2_MacroAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/c2_MacroAssembler_x86.hpp @@ -115,6 +115,9 @@ void varshiftq(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, int vlen_enc, XMMRegister vtmp = xnoreg); void varshiftbw(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len, XMMRegister vtmp); void evarshiftb(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len, XMMRegister vtmp); + // Uniform byte shift via GFNI affine instruction. shift holds the scalar count. + void vshiftb_gfni(int opcode, XMMRegister dst, XMMRegister src, XMMRegister shift, + Register rtmp, Register rbase, int vlen_enc); void insert(BasicType typ, XMMRegister dst, Register val, int idx); void vinsert(BasicType typ, XMMRegister dst, XMMRegister src, Register val, int idx); diff --git a/src/hotspot/cpu/x86/gc/g1/g1_x86_64.ad b/src/hotspot/cpu/x86/gc/g1/g1_x86_64.ad index c28b3c15af43..48c486ea8075 100644 --- a/src/hotspot/cpu/x86/gc/g1/g1_x86_64.ad +++ b/src/hotspot/cpu/x86/gc/g1/g1_x86_64.ad @@ -99,8 +99,6 @@ instruct g1StoreP(memory mem, any_RegP src, rRegP tmp1, rRegP tmp2, rRegP tmp3, ins_pipe(ialu_mem_reg); %} -// TODO 8350865 (same applies to g1StoreLSpecialTwoOops) -// - Do not set/overwrite barrier data here, also handle G1C2BarrierPostNotNull instruct g1StoreLSpecialOneOopOff0(memory mem, rRegL src, immI_0 off, rRegP tmp1, rRegP tmp2, rRegP tmp3, rFlagsReg cr) %{ predicate(UseG1GC); @@ -108,8 +106,6 @@ instruct g1StoreLSpecialOneOopOff0(memory mem, rRegL src, immI_0 off, rRegP tmp1 effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr); format %{ "movq $mem, $src\t# g1StoreLSpecialOneOopOff0" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - __ lea($tmp1$$Register, $mem$$Address); write_barrier_pre(masm, this, $tmp1$$Register /* obj */, @@ -120,8 +116,14 @@ instruct g1StoreLSpecialOneOopOff0(memory mem, rRegL src, immI_0 off, rRegP tmp1 __ movq(Address($tmp1$$Register, 0), $src$$Register); // Extract the narrow oop field value - __ movl($tmp2$$Register, $src$$Register); - __ decode_heap_oop($tmp2$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ movl($tmp2$$Register, $src$$Register); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp2$$Register); + } else { + __ decode_heap_oop_not_null($tmp2$$Register); + } + } write_barrier_post(masm, this, $tmp1$$Register /* store_addr */, $tmp2$$Register /* new_val */, @@ -137,11 +139,12 @@ instruct g1StoreLSpecialOneOopOff4(memory mem, rRegL src, immI_4 off, rRegP tmp1 effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr); format %{ "movq $mem, $src\t# g1StoreLSpecialOneOopOff4" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - - // Adjust address to point to narrow oop Address dst = $mem$$Address; - __ lea($tmp1$$Register, dst.plus_disp(4)); + // Adjust address to point to narrow oop if we need any barrier. Otherwise, no need to touch tmp1 at all. + // We don't save any instruction, but we make the generated assembly less confusing for the poor soul who + // will step through that during debugging. + int off = ((barrier_data() & G1C2BarrierPre) == 0 && (barrier_data() & G1C2BarrierPost) == 0) ? 0 : 4; + __ lea($tmp1$$Register, dst.plus_disp(off)); write_barrier_pre(masm, this, $tmp1$$Register /* obj */, $tmp2$$Register /* pre_val */, @@ -149,12 +152,18 @@ instruct g1StoreLSpecialOneOopOff4(memory mem, rRegL src, immI_4 off, rRegP tmp1 RegSet::of($tmp1$$Register, $src$$Register) /* preserve */); // The address of the oop is the address of the store plus the offset of the oop - __ movq(Address($tmp1$$Register, -4), $src$$Register); + __ movq(Address($tmp1$$Register, -off), $src$$Register); // Shift long value to extract the narrow oop field value - __ movq($tmp2$$Register, $src$$Register); - __ shrq($tmp2$$Register, 32); - __ decode_heap_oop($tmp2$$Register); + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ movq($tmp2$$Register, $src$$Register); + __ shrq($tmp2$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp2$$Register); + } else { + __ decode_heap_oop_not_null($tmp2$$Register); + } + } write_barrier_post(masm, this, $tmp1$$Register /* store_addr */, $tmp2$$Register /* new_val */, @@ -170,43 +179,59 @@ instruct g1StoreLSpecialTwoOops(memory mem, rRegL src, rRegP tmp1, rRegP tmp2, r effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr); format %{ "movq $mem, $src\t# g1StoreLSpecialTwoOops" %} ins_encode %{ - ((MachNode*)this)->set_barrier_data(G1C2BarrierPre | G1C2BarrierPost); - __ lea($tmp1$$Register, $mem$$Address); - write_barrier_pre(masm, this, - $tmp1$$Register /* obj */, - $tmp2$$Register /* pre_val */, - $tmp3$$Register /* tmp */, - RegSet::of($tmp1$$Register, $src$$Register) /* preserve */); - // Adjust address to point to the second narrow oop in the long value - __ addq($tmp1$$Register, 4); - write_barrier_pre(masm, this, - $tmp1$$Register /* obj */, - $tmp2$$Register /* pre_val */, - $tmp3$$Register /* tmp */, - RegSet::of($tmp1$$Register, $src$$Register) /* preserve */); - - // The address of the second oop is the address of the store plus the offset of the second oop - __ movq(Address($tmp1$$Register, -4), $src$$Register); - - // Do the post-barrier of the second oop first since we have its address in tmp1 - __ movq($tmp2$$Register, $src$$Register); - __ shrq($tmp2$$Register, 32); - __ decode_heap_oop($tmp2$$Register); - write_barrier_post(masm, this, - $tmp1$$Register /* store_addr */, - $tmp2$$Register /* new_val */, - $tmp3$$Register /* tmp1 */); - - // Retrieve the address of the first narrow oop - __ addq($tmp1$$Register, -4); - // Extract the first narrow oop - __ movl($tmp2$$Register, $src$$Register); - __ decode_heap_oop($tmp2$$Register); - write_barrier_post(masm, this, - $tmp1$$Register /* store_addr */, - $tmp2$$Register /* new_val */, - $tmp3$$Register /* tmp1 */); + if ((barrier_data() & G1C2BarrierPre) == 0 && (barrier_data() & G1C2BarrierPost) == 0) { + // In case we need barriers, we need tmp1 to walk over both oops, either for pre- or post- barrier. + // But if we don't need any, we can save all these shenanigans and keep it simple. + __ movq(Address($tmp1$$Register, 0), $src$$Register); + } else { + write_barrier_pre(masm, this, + $tmp1$$Register /* obj */, + $tmp2$$Register /* pre_val */, + $tmp3$$Register /* tmp */, + RegSet::of($tmp1$$Register, $src$$Register) /* preserve */); + // Adjust address to point to the second narrow oop in the long value. + __ addq($tmp1$$Register, 4); + write_barrier_pre(masm, this, + $tmp1$$Register /* obj */, + $tmp2$$Register /* pre_val */, + $tmp3$$Register /* tmp */, + RegSet::of($tmp1$$Register, $src$$Register) /* preserve */); + + // The address of the second oop is the address of the store plus the offset of the second oop + __ movq(Address($tmp1$$Register, -4), $src$$Register); + + // Do the post-barrier of the second oop first since we have its address in tmp1 + if ((barrier_data() & G1C2BarrierPost) != 0) { + __ movq($tmp2$$Register, $src$$Register); + __ shrq($tmp2$$Register, 32); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp2$$Register); + } else { + __ decode_heap_oop_not_null($tmp2$$Register); + } + } + write_barrier_post(masm, this, + $tmp1$$Register /* store_addr */, + $tmp2$$Register /* new_val */, + $tmp3$$Register /* tmp1 */); + + // Extract the first narrow oop + if ((barrier_data() & G1C2BarrierPost) != 0) { + // Retrieve the address of the first narrow oop + __ addq($tmp1$$Register, -4); + __ movl($tmp2$$Register, $src$$Register); + if ((barrier_data() & G1C2BarrierPostNotNull) == 0) { + __ decode_heap_oop($tmp2$$Register); + } else { + __ decode_heap_oop_not_null($tmp2$$Register); + } + } + write_barrier_post(masm, this, + $tmp1$$Register /* store_addr */, + $tmp2$$Register /* new_val */, + $tmp3$$Register /* tmp1 */); + } %} ins_pipe(ialu_mem_reg); %} diff --git a/src/hotspot/cpu/x86/peephole_x86_64.cpp b/src/hotspot/cpu/x86/peephole_x86_64.cpp index 9dccea8515ec..0c4971584010 100644 --- a/src/hotspot/cpu/x86/peephole_x86_64.cpp +++ b/src/hotspot/cpu/x86/peephole_x86_64.cpp @@ -184,55 +184,52 @@ bool Peephole::test_may_remove(Block* block, int block_index, PhaseCFG* cfg_, Ph if (block_index < 2 || block->get_node(block_index - 2) != inst1) { return false; } - if (inst1 != nullptr) { - MachNode* prevNode = inst1->isa_Mach(); - if (prevNode != nullptr) { - // Includes other flags as well, but that doesn't matter here - juint all_node_flags = prevNode->flags(); - if (all_node_flags == 0) { - // We can return early - there is no way the test can be removed, the preceding node does not set any flags - return false; - } - juint required_flags = 0; - // Search for the uses of the node and compute which flags are required - for (DUIterator_Fast imax, i = test_to_check->fast_outs(imax); i < imax; i++) { - MachNode* node_out = test_to_check->fast_out(i)->isa_Mach(); - bool found_correct_oper = false; - for (uint16_t j = 0; j < node_out->_num_opnds; ++j) { - MachOper* operand = node_out->_opnds[j]; - if (operand->opcode() == cmpOp_rule || operand->opcode() == cmpOpU_rule) { - auto condition = static_cast(operand->ccode()); - juint flags_for_inst = map_condition_to_required_test_flags(condition); - required_flags = required_flags | flags_for_inst; - found_correct_oper = true; - break; - } - } - if (!found_correct_oper) { - // We could not find one the required flags for one of the dependencies. Keep the test as it might set flags needed for that node - return false; + if (MachNode* prevNode = Node::isa(inst1); prevNode != nullptr) { + // Includes other flags as well, but that doesn't matter here + juint all_node_flags = prevNode->flags(); + if (all_node_flags == 0) { + // We can return early - there is no way the test can be removed, the preceding node does not set any flags + return false; + } + juint required_flags = 0; + // Search for the uses of the node and compute which flags are required + for (DUIterator_Fast imax, i = test_to_check->fast_outs(imax); i < imax; i++) { + MachNode* node_out = test_to_check->fast_out(i)->isa_Mach(); + bool found_correct_oper = false; + for (uint16_t j = 0; j < node_out->_num_opnds; ++j) { + MachOper* operand = node_out->_opnds[j]; + if (operand->opcode() == cmpOp_rule || operand->opcode() == cmpOpU_rule) { + auto condition = static_cast(operand->ccode()); + juint flags_for_inst = map_condition_to_required_test_flags(condition); + required_flags = required_flags | flags_for_inst; + found_correct_oper = true; + break; } } - assert(required_flags != 0, "No flags required, should be impossible!"); - bool sets_all_required_flags = (required_flags & ~all_node_flags) == 0; - if (sets_all_required_flags) { - // All flags are covered are clear to remove this test - MachProjNode* machProjNode = block->get_node(block_index - 1)->isa_MachProj(); - assert(machProjNode != nullptr, "Expected a MachProj node here!"); - assert(ra_->get_reg_first(machProjNode) == ra_->get_reg_first(test_to_check), "Test must operate on the same register as its replacement"); - - // Remove the original test node and replace it with the pseudo test node. The AND node already sets ZF - test_to_check->replace_by(machProjNode); - - // Modify the block - test_to_check->set_removed(); - block->remove_node(block_index); - - // Modify the control flow - cfg_->map_node_to_block(test_to_check, nullptr); - return true; + if (!found_correct_oper) { + // We could not find one the required flags for one of the dependencies. Keep the test as it might set flags needed for that node + return false; } } + assert(required_flags != 0, "No flags required, should be impossible!"); + bool sets_all_required_flags = (required_flags & ~all_node_flags) == 0; + if (sets_all_required_flags) { + // All flags are covered are clear to remove this test + MachProjNode* machProjNode = block->get_node(block_index - 1)->isa_MachProj(); + assert(machProjNode != nullptr, "Expected a MachProj node here!"); + assert(ra_->get_reg_first(machProjNode) == ra_->get_reg_first(test_to_check), "Test must operate on the same register as its replacement"); + + // Remove the original test node and replace it with the pseudo test node. The AND node already sets ZF + test_to_check->replace_by(machProjNode); + + // Modify the block + test_to_check->set_removed(); + block->remove_node(block_index); + + // Modify the control flow + cfg_->map_node_to_block(test_to_check, nullptr); + return true; + } } return false; } diff --git a/src/hotspot/cpu/x86/stubDeclarations_x86.hpp b/src/hotspot/cpu/x86/stubDeclarations_x86.hpp index 7669ef42bf42..fd3b978b4698 100644 --- a/src/hotspot/cpu/x86/stubDeclarations_x86.hpp +++ b/src/hotspot/cpu/x86/stubDeclarations_x86.hpp @@ -108,6 +108,10 @@ do_stub(compiler, vector_byte_perm_mask) \ do_arch_entry(x86, compiler,vector_byte_perm_mask, \ vector_byte_perm_mask, vector_byte_perm_mask) \ + do_stub(compiler, vector_byte_shift_gfni_matrix) \ + do_arch_entry(x86, compiler, vector_byte_shift_gfni_matrix, \ + vector_byte_shift_gfni_matrix, \ + vector_byte_shift_gfni_matrix) \ do_stub(compiler, vector_int_to_byte_mask) \ do_arch_entry(x86, compiler, vector_int_to_byte_mask, \ vector_int_to_byte_mask, vector_int_to_byte_mask) \ diff --git a/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp b/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp index 506d1f13f361..d14929b77735 100644 --- a/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp +++ b/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp @@ -1425,6 +1425,65 @@ address StubGenerator::generate_vector_byte_perm_mask() { return start; } +// 3 * 32 matrices: logical-left, logical-right, arithmetic-right, counts 0..31. +address StubGenerator::generate_vector_byte_shift_gfni_matrix() { + StubId stub_id = StubId::stubgen_vector_byte_shift_gfni_matrix_id; + int entry_count = StubInfo::entry_count(stub_id); + assert(entry_count == 1, "sanity check"); + address start = load_archive_data(stub_id); + if (start != nullptr) { + return start; + } + __ align(CodeEntryAlignment); + StubCodeMark mark(this, stub_id); + start = __ pc(); + + // Counts 0..7. Counts 8..31 have shifted the byte out of the low 8 bits. + static const uint64_t mats[3][8] = { + // logical left + { 0x0102040810204080ULL, + 0x0001020408102040ULL, + 0x0000010204081020ULL, + 0x0000000102040810ULL, + 0x0000000001020408ULL, + 0x0000000000010204ULL, + 0x0000000000000102ULL, + 0x0000000000000001ULL }, + // logical right + { 0x0102040810204080ULL, + 0x0204081020408000ULL, + 0x0408102040800000ULL, + 0x0810204080000000ULL, + 0x1020408000000000ULL, + 0x2040800000000000ULL, + 0x4080000000000000ULL, + 0x8000000000000000ULL }, + // arithmetic right + { 0x0102040810204080ULL, + 0x0204081020408080ULL, + 0x0408102040808080ULL, + 0x0810204080808080ULL, + 0x1020408080808080ULL, + 0x2040808080808080ULL, + 0x4080808080808080ULL, + 0x8080808080808080ULL } + }; + static const uint64_t saturated[3] = { + 0, // logical left + 0, // logical right + 0x8080808080808080ULL // arithmetic right, sign fill + }; + for (int kind = 0; kind < 3; kind++) { + for (int n = 0; n < 32; n++) { + uint64_t m = (n < 8) ? mats[kind][n] : saturated[kind]; + __ emit_data64((jlong)m, relocInfo::none); + } + } + + store_archive_data(stub_id, start, __ pc()); + return start; +} + address StubGenerator::generate_vector_fp_mask(StubId stub_id, int64_t mask) { int entry_count = StubInfo::entry_count(stub_id); assert(entry_count == 1, "sanity check"); @@ -3336,6 +3395,10 @@ address StubGenerator::generate_base64_decodeBlock() { __ BIND(L_finalBit); // Now have 1 to 63 bytes left to decode + // A padded Base64 tail shorter than one complete block is handled by Java. + __ cmpl(length, 4); + __ jcc(Assembler::less, L_bruteForce); + // I was going to let Java take care of the final fragment // however it will repeatedly call this routine for every 4 bytes // of input data, so handle the rest here. @@ -5015,6 +5078,7 @@ void StubGenerator::generate_compiler_stubs() { StubRoutines::x86::_vector_int_mask_cmp_bits = generate_vector_mask(StubId::stubgen_vector_int_mask_cmp_bits_id, 0x0000000100000001); StubRoutines::x86::_vector_short_to_byte_mask = generate_vector_mask(StubId::stubgen_vector_short_to_byte_mask_id, 0x00ff00ff00ff00ff); StubRoutines::x86::_vector_byte_perm_mask = generate_vector_byte_perm_mask(); + StubRoutines::x86::_vector_byte_shift_gfni_matrix = generate_vector_byte_shift_gfni_matrix(); StubRoutines::x86::_vector_int_to_byte_mask = generate_vector_mask(StubId::stubgen_vector_int_to_byte_mask_id, 0x000000ff000000ff); StubRoutines::x86::_vector_int_to_short_mask = generate_vector_mask(StubId::stubgen_vector_int_to_short_mask_id, 0x0000ffff0000ffff); StubRoutines::x86::_vector_32_bit_mask = generate_vector_custom_i32(StubId::stubgen_vector_32_bit_mask_id, Assembler::AVX_512bit, diff --git a/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp b/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp index 7df0c3090f4e..1d7c802d4848 100644 --- a/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp +++ b/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp @@ -104,6 +104,8 @@ class StubGenerator: public StubCodeGenerator { address generate_vector_byte_perm_mask(); + address generate_vector_byte_shift_gfni_matrix(); + address generate_vector_fp_mask(StubId stub_id, int64_t mask); address generate_vector_custom_i32(StubId stub_id, Assembler::AvxVectorLen len, diff --git a/src/hotspot/cpu/x86/vm_version_x86.cpp b/src/hotspot/cpu/x86/vm_version_x86.cpp index 59ee4794b6d2..5f2f2bfa1363 100644 --- a/src/hotspot/cpu/x86/vm_version_x86.cpp +++ b/src/hotspot/cpu/x86/vm_version_x86.cpp @@ -1895,12 +1895,7 @@ void VM_Version::get_processor_features() { } #ifdef COMPILER2 if (FLAG_IS_DEFAULT(UseFPUForSpilling) && supports_sse4_2()) { - // Spilling to FPU registers not beneficial on Haswell and beyond - if (UseAVX > 1) { - FLAG_SET_DEFAULT(UseFPUForSpilling, false); - } else { - FLAG_SET_DEFAULT(UseFPUForSpilling, true); - } + FLAG_SET_DEFAULT(UseFPUForSpilling, true); } #endif } diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index 652280b2c955..6c54ffea6fe8 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -1477,7 +1477,7 @@ source %{ bool castLL_is_imm32(const Node* n) { assert(n->is_CastLL(), "must be a CastLL"); - const TypeLong* t = n->bottom_type()->is_long(); + const TypeLong* t = n->bottom_type()->as_long(); return (t->_lo == min_jlong || Assembler::is_simm32(t->_lo)) && (t->_hi == max_jlong || Assembler::is_simm32(t->_hi)); } @@ -1820,11 +1820,6 @@ int ConstantTable::calculate_table_base_offset() const { return 0; // absolute addressing, no offset } -bool MachConstantBaseNode::requires_postalloc_expand() const { return false; } -void MachConstantBaseNode::postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_) { - ShouldNotReachHere(); -} - void MachConstantBaseNode::emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const { // Empty encoding } @@ -2125,7 +2120,7 @@ uint MachSpillCopyNode::implementation(C2_MacroAssembler* masm, // Self copy, no move return 0; } - if (bottom_type()->isa_vect() != nullptr && bottom_type()->isa_pvectmask() == nullptr) { + if (bottom_type()->is_vect() && !bottom_type()->is_pvectmask()) { uint ireg = ideal_reg(); assert((src_first_rc != rc_int && dst_first_rc != rc_int), "sanity"); assert((ireg == Op_VecS || ireg == Op_VecD || ireg == Op_VecX || ireg == Op_VecY || ireg == Op_VecZ ), "sanity"); @@ -3806,7 +3801,7 @@ bool Matcher::vector_rearrange_requires_load_shuffle(BasicType elem_bt, int vlen bool Matcher::mask_op_prefers_predicate(int opcode, const TypeVect* vt) { // Prefer predicate if the mask type is "TypePVectMask". - return vt->isa_pvectmask() != nullptr; + return vt->is_pvectmask(); } MachOper* Matcher::pd_specialize_generic_vector_operand(MachOper* generic_opnd, uint ideal_reg, bool is_temp) { @@ -3958,7 +3953,7 @@ uint Matcher::vector_ideal_reg(int size) { static bool clone_conv(Node* conv, Matcher* matcher, Matcher::MStack& mstack, VectorSet& address_visited) { if (conv->Opcode() == Op_ConvI2L && - conv->as_Type()->type()->is_long()->_lo >= 0 && + conv->as_Type()->type()->as_long()->_lo >= 0 && // Are there other uses besides address expressions? !matcher->is_visited(conv)) { address_visited.set(conv->_idx); // Flag as address_visited @@ -4996,7 +4991,7 @@ operand immN0() %{ operand immP31() %{ - predicate(n->as_Type()->type()->is_ptr()->reloc() == relocInfo::none + predicate(n->as_Type()->type()->as_ptr()->reloc() == relocInfo::none && (n->get_ptr() >> 31) == 0); match(ConP); @@ -5771,7 +5766,7 @@ operand indIndexScale(any_RegP reg, rRegL lreg, immI2 scale) operand indPosIndexScale(any_RegP reg, rRegI idx, immI2 scale) %{ constraint(ALLOC_IN_RC(ptr_reg)); - predicate(n->in(3)->in(1)->as_Type()->type()->is_long()->_lo >= 0); + predicate(n->in(3)->in(1)->as_Type()->type()->as_long()->_lo >= 0); match(AddP reg (LShiftL (ConvI2L idx) scale)); op_cost(10); @@ -5804,7 +5799,7 @@ operand indIndexScaleOffset(any_RegP reg, immL32 off, rRegL lreg, immI2 scale) operand indPosIndexOffset(any_RegP reg, immL32 off, rRegI idx) %{ constraint(ALLOC_IN_RC(ptr_reg)); - predicate(n->in(2)->in(3)->as_Type()->type()->is_long()->_lo >= 0); + predicate(n->in(2)->in(3)->as_Type()->type()->as_long()->_lo >= 0); match(AddP (AddP reg (ConvI2L idx)) off); op_cost(10); @@ -5821,7 +5816,7 @@ operand indPosIndexOffset(any_RegP reg, immL32 off, rRegI idx) operand indPosIndexScaleOffset(any_RegP reg, immL32 off, rRegI idx, immI2 scale) %{ constraint(ALLOC_IN_RC(ptr_reg)); - predicate(n->in(2)->in(3)->in(1)->as_Type()->type()->is_long()->_lo >= 0); + predicate(n->in(2)->in(3)->in(1)->as_Type()->type()->as_long()->_lo >= 0); match(AddP (AddP reg (LShiftL (ConvI2L idx) scale)) off); op_cost(10); @@ -5988,7 +5983,7 @@ operand indIndexScaleOffsetNarrow(rRegN reg, immL32 off, rRegL lreg, immI2 scale operand indPosIndexOffsetNarrow(rRegN reg, immL32 off, rRegI idx) %{ constraint(ALLOC_IN_RC(ptr_reg)); - predicate(CompressedOops::shift() == 0 && n->in(2)->in(3)->as_Type()->type()->is_long()->_lo >= 0); + predicate(CompressedOops::shift() == 0 && n->in(2)->in(3)->as_Type()->type()->as_long()->_lo >= 0); match(AddP (AddP (DecodeN reg) (ConvI2L idx)) off); op_cost(10); @@ -6005,7 +6000,7 @@ operand indPosIndexOffsetNarrow(rRegN reg, immL32 off, rRegI idx) operand indPosIndexScaleOffsetNarrow(rRegN reg, immL32 off, rRegI idx, immI2 scale) %{ constraint(ALLOC_IN_RC(ptr_reg)); - predicate(CompressedOops::shift() == 0 && n->in(2)->in(3)->in(1)->as_Type()->type()->is_long()->_lo >= 0); + predicate(CompressedOops::shift() == 0 && n->in(2)->in(3)->in(1)->as_Type()->type()->as_long()->_lo >= 0); match(AddP (AddP (DecodeN reg) (LShiftL (ConvI2L idx) scale)) off); op_cost(10); @@ -9091,8 +9086,8 @@ instruct encodeHeapOop_not_null(rRegN dst, rRegP src, rFlagsReg cr) %{ %} instruct decodeHeapOop(rRegP dst, rRegN src, rFlagsReg cr) %{ - predicate(n->bottom_type()->is_ptr()->ptr() != TypePtr::NotNull && - n->bottom_type()->is_ptr()->ptr() != TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() != TypePtr::NotNull && + n->bottom_type()->as_ptr()->ptr() != TypePtr::Constant); match(Set dst (DecodeN src)); effect(KILL cr); format %{ "decode_heap_oop $dst,$src" %} @@ -9108,8 +9103,8 @@ instruct decodeHeapOop(rRegP dst, rRegN src, rFlagsReg cr) %{ %} instruct decodeHeapOop_not_null(rRegP dst, rRegN src, rFlagsReg cr) %{ - predicate(n->bottom_type()->is_ptr()->ptr() == TypePtr::NotNull || - n->bottom_type()->is_ptr()->ptr() == TypePtr::Constant); + predicate(n->bottom_type()->as_ptr()->ptr() == TypePtr::NotNull || + n->bottom_type()->as_ptr()->ptr() == TypePtr::Constant); match(Set dst (DecodeN src)); effect(KILL cr); format %{ "decode_heap_oop_not_null $dst,$src" %} @@ -10300,7 +10295,7 @@ instruct incL_rReg(rRegL dst, immL1 src, rFlagsReg cr) ins_pipe(ialu_reg); %} -instruct incL_rReg_ndd(rRegL dst, rRegI src, immL1 val, rFlagsReg cr) +instruct incL_rReg_ndd(rRegL dst, rRegL src, immL1 val, rFlagsReg cr) %{ predicate(UseAPX && UseIncDec); match(Set dst (AddL src val)); @@ -10490,7 +10485,7 @@ instruct castII_checked(rRegI dst, rFlagsReg cr) effect(KILL cr); format %{ "# cast_checked_II $dst" %} ins_encode %{ - __ verify_int_in_range(_idx, bottom_type()->is_int(), $dst$$Register); + __ verify_int_in_range(_idx, bottom_type()->as_int(), $dst$$Register); %} ins_pipe(pipe_slow); %} @@ -10515,7 +10510,7 @@ instruct castLL_checked_L32(rRegL dst, rFlagsReg cr) effect(KILL cr); format %{ "# cast_checked_LL $dst" %} ins_encode %{ - __ verify_long_in_range(_idx, bottom_type()->is_long(), $dst$$Register, noreg); + __ verify_long_in_range(_idx, bottom_type()->as_long(), $dst$$Register, noreg); %} ins_pipe(pipe_slow); %} @@ -10528,7 +10523,7 @@ instruct castLL_checked(rRegL dst, rRegL tmp, rFlagsReg cr) effect(KILL cr, TEMP tmp); format %{ "# cast_checked_LL $dst\tusing $tmp as TEMP" %} ins_encode %{ - __ verify_long_in_range(_idx, bottom_type()->is_long(), $dst$$Register, $tmp$$Register); + __ verify_long_in_range(_idx, bottom_type()->as_long(), $dst$$Register, $tmp$$Register); %} ins_pipe(pipe_slow); %} @@ -12634,7 +12629,7 @@ instruct rorL_rReg_Var_ndd(rRegL dst, rRegL src, rcx_RegI shift, rFlagsReg cr) //----------------------------- CompressBits/ExpandBits ------------------------ instruct compressBitsL_reg(rRegL dst, rRegL src, rRegL mask) %{ - predicate(n->bottom_type()->isa_long()); + predicate(n->bottom_type()->is_long()); match(Set dst (CompressBits src mask)); format %{ "pextq $dst, $src, $mask\t! parallel bit extract" %} ins_encode %{ @@ -12644,7 +12639,7 @@ instruct compressBitsL_reg(rRegL dst, rRegL src, rRegL mask) %{ %} instruct expandBitsL_reg(rRegL dst, rRegL src, rRegL mask) %{ - predicate(n->bottom_type()->isa_long()); + predicate(n->bottom_type()->is_long()); match(Set dst (ExpandBits src mask)); format %{ "pdepq $dst, $src, $mask\t! parallel bit deposit" %} ins_encode %{ @@ -12654,7 +12649,7 @@ instruct expandBitsL_reg(rRegL dst, rRegL src, rRegL mask) %{ %} instruct compressBitsL_mem(rRegL dst, rRegL src, memory mask) %{ - predicate(n->bottom_type()->isa_long()); + predicate(n->bottom_type()->is_long()); match(Set dst (CompressBits src (LoadL mask))); format %{ "pextq $dst, $src, $mask\t! parallel bit extract" %} ins_encode %{ @@ -12664,7 +12659,7 @@ instruct compressBitsL_mem(rRegL dst, rRegL src, memory mask) %{ %} instruct expandBitsL_mem(rRegL dst, rRegL src, memory mask) %{ - predicate(n->bottom_type()->isa_long()); + predicate(n->bottom_type()->is_long()); match(Set dst (ExpandBits src (LoadL mask))); format %{ "pdepq $dst, $src, $mask\t! parallel bit deposit" %} ins_encode %{ @@ -13179,7 +13174,7 @@ instruct xorI_rReg_im1_ndd(rRegI dst, rRegI src, immI_M1 imm) instruct xorI_rReg_imm(rRegI dst, immI src, rFlagsReg cr) %{ // Strict predicate check to make selection of xorI_rReg_im1 cost agnostic if immI src is -1. - predicate(!UseAPX && n->in(2)->bottom_type()->is_int()->get_con() != -1); + predicate(!UseAPX && n->in(2)->bottom_type()->as_int()->get_con() != -1); match(Set dst (XorI dst src)); effect(KILL cr); flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag); @@ -13194,7 +13189,7 @@ instruct xorI_rReg_imm(rRegI dst, immI src, rFlagsReg cr) instruct xorI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) %{ // Strict predicate check to make selection of xorI_rReg_im1_ndd cost agnostic if immI src2 is -1. - predicate(UseAPX && n->in(2)->bottom_type()->is_int()->get_con() != -1); + predicate(UseAPX && n->in(2)->bottom_type()->as_int()->get_con() != -1); match(Set dst (XorI src1 src2)); effect(KILL cr); flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); @@ -13587,7 +13582,7 @@ instruct orL_rReg_castP2X(rRegL dst, any_RegP src, rFlagsReg cr) %{ ins_pipe(ialu_reg_reg); %} -instruct orL_rReg_castP2X_ndd(rRegL dst, any_RegP src1, any_RegP src2, rFlagsReg cr) %{ +instruct orL_rReg_castP2X_ndd(rRegL dst, rRegL src1, any_RegP src2, rFlagsReg cr) %{ predicate(UseAPX); match(Set dst (OrL src1 (CastP2X src2))); effect(KILL cr); @@ -13766,7 +13761,7 @@ instruct xorL_rReg_im1_ndd(rRegL dst,rRegL src, immL_M1 imm) instruct xorL_rReg_imm(rRegL dst, immL32 src, rFlagsReg cr) %{ // Strict predicate check to make selection of xorL_rReg_im1 cost agnostic if immL32 src is -1. - predicate(!UseAPX && n->in(2)->bottom_type()->is_long()->get_con() != -1L); + predicate(!UseAPX && n->in(2)->bottom_type()->as_long()->get_con() != -1L); match(Set dst (XorL dst src)); effect(KILL cr); flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag); @@ -13781,7 +13776,7 @@ instruct xorL_rReg_imm(rRegL dst, immL32 src, rFlagsReg cr) instruct xorL_rReg_rReg_imm(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) %{ // Strict predicate check to make selection of xorL_rReg_im1_ndd cost agnostic if immL32 src2 is -1. - predicate(UseAPX && n->in(2)->bottom_type()->is_long()->get_con() != -1L); + predicate(UseAPX && n->in(2)->bottom_type()->as_long()->get_con() != -1L); match(Set dst (XorL src1 src2)); effect(KILL cr); flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); @@ -16137,7 +16132,7 @@ instruct compP_rReg_mem(rFlagsRegU cr, rRegP op1, memory op2) // and raw pointers have no anti-dependencies. instruct compP_mem_rReg(rFlagsRegU cr, rRegP op1, memory op2) %{ - predicate(n->in(2)->in(2)->bottom_type()->isa_rawptr() != nullptr && + predicate(n->in(2)->in(2)->bottom_type()->is_rawptr() && n->in(2)->as_Load()->barrier_data() == 0); match(Set cr (CmpP op1 (LoadP op2))); @@ -18032,7 +18027,7 @@ instruct vconvHF2F_reg_reg(vec dst, vec src) %{ // ---------------------------------------- VectorReinterpret ------------------------------------ instruct reinterpret_mask(kReg dst) %{ - predicate(n->bottom_type()->isa_pvectmask() && + predicate(n->bottom_type()->is_pvectmask() && Matcher::vector_length(n) == Matcher::vector_length(n->in(1))); // dst == src match(Set dst (VectorReinterpret dst)); ins_cost(125); @@ -18045,10 +18040,10 @@ instruct reinterpret_mask(kReg dst) %{ instruct reinterpret_mask_W2B(kReg dst, kReg src, vec xtmp) %{ predicate(UseAVX > 2 && Matcher::vector_length(n) != Matcher::vector_length(n->in(1)) && - n->bottom_type()->isa_pvectmask() && - n->in(1)->bottom_type()->isa_pvectmask() && - n->in(1)->bottom_type()->is_pvectmask()->element_basic_type() == T_SHORT && - n->bottom_type()->is_pvectmask()->element_basic_type() == T_BYTE); // dst == src + n->bottom_type()->is_pvectmask() && + n->in(1)->bottom_type()->is_pvectmask() && + n->in(1)->bottom_type()->as_pvectmask()->element_basic_type() == T_SHORT && + n->bottom_type()->as_pvectmask()->element_basic_type() == T_BYTE); // dst == src match(Set dst (VectorReinterpret src)); effect(TEMP xtmp); format %{ "vector_mask_reinterpret_W2B $dst $src\t!" %} @@ -18065,11 +18060,11 @@ instruct reinterpret_mask_W2B(kReg dst, kReg src, vec xtmp) %{ instruct reinterpret_mask_D2B(kReg dst, kReg src, vec xtmp) %{ predicate(UseAVX > 2 && Matcher::vector_length(n) != Matcher::vector_length(n->in(1)) && - n->bottom_type()->isa_pvectmask() && - n->in(1)->bottom_type()->isa_pvectmask() && - (n->in(1)->bottom_type()->is_pvectmask()->element_basic_type() == T_INT || - n->in(1)->bottom_type()->is_pvectmask()->element_basic_type() == T_FLOAT) && - n->bottom_type()->is_pvectmask()->element_basic_type() == T_BYTE); // dst == src + n->bottom_type()->is_pvectmask() && + n->in(1)->bottom_type()->is_pvectmask() && + (n->in(1)->bottom_type()->as_pvectmask()->element_basic_type() == T_INT || + n->in(1)->bottom_type()->as_pvectmask()->element_basic_type() == T_FLOAT) && + n->bottom_type()->as_pvectmask()->element_basic_type() == T_BYTE); // dst == src match(Set dst (VectorReinterpret src)); effect(TEMP xtmp); format %{ "vector_mask_reinterpret_D2B $dst $src\t!" %} @@ -18086,11 +18081,11 @@ instruct reinterpret_mask_D2B(kReg dst, kReg src, vec xtmp) %{ instruct reinterpret_mask_Q2B(kReg dst, kReg src, vec xtmp) %{ predicate(UseAVX > 2 && Matcher::vector_length(n) != Matcher::vector_length(n->in(1)) && - n->bottom_type()->isa_pvectmask() && - n->in(1)->bottom_type()->isa_pvectmask() && - (n->in(1)->bottom_type()->is_pvectmask()->element_basic_type() == T_LONG || - n->in(1)->bottom_type()->is_pvectmask()->element_basic_type() == T_DOUBLE) && - n->bottom_type()->is_pvectmask()->element_basic_type() == T_BYTE); // dst == src + n->bottom_type()->is_pvectmask() && + n->in(1)->bottom_type()->is_pvectmask() && + (n->in(1)->bottom_type()->as_pvectmask()->element_basic_type() == T_LONG || + n->in(1)->bottom_type()->as_pvectmask()->element_basic_type() == T_DOUBLE) && + n->bottom_type()->as_pvectmask()->element_basic_type() == T_BYTE); // dst == src match(Set dst (VectorReinterpret src)); effect(TEMP xtmp); format %{ "vector_mask_reinterpret_Q2B $dst $src\t!" %} @@ -18106,7 +18101,7 @@ instruct reinterpret_mask_Q2B(kReg dst, kReg src, vec xtmp) %{ %} instruct reinterpret(vec dst) %{ - predicate(!n->bottom_type()->isa_pvectmask() && + predicate(!n->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n) == Matcher::vector_length_in_bytes(n->in(1))); // dst == src match(Set dst (VectorReinterpret dst)); ins_cost(125); @@ -18142,7 +18137,7 @@ instruct reinterpret_expand(vec dst, vec src) %{ instruct vreinterpret_expand4(legVec dst, vec src) %{ predicate(UseAVX > 0 && - !n->bottom_type()->isa_pvectmask() && + !n->bottom_type()->is_pvectmask() && (Matcher::vector_length_in_bytes(n->in(1)) == 4) && // src (Matcher::vector_length_in_bytes(n->in(1)) < Matcher::vector_length_in_bytes(n))); // src < dst match(Set dst (VectorReinterpret src)); @@ -18157,7 +18152,7 @@ instruct vreinterpret_expand4(legVec dst, vec src) %{ instruct vreinterpret_expand(legVec dst, vec src) %{ predicate(UseAVX > 0 && - !n->bottom_type()->isa_pvectmask() && + !n->bottom_type()->is_pvectmask() && (Matcher::vector_length_in_bytes(n->in(1)) > 4) && // src (Matcher::vector_length_in_bytes(n->in(1)) < Matcher::vector_length_in_bytes(n))); // src < dst match(Set dst (VectorReinterpret src)); @@ -18175,7 +18170,7 @@ instruct vreinterpret_expand(legVec dst, vec src) %{ %} instruct reinterpret_shrink(vec dst, legVec src) %{ - predicate(!n->bottom_type()->isa_pvectmask() && + predicate(!n->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n->in(1)) > Matcher::vector_length_in_bytes(n)); // src > dst match(Set dst (VectorReinterpret src)); ins_cost(125); @@ -20888,7 +20883,7 @@ instruct copySignD_imm(regD dst, regD src, regD tmp1, rRegL tmp2, immD zero) %{ //----------------------------- CompressBits/ExpandBits ------------------------ instruct compressBitsI_reg(rRegI dst, rRegI src, rRegI mask) %{ - predicate(n->bottom_type()->isa_int()); + predicate(n->bottom_type()->is_int()); match(Set dst (CompressBits src mask)); format %{ "pextl $dst, $src, $mask\t! parallel bit extract" %} ins_encode %{ @@ -20898,7 +20893,7 @@ instruct compressBitsI_reg(rRegI dst, rRegI src, rRegI mask) %{ %} instruct expandBitsI_reg(rRegI dst, rRegI src, rRegI mask) %{ - predicate(n->bottom_type()->isa_int()); + predicate(n->bottom_type()->is_int()); match(Set dst (ExpandBits src mask)); format %{ "pdepl $dst, $src, $mask\t! parallel bit deposit" %} ins_encode %{ @@ -20908,7 +20903,7 @@ instruct expandBitsI_reg(rRegI dst, rRegI src, rRegI mask) %{ %} instruct compressBitsI_mem(rRegI dst, rRegI src, memory mask) %{ - predicate(n->bottom_type()->isa_int()); + predicate(n->bottom_type()->is_int()); match(Set dst (CompressBits src (LoadI mask))); format %{ "pextl $dst, $src, $mask\t! parallel bit extract" %} ins_encode %{ @@ -20918,7 +20913,7 @@ instruct compressBitsI_mem(rRegI dst, rRegI src, memory mask) %{ %} instruct expandBitsI_mem(rRegI dst, rRegI src, memory mask) %{ - predicate(n->bottom_type()->isa_int()); + predicate(n->bottom_type()->is_int()); match(Set dst (ExpandBits src (LoadI mask))); format %{ "pdepl $dst, $src, $mask\t! parallel bit deposit" %} ins_encode %{ @@ -21013,7 +21008,7 @@ instruct vshiftB(vec dst, vec src, vec shift, vec tmp) %{ instruct vshift16B(vec dst, vec src, vec shift, vec tmp1, vec tmp2) %{ predicate(Matcher::vector_length(n) == 16 && !n->as_ShiftV()->is_var_shift() && - UseAVX <= 1); + (UseAVX == 0 || (UseAVX == 1 && !VM_Version::supports_gfni()))); match(Set dst ( LShiftVB src shift)); match(Set dst ( RShiftVB src shift)); match(Set dst (URShiftVB src shift)); @@ -21038,7 +21033,7 @@ instruct vshift16B(vec dst, vec src, vec shift, vec tmp1, vec tmp2) %{ instruct vshift16B_avx(vec dst, vec src, vec shift, vec tmp) %{ predicate(Matcher::vector_length(n) == 16 && !n->as_ShiftV()->is_var_shift() && - UseAVX > 1); + UseAVX > 1 && !VM_Version::supports_gfni()); match(Set dst ( LShiftVB src shift)); match(Set dst ( RShiftVB src shift)); match(Set dst (URShiftVB src shift)); @@ -21058,7 +21053,8 @@ instruct vshift16B_avx(vec dst, vec src, vec shift, vec tmp) %{ %} instruct vshift32B_avx(vec dst, vec src, vec shift, vec tmp) %{ - predicate(Matcher::vector_length(n) == 32 && !n->as_ShiftV()->is_var_shift()); + predicate(Matcher::vector_length(n) == 32 && !n->as_ShiftV()->is_var_shift() && + !VM_Version::supports_gfni()); match(Set dst ( LShiftVB src shift)); match(Set dst ( RShiftVB src shift)); match(Set dst (URShiftVB src shift)); @@ -21083,7 +21079,8 @@ instruct vshift32B_avx(vec dst, vec src, vec shift, vec tmp) %{ %} instruct vshift64B_avx(vec dst, vec src, vec shift, vec tmp1, vec tmp2) %{ - predicate(Matcher::vector_length(n) == 64 && !n->as_ShiftV()->is_var_shift()); + predicate(Matcher::vector_length(n) == 64 && !n->as_ShiftV()->is_var_shift() && + !VM_Version::supports_gfni()); match(Set dst ( LShiftVB src shift)); match(Set dst (RShiftVB src shift)); match(Set dst (URShiftVB src shift)); @@ -21110,6 +21107,24 @@ instruct vshift64B_avx(vec dst, vec src, vec shift, vec tmp1, vec tmp2) %{ ins_pipe( pipe_slow ); %} +instruct vshiftB_gfni(vec dst, vec src, vec shift, rRegL rtmp, rRegL rbase) %{ + predicate(!n->as_ShiftV()->is_var_shift() && + VM_Version::supports_gfni() && UseAVX > 0 && + Matcher::vector_length(n) >= 16); + match(Set dst ( LShiftVB src shift)); + match(Set dst ( RShiftVB src shift)); + match(Set dst (URShiftVB src shift)); + effect(TEMP dst, TEMP rtmp, TEMP rbase); + format %{ "vector_byte_shift_gfni $dst,$src,$shift\t! using $rtmp and $rbase as TEMP" %} + ins_encode %{ + int vlen_enc = vector_length_encoding(this); + __ vshiftb_gfni(this->ideal_Opcode(), + $dst$$XMMRegister, $src$$XMMRegister, $shift$$XMMRegister, + $rtmp$$Register, $rbase$$Register, vlen_enc); + %} + ins_pipe( pipe_slow ); +%} + // Shorts vector logical right shift produces incorrect Java result // for negative data because java code convert short value into int with // sign extension before a shift. But char vectors are fine since chars are @@ -22194,7 +22209,7 @@ instruct vround_reg_evex(vec dst, vec src, rRegP tmp, vec xtmp1, vec xtmp2, kReg // --------------------------------- VectorMaskCmp -------------------------------------- instruct vcmpFD(legVec dst, legVec src1, legVec src2, immI8 cond) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && + predicate(!n->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n->in(1)->in(1)) >= 8 && // src1 Matcher::vector_length_in_bytes(n->in(1)->in(1)) <= 32 && // src1 is_floating_point_type(Matcher::vector_element_basic_type(n->in(1)->in(1)))); // src1 T_FLOAT, T_DOUBLE @@ -22214,7 +22229,7 @@ instruct vcmpFD(legVec dst, legVec src1, legVec src2, immI8 cond) %{ instruct evcmpFD64(vec dst, vec src1, vec src2, immI8 cond, kReg ktmp) %{ predicate(Matcher::vector_length_in_bytes(n->in(1)->in(1)) == 64 && // src1 - n->bottom_type()->isa_pvectmask() == nullptr && + !n->bottom_type()->is_pvectmask() && is_floating_point_type(Matcher::vector_element_basic_type(n->in(1)->in(1)))); // src1 T_FLOAT, T_DOUBLE match(Set dst (VectorMaskCmp (Binary src1 src2) cond)); effect(TEMP ktmp); @@ -22235,12 +22250,12 @@ instruct evcmpFD64(vec dst, vec src1, vec src2, immI8 cond, kReg ktmp) %{ %} instruct evcmpFD(kReg dst, vec src1, vec src2, immI8 cond) %{ - predicate(n->bottom_type()->isa_pvectmask() && + predicate(n->bottom_type()->is_pvectmask() && is_floating_point_type(Matcher::vector_element_basic_type(n->in(1)->in(1)))); // src1 T_FLOAT, T_DOUBLE match(Set dst (VectorMaskCmp (Binary src1 src2) cond)); format %{ "vector_compare_evex $dst,$src1,$src2,$cond\t!" %} ins_encode %{ - assert(bottom_type()->isa_pvectmask(), "TypePVectMask expected"); + assert(bottom_type()->is_pvectmask(), "TypePVectMask expected"); int vlen_enc = vector_length_encoding(this, $src1); Assembler::ComparisonPredicateFP cmp = booltest_pred_to_comparison_pred_fp($cond$$constant); KRegister mask = k0; // The comparison itself is not being masked. @@ -22254,7 +22269,7 @@ instruct evcmpFD(kReg dst, vec src1, vec src2, immI8 cond) %{ %} instruct vcmp_direct(legVec dst, legVec src1, legVec src2, immI8 cond) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && + predicate(!n->bottom_type()->is_pvectmask() && !Matcher::is_unsigned_booltest_pred(n->in(2)->get_int()) && Matcher::vector_length_in_bytes(n->in(1)->in(1)) >= 4 && // src1 Matcher::vector_length_in_bytes(n->in(1)->in(1)) <= 32 && // src1 @@ -22274,7 +22289,7 @@ instruct vcmp_direct(legVec dst, legVec src1, legVec src2, immI8 cond) %{ %} instruct vcmp_negate(legVec dst, legVec src1, legVec src2, immI8 cond, legVec xtmp) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && + predicate(!n->bottom_type()->is_pvectmask() && !Matcher::is_unsigned_booltest_pred(n->in(2)->get_int()) && Matcher::vector_length_in_bytes(n->in(1)->in(1)) >= 4 && // src1 Matcher::vector_length_in_bytes(n->in(1)->in(1)) <= 32 && // src1 @@ -22295,7 +22310,7 @@ instruct vcmp_negate(legVec dst, legVec src1, legVec src2, immI8 cond, legVec xt %} instruct vcmpu(legVec dst, legVec src1, legVec src2, immI8 cond, legVec xtmp) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && + predicate(!n->bottom_type()->is_pvectmask() && Matcher::is_unsigned_booltest_pred(n->in(2)->get_int()) && Matcher::vector_length_in_bytes(n->in(1)->in(1)) >= 4 && // src1 Matcher::vector_length_in_bytes(n->in(1)->in(1)) <= 32 && // src1 @@ -22322,7 +22337,7 @@ instruct vcmpu(legVec dst, legVec src1, legVec src2, immI8 cond, legVec xtmp) %{ %} instruct vcmp64(vec dst, vec src1, vec src2, immI8 cond, kReg ktmp) %{ - predicate((n->bottom_type()->isa_pvectmask() == nullptr && + predicate((!n->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n->in(1)->in(1)) == 64) && // src1 is_integral_type(Matcher::vector_element_basic_type(n->in(1)->in(1)))); // src1 match(Set dst (VectorMaskCmp (Binary src1 src2) cond)); @@ -22357,13 +22372,13 @@ instruct vcmp64(vec dst, vec src1, vec src2, immI8 cond, kReg ktmp) %{ instruct evcmp(kReg dst, vec src1, vec src2, immI8 cond) %{ - predicate(n->bottom_type()->isa_pvectmask() && + predicate(n->bottom_type()->is_pvectmask() && is_integral_type(Matcher::vector_element_basic_type(n->in(1)->in(1)))); // src1 match(Set dst (VectorMaskCmp (Binary src1 src2) cond)); format %{ "vector_compared_evex $dst,$src1,$src2,$cond\t!" %} ins_encode %{ assert(UseAVX > 2, "required"); - assert(bottom_type()->isa_pvectmask(), "TypePVectMask expected"); + assert(bottom_type()->is_pvectmask(), "TypePVectMask expected"); int vlen_enc = vector_length_encoding(this, $src1); Assembler::ComparisonPredicate cmp = booltest_pred_to_comparison_pred($cond$$constant); @@ -22532,7 +22547,7 @@ instruct blendvp(vec dst, vec src, vec mask, rxmm0 tmp) %{ instruct vblendvpI(legVec dst, legVec src1, legVec src2, legVec mask) %{ predicate(UseAVX > 0 && !EnableX86ECoreOpts && - n->in(2)->bottom_type()->isa_pvectmask() == nullptr && + !n->in(2)->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n) <= 32 && is_integral_type(Matcher::vector_element_basic_type(n))); match(Set dst (VectorBlend (Binary src1 src2) mask)); @@ -22546,7 +22561,7 @@ instruct vblendvpI(legVec dst, legVec src1, legVec src2, legVec mask) %{ instruct vblendvpFD(legVec dst, legVec src1, legVec src2, legVec mask) %{ predicate(UseAVX > 0 && !EnableX86ECoreOpts && - n->in(2)->bottom_type()->isa_pvectmask() == nullptr && + !n->in(2)->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n) <= 32 && !is_integral_type(Matcher::vector_element_basic_type(n))); match(Set dst (VectorBlend (Binary src1 src2) mask)); @@ -22560,7 +22575,7 @@ instruct vblendvpFD(legVec dst, legVec src1, legVec src2, legVec mask) %{ instruct vblendvp(legVec dst, legVec src1, legVec src2, legVec mask, legVec vtmp) %{ predicate(UseAVX > 0 && EnableX86ECoreOpts && - n->in(2)->bottom_type()->isa_pvectmask() == nullptr && + !n->in(2)->bottom_type()->is_pvectmask() && Matcher::vector_length_in_bytes(n) <= 32); match(Set dst (VectorBlend (Binary src1 src2) mask)); format %{ "vector_blend $dst,$src1,$src2,$mask\t! using $vtmp as TEMP" %} @@ -22576,7 +22591,7 @@ instruct vblendvp(legVec dst, legVec src1, legVec src2, legVec mask, legVec vtmp instruct evblendvp64(vec dst, vec src1, vec src2, vec mask, kReg ktmp) %{ predicate(Matcher::vector_length_in_bytes(n) == 64 && - n->in(2)->bottom_type()->isa_pvectmask() == nullptr); + !n->in(2)->bottom_type()->is_pvectmask()); match(Set dst (VectorBlend (Binary src1 src2) mask)); format %{ "vector_blend $dst,$src1,$src2,$mask\t! using k2 as TEMP" %} effect(TEMP ktmp); @@ -22591,7 +22606,7 @@ instruct evblendvp64(vec dst, vec src1, vec src2, vec mask, kReg ktmp) %{ instruct evblendvp64_masked(vec dst, vec src1, vec src2, kReg mask) %{ - predicate(n->in(2)->bottom_type()->isa_pvectmask() && + predicate(n->in(2)->bottom_type()->is_pvectmask() && (!is_subword_type(Matcher::vector_element_basic_type(n)) || VM_Version::supports_avx512bw())); match(Set dst (VectorBlend (Binary src1 src2) mask)); @@ -22790,7 +22805,7 @@ instruct ktest_ge8(rFlagsRegU cr, kReg src1, kReg src2) %{ //------------------------------------- LoadMask -------------------------------------------- instruct loadMask(legVec dst, legVec src) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && !VM_Version::supports_avx512vlbw()); + predicate(!n->bottom_type()->is_pvectmask() && !VM_Version::supports_avx512vlbw()); match(Set dst (VectorLoadMask src)); effect(TEMP dst); format %{ "vector_loadmask_byte $dst, $src\n\t" %} @@ -22803,7 +22818,7 @@ instruct loadMask(legVec dst, legVec src) %{ %} instruct loadMask64(kReg dst, vec src, vec xtmp) %{ - predicate(n->bottom_type()->isa_pvectmask() && !VM_Version::supports_avx512vlbw()); + predicate(n->bottom_type()->is_pvectmask() && !VM_Version::supports_avx512vlbw()); match(Set dst (VectorLoadMask src)); effect(TEMP xtmp); format %{ "vector_loadmask_64byte $dst, $src\t! using $xtmp as TEMP" %} @@ -22815,7 +22830,7 @@ instruct loadMask64(kReg dst, vec src, vec xtmp) %{ %} instruct loadMask_evex(kReg dst, vec src, vec xtmp) %{ - predicate(n->bottom_type()->isa_pvectmask() && VM_Version::supports_avx512vlbw()); + predicate(n->bottom_type()->is_pvectmask() && VM_Version::supports_avx512vlbw()); match(Set dst (VectorLoadMask src)); effect(TEMP xtmp); format %{ "vector_loadmask_byte $dst, $src\t! using $xtmp as TEMP" %} @@ -22830,7 +22845,7 @@ instruct loadMask_evex(kReg dst, vec src, vec xtmp) %{ //------------------------------------- StoreMask -------------------------------------------- instruct vstoreMask1B(vec dst, vec src, immI_1 size) %{ - predicate(Matcher::vector_length(n) < 64 && n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(Matcher::vector_length(n) < 64 && !n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorStoreMask src size)); format %{ "vector_store_mask $dst, $src \t! elem size is $size byte[s]" %} ins_encode %{ @@ -22848,7 +22863,7 @@ instruct vstoreMask1B(vec dst, vec src, immI_1 size) %{ %} instruct vstoreMask2B(vec dst, vec src, vec xtmp, immI_2 size) %{ - predicate(Matcher::vector_length(n) <= 16 && n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(Matcher::vector_length(n) <= 16 && !n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorStoreMask src size)); effect(TEMP_DEF dst, TEMP xtmp); format %{ "vector_store_mask $dst, $src \t! elem size is $size byte[s]" %} @@ -22871,7 +22886,7 @@ instruct vstoreMask2B(vec dst, vec src, vec xtmp, immI_2 size) %{ %} instruct vstoreMask4B(vec dst, vec src, vec xtmp, immI_4 size) %{ - predicate(UseAVX <= 2 && Matcher::vector_length(n) <= 8 && n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(UseAVX <= 2 && Matcher::vector_length(n) <= 8 && !n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorStoreMask src size)); format %{ "vector_store_mask $dst, $src \t! elem size is $size byte[s]" %} effect(TEMP_DEF dst, TEMP xtmp); @@ -22931,7 +22946,7 @@ instruct storeMask8B_avx(vec dst, vec src, immI_8 size, vec vtmp) %{ %} instruct vstoreMask4B_evex_novectmask(vec dst, vec src, immI_4 size) %{ - predicate(UseAVX > 2 && n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(UseAVX > 2 && !n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorStoreMask src size)); format %{ "vector_store_mask $dst, $src \t! elem size is $size byte[s]" %} ins_encode %{ @@ -22947,7 +22962,7 @@ instruct vstoreMask4B_evex_novectmask(vec dst, vec src, immI_4 size) %{ %} instruct vstoreMask8B_evex_novectmask(vec dst, vec src, immI_8 size) %{ - predicate(UseAVX > 2 && n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(UseAVX > 2 && !n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorStoreMask src size)); format %{ "vector_store_mask $dst, $src \t! elem size is $size byte[s]" %} ins_encode %{ @@ -22963,7 +22978,7 @@ instruct vstoreMask8B_evex_novectmask(vec dst, vec src, immI_8 size) %{ %} instruct vstoreMask_evex_vectmask(vec dst, kReg mask, immI size) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask() && !VM_Version::supports_avx512vlbw()); + predicate(n->in(1)->bottom_type()->is_pvectmask() && !VM_Version::supports_avx512vlbw()); match(Set dst (VectorStoreMask mask size)); effect(TEMP_DEF dst); format %{ "vector_store_mask $dst, $mask \t! elem size is $size byte[s]" %} @@ -22977,7 +22992,7 @@ instruct vstoreMask_evex_vectmask(vec dst, kReg mask, immI size) %{ %} instruct vstoreMask_evex(vec dst, kReg mask, immI size) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask() && VM_Version::supports_avx512vlbw()); + predicate(n->in(1)->bottom_type()->is_pvectmask() && VM_Version::supports_avx512vlbw()); match(Set dst (VectorStoreMask mask size)); effect(TEMP_DEF dst); format %{ "vector_store_mask $dst, $mask \t! elem size is $size byte[s]" %} @@ -23577,7 +23592,7 @@ instruct vprotate_immI8(vec dst, vec src, immI8 shift) %{ ins_encode %{ int opcode = this->ideal_Opcode(); int vector_len = vector_length_encoding(this); - BasicType etype = this->bottom_type()->is_vect()->element_basic_type(); + BasicType etype = this->bottom_type()->as_vect()->element_basic_type(); __ vprotate_imm(opcode, etype, $dst$$XMMRegister, $src$$XMMRegister, $shift$$constant, vector_len); %} ins_pipe( pipe_slow ); @@ -23590,7 +23605,7 @@ instruct vprorate(vec dst, vec src, vec shift) %{ ins_encode %{ int opcode = this->ideal_Opcode(); int vector_len = vector_length_encoding(this); - BasicType etype = this->bottom_type()->is_vect()->element_basic_type(); + BasicType etype = this->bottom_type()->as_vect()->element_basic_type(); __ vprotate_var(opcode, etype, $dst$$XMMRegister, $src$$XMMRegister, $shift$$XMMRegister, vector_len); %} ins_pipe( pipe_slow ); @@ -23598,11 +23613,11 @@ instruct vprorate(vec dst, vec src, vec shift) %{ // ---------------------------------- Masked Operations ------------------------------------ instruct vmasked_load_avx_non_subword(vec dst, memory mem, vec mask) %{ - predicate(!n->in(3)->bottom_type()->isa_pvectmask()); + predicate(!n->in(3)->bottom_type()->is_pvectmask()); match(Set dst (LoadVectorMasked mem mask)); format %{ "vector_masked_load $dst, $mem, $mask \t! vector masked copy" %} ins_encode %{ - BasicType elmType = this->bottom_type()->is_vect()->element_basic_type(); + BasicType elmType = this->bottom_type()->as_vect()->element_basic_type(); int vlen_enc = vector_length_encoding(this); __ vmovmask(elmType, $dst$$XMMRegister, $mem$$Address, $mask$$XMMRegister, vlen_enc); %} @@ -23611,11 +23626,11 @@ instruct vmasked_load_avx_non_subword(vec dst, memory mem, vec mask) %{ instruct vmasked_load_evex(vec dst, memory mem, kReg mask) %{ - predicate(n->in(3)->bottom_type()->isa_pvectmask()); + predicate(n->in(3)->bottom_type()->is_pvectmask()); match(Set dst (LoadVectorMasked mem mask)); format %{ "vector_masked_load $dst, $mem, $mask \t! vector masked copy" %} ins_encode %{ - BasicType elmType = this->bottom_type()->is_vect()->element_basic_type(); + BasicType elmType = this->bottom_type()->as_vect()->element_basic_type(); int vector_len = vector_length_encoding(this); __ evmovdqu(elmType, $mask$$KRegister, $dst$$XMMRegister, $mem$$Address, false, vector_len); %} @@ -23623,25 +23638,25 @@ instruct vmasked_load_evex(vec dst, memory mem, kReg mask) %{ %} instruct vmasked_store_avx_non_subword(memory mem, vec src, vec mask) %{ - predicate(!n->in(3)->in(2)->bottom_type()->isa_pvectmask()); + predicate(!n->in(3)->in(2)->bottom_type()->is_pvectmask()); match(Set mem (StoreVectorMasked mem (Binary src mask))); format %{ "vector_masked_store $mem, $src, $mask \t! vector masked store" %} ins_encode %{ const MachNode* src_node = static_cast(this->in(this->operand_index($src))); int vlen_enc = vector_length_encoding(src_node); - BasicType elmType = src_node->bottom_type()->is_vect()->element_basic_type(); + BasicType elmType = src_node->bottom_type()->as_vect()->element_basic_type(); __ vmovmask(elmType, $mem$$Address, $src$$XMMRegister, $mask$$XMMRegister, vlen_enc); %} ins_pipe( pipe_slow ); %} instruct vmasked_store_evex(memory mem, vec src, kReg mask) %{ - predicate(n->in(3)->in(2)->bottom_type()->isa_pvectmask()); + predicate(n->in(3)->in(2)->bottom_type()->is_pvectmask()); match(Set mem (StoreVectorMasked mem (Binary src mask))); format %{ "vector_masked_store $mem, $src, $mask \t! vector masked store" %} ins_encode %{ const MachNode* src_node = static_cast(this->in(this->operand_index($src))); - BasicType elmType = src_node->bottom_type()->is_vect()->element_basic_type(); + BasicType elmType = src_node->bottom_type()->as_vect()->element_basic_type(); int vlen_enc = vector_length_encoding(src_node); __ evmovdqu(elmType, $mask$$KRegister, $mem$$Address, $src$$XMMRegister, true, vlen_enc); %} @@ -23715,7 +23730,7 @@ instruct vmask_gen_imm(kReg dst, immL len, rRegL temp) %{ %} instruct vmask_tolong_evex(rRegL dst, kReg mask, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask()); + predicate(n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskToLong mask)); effect(TEMP dst, KILL cr); format %{ "vector_tolong_evex $dst, $mask \t! vector mask tolong" %} @@ -23732,7 +23747,7 @@ instruct vmask_tolong_evex(rRegL dst, kReg mask, rFlagsReg cr) %{ %} instruct vmask_tolong_bool(rRegL dst, vec mask, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskToLong mask)); format %{ "vector_tolong_bool $dst, $mask \t! using $xtmp as TEMP" %} effect(TEMP_DEF dst, TEMP xtmp, KILL cr); @@ -23748,7 +23763,7 @@ instruct vmask_tolong_bool(rRegL dst, vec mask, vec xtmp, rFlagsReg cr) %{ %} instruct vmask_tolong_avx(rRegL dst, vec mask, immI size, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskToLong (VectorStoreMask mask size))); format %{ "vector_tolong_avx $dst, $mask \t! using $xtmp as TEMP" %} effect(TEMP_DEF dst, TEMP xtmp, KILL cr); @@ -23764,7 +23779,7 @@ instruct vmask_tolong_avx(rRegL dst, vec mask, immI size, vec xtmp, rFlagsReg cr %} instruct vmask_truecount_evex(rRegI dst, kReg mask, rRegL tmp, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask()); + predicate(n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskTrueCount mask)); effect(TEMP_DEF dst, TEMP tmp, KILL cr); format %{ "vector_truecount_evex $dst, $mask \t! using $tmp as TEMP" %} @@ -23781,7 +23796,7 @@ instruct vmask_truecount_evex(rRegI dst, kReg mask, rRegL tmp, rFlagsReg cr) %{ %} instruct vmask_truecount_bool(rRegI dst, vec mask, rRegL tmp, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskTrueCount mask)); effect(TEMP_DEF dst, TEMP tmp, TEMP xtmp, KILL cr); format %{ "vector_truecount_bool $dst, $mask \t! using $tmp, $xtmp as TEMP" %} @@ -23797,7 +23812,7 @@ instruct vmask_truecount_bool(rRegI dst, vec mask, rRegL tmp, vec xtmp, rFlagsRe %} instruct vmask_truecount_avx(rRegI dst, vec mask, immI size, rRegL tmp, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskTrueCount (VectorStoreMask mask size))); effect(TEMP_DEF dst, TEMP tmp, TEMP xtmp, KILL cr); format %{ "vector_truecount_avx $dst, $mask \t! using $tmp, $xtmp as TEMP" %} @@ -23813,7 +23828,7 @@ instruct vmask_truecount_avx(rRegI dst, vec mask, immI size, rRegL tmp, vec xtmp %} instruct vmask_first_or_last_true_evex(rRegI dst, kReg mask, rRegL tmp, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask()); + predicate(n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskFirstTrue mask)); match(Set dst (VectorMaskLastTrue mask)); effect(TEMP_DEF dst, TEMP tmp, KILL cr); @@ -23831,7 +23846,7 @@ instruct vmask_first_or_last_true_evex(rRegI dst, kReg mask, rRegL tmp, rFlagsRe %} instruct vmask_first_or_last_true_bool(rRegI dst, vec mask, rRegL tmp, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskFirstTrue mask)); match(Set dst (VectorMaskLastTrue mask)); effect(TEMP_DEF dst, TEMP tmp, TEMP xtmp, KILL cr); @@ -23848,7 +23863,7 @@ instruct vmask_first_or_last_true_bool(rRegI dst, vec mask, rRegL tmp, vec xtmp, %} instruct vmask_first_or_last_true_avx(rRegI dst, vec mask, immI size, rRegL tmp, vec xtmp, rFlagsReg cr) %{ - predicate(n->in(1)->in(1)->bottom_type()->isa_pvectmask() == nullptr); + predicate(!n->in(1)->in(1)->bottom_type()->is_pvectmask()); match(Set dst (VectorMaskFirstTrue (VectorStoreMask mask size))); match(Set dst (VectorMaskLastTrue (VectorStoreMask mask size))); effect(TEMP_DEF dst, TEMP tmp, TEMP xtmp, KILL cr); @@ -23900,7 +23915,7 @@ instruct vcompress_mask_reg_evex(kReg dst, kReg mask, rRegL rtmp1, rRegL rtmp2, effect(TEMP rtmp1, TEMP rtmp2, KILL cr); format %{ "mask_compress_evex $dst, $mask\t! using $rtmp1 and $rtmp2 as TEMP" %} ins_encode %{ - assert(this->in(1)->bottom_type()->isa_pvectmask(), ""); + assert(this->in(1)->bottom_type()->is_pvectmask(), ""); int mask_len = Matcher::vector_length(this); __ vector_mask_compress($dst$$KRegister, $mask$$KRegister, $rtmp1$$Register, $rtmp2$$Register, mask_len); %} @@ -24570,7 +24585,7 @@ instruct evcmp_masked(kReg dst, vec src1, vec src2, immI8 cond, kReg mask) %{ match(Set dst (VectorMaskCmp (Binary src1 src2) (Binary cond mask))); format %{ "vcmp_masked $dst, $src1, $src2, $cond, $mask" %} ins_encode %{ - assert(bottom_type()->isa_pvectmask(), "TypePVectMask expected"); + assert(bottom_type()->is_pvectmask(), "TypePVectMask expected"); int vlen_enc = vector_length_encoding(this, $src1); BasicType src1_elem_bt = Matcher::vector_element_basic_type(this, $src1); @@ -24653,7 +24668,7 @@ instruct mask_not_imm(kReg dst, kReg src, immI_M1 cnt) %{ %} instruct long_to_maskLE8_avx(vec dst, rRegL src, rRegL rtmp1) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && Matcher::vector_length(n) <= 8); + predicate(!n->bottom_type()->is_pvectmask() && Matcher::vector_length(n) <= 8); match(Set dst (VectorLongToMask src)); effect(TEMP dst, TEMP rtmp1); format %{ "long_to_mask_avx $dst, $src\t! using $rtmp1" %} @@ -24668,7 +24683,7 @@ instruct long_to_maskLE8_avx(vec dst, rRegL src, rRegL rtmp1) %{ instruct long_to_maskGT8_avx(vec dst, rRegL src, rRegL rtmp1, rRegL rtmp2, vec xtmp1, rFlagsReg cr) %{ - predicate(n->bottom_type()->isa_pvectmask() == nullptr && Matcher::vector_length(n) > 8); + predicate(!n->bottom_type()->is_pvectmask() && Matcher::vector_length(n) > 8); match(Set dst (VectorLongToMask src)); effect(TEMP dst, TEMP rtmp1, TEMP rtmp2, TEMP xtmp1, KILL cr); format %{ "long_to_mask_avx $dst, $src\t! using $rtmp1, $rtmp2, $xtmp1, as TEMP" %} @@ -24683,7 +24698,7 @@ instruct long_to_maskGT8_avx(vec dst, rRegL src, rRegL rtmp1, rRegL rtmp2, vec x %} instruct long_to_mask_evex(kReg dst, rRegL src) %{ - predicate(n->bottom_type()->isa_pvectmask()); + predicate(n->bottom_type()->is_pvectmask()); match(Set dst (VectorLongToMask src)); format %{ "long_to_mask_evex $dst, $src\t!" %} ins_encode %{ diff --git a/src/hotspot/os/linux/gc/z/zLargePages_linux.cpp b/src/hotspot/os/linux/gc/z/zLargePages_linux.cpp index 76b5b38c5a34..015d764a8a4e 100644 --- a/src/hotspot/os/linux/gc/z/zLargePages_linux.cpp +++ b/src/hotspot/os/linux/gc/z/zLargePages_linux.cpp @@ -27,6 +27,7 @@ #include "os_linux.hpp" #include "runtime/globals.hpp" #include "runtime/globals_extension.hpp" +#include "utilities/align.hpp" #include @@ -61,18 +62,21 @@ bool ZLargePages::pd_collapse(void* addr, size_t bytes) { static bool madv_collapse_available() { const size_t size = 2 * M; - void* const res = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + const size_t chunk_size = 2 * size; + char* const res = (char*)::mmap(nullptr, chunk_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (res == MAP_FAILED) { return false; } + char* const aligned = align_up(res, size); + assert(size >= os::vm_page_size(), "Unexpected page size"); - os::pretouch_memory(res, (void*)(((char*)res) + os::vm_page_size())); + os::pretouch_memory(aligned, aligned + os::vm_page_size()); - const bool result = ZLargePages::pd_collapse(res, size); + const bool result = ZLargePages::pd_collapse(aligned, size); - munmap(res, size); + ::munmap(res, chunk_size); return result; } diff --git a/src/hotspot/os/windows/os_windows.cpp b/src/hotspot/os/windows/os_windows.cpp index 9710d65bfda8..1634c7a89b67 100644 --- a/src/hotspot/os/windows/os_windows.cpp +++ b/src/hotspot/os/windows/os_windows.cpp @@ -5021,6 +5021,7 @@ static WCHAR* get_path_to_target(const wchar_t* wide_path) { if (target_path_size == 0) { DWORD errcode = ::GetLastError(); log_debug(os)("get_path_to_target() failed to GetFinalPathNameByHandleW: GetLastError->%lu.", errcode); + ::CloseHandle(hFile); return nullptr; } @@ -5032,12 +5033,15 @@ static WCHAR* get_path_to_target(const wchar_t* wide_path) { if (res != target_path_size - 1) { DWORD errcode = ::GetLastError(); log_debug(os)("get_path_to_target() failed to GetFinalPathNameByHandleW: GetLastError->%lu.", errcode); + ::CloseHandle(hFile); + FREE_C_HEAP_ARRAY(path_to_target); return nullptr; } if (::CloseHandle(hFile) == 0) { DWORD errcode = ::GetLastError(); log_debug(os)("get_path_to_target() failed to CloseHandle: GetLastError->%lu.", errcode); + FREE_C_HEAP_ARRAY(path_to_target); return nullptr; } diff --git a/src/hotspot/os_cpu/linux_riscv/vm_version_linux_riscv.cpp b/src/hotspot/os_cpu/linux_riscv/vm_version_linux_riscv.cpp index 253b95a342dd..2056644c26d7 100644 --- a/src/hotspot/os_cpu/linux_riscv/vm_version_linux_riscv.cpp +++ b/src/hotspot/os_cpu/linux_riscv/vm_version_linux_riscv.cpp @@ -122,11 +122,11 @@ void VM_Version::RVNonExtFeatureValue::log_enabled() { } void VM_Version::apply_aot_cache_cpu_features() { - RVExtFeatures* archived_cpu_features = (RVExtFeatures*)get_aot_cache_cpu_features(); + RVExtFeatureSet* archived_cpu_features = (RVExtFeatureSet*)get_aot_cache_cpu_features(); if (archived_cpu_features != nullptr) { assert(is_aligned(archived_cpu_features, cpu_features_alignment()), "sanity check"); assert(UseAOTCacheCpuFeaturesOnly, "UseAOTCacheCpuFeaturesOnly must be true"); - RVExtFeatures* runtime_cpu_features = RVExtFeatures::current(); + RVExtFeatureSet* runtime_cpu_features = RVExtFeatureSet::current(); if (!runtime_cpu_features->super_set_of(archived_cpu_features)) { if (!FLAG_IS_DEFAULT(UseAOTCacheCpuFeaturesOnly)) { warning("UseAOTCacheCpuFeaturesOnly is ignored: one or more cpu features recorded in AOT cache are not supported by this CPU"); @@ -136,11 +136,11 @@ void VM_Version::apply_aot_cache_cpu_features() { } _rv_ext_features_disabled_by_aot_cache = runtime_cpu_features->features_not_in(archived_cpu_features); // Undetected extensions can still have flags enabled by command-line options or RVA profiles. - for (int i = 0; i < RVExtFeatures::MAX_CPU_FEATURE_INDEX; i++) { + for (int i = 0; i < RVExtFeatureSet::CPU_FEATURE_COUNT; i++) { if (!archived_cpu_features->support_feature(i)) { - _feature_list[i]->disable_feature(); + _ext_feature_list[i]->disable_feature(); // Normal flag initialization skips disabled extensions. - _feature_list[i]->update_flag(); + _ext_feature_list[i]->update_flag(); } } @@ -176,7 +176,7 @@ void VM_Version::setup_cpu_available_features() { vendor_features(); // Linux kernel require Zifencei - if (!ext_Zifencei.enabled()) { + if (!ext_Zifencei.feature_enabled()) { log_info(os, cpu)("Zifencei not found, required by Linux, enabling."); ext_Zifencei.enable_feature(); } @@ -195,13 +195,15 @@ void VM_Version::setup_cpu_available_features() { strcat(buf, "rv64"); int i = 0; while (_feature_list[i] != nullptr) { - if (_feature_list[i]->enabled()) { - // Change flag default - _feature_list[i]->update_flag(); + if (_feature_list[i]->feature_enabled()) { + if (i < RVExtFeatureSet::CPU_FEATURE_COUNT) { + assert(_ext_feature_list[i] == _feature_list[i], "feature lists must have the same extension order"); + _ext_feature_list[i]->update_flag(); + } // Feature will be disabled by update_flag() if flag // is set to false by the user on the command line. - if (!_feature_list[i]->enabled()) { + if (!_feature_list[i]->feature_enabled()) { continue; } @@ -341,7 +343,7 @@ char* VM_Version::os_uarch_additional_features() { } void VM_Version::vendor_features() { - if (!mvendorid.enabled()) { + if (!mvendorid.feature_enabled()) { return; } switch (mvendorid.value()) { @@ -387,7 +389,7 @@ void VM_Version::rivos_features() { } void VM_Version::xuantie_features() { - if (!marchid.enabled()) { + if (!marchid.feature_enabled()) { return; } diff --git a/src/hotspot/share/adlc/output_c.cpp b/src/hotspot/share/adlc/output_c.cpp index 6adff64b456f..ea9d069f1d59 100644 --- a/src/hotspot/share/adlc/output_c.cpp +++ b/src/hotspot/share/adlc/output_c.cpp @@ -3751,11 +3751,11 @@ static void path_to_constant(FILE *fp, FormDict &globals, if ( strcmp(optype,"ConI") == 0 ) { fprintf(fp, "_leaf->get_int()"); } else if ( (strcmp(optype,"ConP") == 0) ) { - fprintf(fp, "_leaf->bottom_type()->is_ptr()"); + fprintf(fp, "_leaf->bottom_type()->as_ptr()"); } else if ( (strcmp(optype,"ConN") == 0) ) { - fprintf(fp, "_leaf->bottom_type()->is_narrowoop()"); + fprintf(fp, "_leaf->bottom_type()->as_narrowoop()"); } else if ( (strcmp(optype,"ConNKlass") == 0) ) { - fprintf(fp, "_leaf->bottom_type()->is_narrowklass()"); + fprintf(fp, "_leaf->bottom_type()->as_narrowklass()"); } else if ( (strcmp(optype,"ConH") == 0) ) { fprintf(fp, "_leaf->geth()"); } else if ( (strcmp(optype,"ConF") == 0) ) { diff --git a/src/hotspot/share/c1/c1_GraphBuilder.cpp b/src/hotspot/share/c1/c1_GraphBuilder.cpp index 5e46b52ad594..60a5ca5f41b6 100644 --- a/src/hotspot/share/c1/c1_GraphBuilder.cpp +++ b/src/hotspot/share/c1/c1_GraphBuilder.cpp @@ -737,6 +737,20 @@ class MemoryBuffer: public CompilationResourceObj { } }; +class MemoryEffects: public ValueNumberingVisitor { + private: + MemoryBuffer* _mem; + + protected: + void kill_memory() override { _mem->kill(); } + // Because we only care about memory effects the rest are noops. + void kill_field(ciField* field, bool all_offsets) override { return; } + void kill_array(ValueType* type) override { return; } + + public: + explicit MemoryEffects(MemoryBuffer* mem): _mem(mem) {} +}; + // Implementation of GraphBuilder's ScopeData @@ -2673,13 +2687,11 @@ void GraphBuilder::monitorenter(Value x, int bci) { // save state before locking in case of deoptimization after a NullPointerException ValueStack* state_before = copy_state_for_exception_with_bci(bci); append_with_bci(new MonitorEnter(x, state()->lock(x), state_before, maybe_valuetype), bci); - kill_all(); } void GraphBuilder::monitorexit(Value x, int bci) { append_with_bci(new MonitorExit(x, state()->unlock()), bci); - kill_all(); } @@ -2709,6 +2721,13 @@ void GraphBuilder::throw_op(int bci) { Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) { + if (EliminateFieldAccess) { + // We must kill memory for operations with memory side effects + // before we canonicalize the instruction. + MemoryEffects mem_effects(_memory); + instr->visit(&mem_effects); + } + Canonicalizer canon(compilation(), instr, bci); Instruction* i1 = canon.canonical(); if (i1->is_linked() || !i1->can_be_linked()) { @@ -2754,12 +2773,6 @@ Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) { // save state after modification of operand stack for StateSplit instructions StateSplit* s = i1->as_StateSplit(); if (s != nullptr) { - if (EliminateFieldAccess) { - Intrinsic* intrinsic = s->as_Intrinsic(); - if (s->as_Invoke() != nullptr || (intrinsic && !intrinsic->preserves_state())) { - _memory->kill(); - } - } s->set_state(state()->copy(ValueStack::StateAfter, canon.bci())); } @@ -4748,7 +4761,6 @@ void GraphBuilder::append_unsafe_put(ciMethod* callee, BasicType t, bool is_vola } Instruction* op = append(new UnsafePut(t, args->at(1), offset, val, is_volatile)); compilation()->set_has_unsafe_access(true); - kill_all(); } void GraphBuilder::append_unsafe_CAS(ciMethod* callee) { @@ -4904,7 +4916,6 @@ void GraphBuilder::append_unsafe_get_and_set(ciMethod* callee, bool is_add) { #endif Instruction* op = append(new UnsafeGetAndSet(t, args->at(1), offset, args->at(3), is_add)); compilation()->set_has_unsafe_access(true); - kill_all(); push(op->type(), op); } diff --git a/src/hotspot/share/c1/c1_LIRGenerator.cpp b/src/hotspot/share/c1/c1_LIRGenerator.cpp index e6d5b490d07b..e200e05f8d39 100644 --- a/src/hotspot/share/c1/c1_LIRGenerator.cpp +++ b/src/hotspot/share/c1/c1_LIRGenerator.cpp @@ -2229,7 +2229,7 @@ void LIRGenerator::do_LoadField(LoadField* x) { // Copy the payload to the buffer assert(buffer != nullptr, "buffer required"); LIRItem dest(buffer, this); - access_store_at(decorators, bt, dest, LIR_OprFact::intConst(vk->payload_offset()), payload); + access_store_at(decorators, bt, dest, LIR_OprFact::intConst(vk->payload_offset()), payload, nullptr, nullptr, vk); if (field->is_null_free()) { set_result(x, buffer->operand()); diff --git a/src/hotspot/share/c1/c1_ValueMap.hpp b/src/hotspot/share/c1/c1_ValueMap.hpp index d5c26e28ff38..2a5235bae43d 100644 --- a/src/hotspot/share/c1/c1_ValueMap.hpp +++ b/src/hotspot/share/c1/c1_ValueMap.hpp @@ -198,10 +198,11 @@ class ValueNumberingVisitor: public InstructionVisitor { } } void do_NewTypeArray (NewTypeArray* x) { /* nothing to do */ } - void do_NewObjectArray (NewObjectArray* x) { /* nothing to do */ } - void do_NewMultiArray (NewMultiArray* x) { /* nothing to do */ } - void do_CheckCast (CheckCast* x) { /* nothing to do */ } - void do_InstanceOf (InstanceOf* x) { /* nothing to do */ } + // The following four operations can trigger class loading and thus side-effects in class loaders. + void do_NewObjectArray (NewObjectArray* x) { kill_memory(); } + void do_NewMultiArray (NewMultiArray* x) { kill_memory(); } + void do_InstanceOf (InstanceOf* x) { kill_memory(); } + void do_CheckCast (CheckCast* x) { kill_memory(); } void do_BlockBegin (BlockBegin* x) { /* nothing to do */ } void do_Goto (Goto* x) { /* nothing to do */ } void do_If (If* x) { /* nothing to do */ } diff --git a/src/hotspot/share/cds/aotClassLocation.cpp b/src/hotspot/share/cds/aotClassLocation.cpp index 4ed81459e57f..d5d05e8bcad0 100644 --- a/src/hotspot/share/cds/aotClassLocation.cpp +++ b/src/hotspot/share/cds/aotClassLocation.cpp @@ -45,6 +45,7 @@ #include "runtime/handles.inline.hpp" #include "utilities/classpathStream.hpp" #include "utilities/formatBuffer.hpp" +#include "utilities/resizableHashTable.hpp" #include "utilities/stringUtils.hpp" #include @@ -467,6 +468,67 @@ bool AOTClassLocation::check(const char* runtime_path, bool has_aot_linked_class return true; } +inline unsigned cstring_hash(const char* const& s) { + return java_lang_String::hash_code((const jbyte*)s, checked_cast(strlen(s))); +} + +inline bool cstring_equals(const char* const& a, const char* const& b) { + return strcmp(a, b) == 0; +} + +typedef ResizeableHashTable AOTClassLocationIndexHashtableBase; + +class AOTClassLocationIndexHashtable: public AOTClassLocationIndexHashtableBase { +public: + AOTClassLocationIndexHashtable(bool is_named_module) : AOTClassLocationIndexHashtableBase(/*min*/107, /*max*/4049) { + AOTClassLocationConfig::dumptime_iterate([&] (AOTClassLocation* cl) { + if (!cl->is_modules_image() && cl->from_module_path() == is_named_module) { + int i = cl->index(); + assert(i > 0, "module image is always at index 0"); + ResourceMark rm; + const char* canon_path = ClassLoader::get_canonical_path(cl->path(), JavaThread::current()); // resource allocated + if (canon_path != nullptr) { // invalid paths are ignored + const char* canon_path_dup = os::strdup(canon_path, mtClassShared); + bool created; + put_if_absent(canon_path_dup, i, &created); + if (!created) { + // If the exact same path appears more than once, only the first one is recorded. + os::free((void*)canon_path_dup); + } + } + } + return true; // Keep iterating + }); + } +}; + +// We need to use two tables as the same pathname can appear in both Group::MODULE_PATH, and +// Group::{BOOT_CLASSPATH,APP_CLASSPATH}. If a class is defined in a named module, we must use +// its index from _named_module_table, and vice versa. +static AOTClassLocationIndexHashtable* _named_module_table = nullptr; // MODULE_PATH +static AOTClassLocationIndexHashtable* _unnamed_module_table = nullptr; // BOOT_CLASSPATH + APP_CLASSPATH + +int AOTClassLocationConfig::dumptime_get_class_location_index(const char* path, bool is_named_module) { + assert(CDSConfig::is_dumping_archive(), ""); + + // The `ClassFileStream::source` computed by the Java class loader code may not have the exact same + // output as ClassLoader::get_canonical_path(). E.g., when the source is a directory, the Java + // code would append a trailing "/" character, while the C code doesn't. To be safe, always + // canonicalize again with the C code. + ResourceMark rm; + const char* canon_path = ClassLoader::get_canonical_path(path, JavaThread::current()); + if (canon_path != nullptr) { + int* saved = is_named_module ? + _named_module_table->get(canon_path) : _unnamed_module_table->get(canon_path); + if (saved != nullptr) { + return *saved; + } + } + + return -1; +} + void AOTClassLocationConfig::dumptime_init(JavaThread* current) { assert(CDSConfig::is_dumping_archive(), ""); _dumptime_instance = NEW_C_HEAP_OBJ(AOTClassLocationConfig, mtClassShared); @@ -484,6 +546,9 @@ void AOTClassLocationConfig::dumptime_init(JavaThread* current) { // the AOT config file, so we don't go through ClassLoader::record_result(). dumptime_update_max_used_index(runtime()->_max_used_index); // Same value as recorded in the training run. } + + _named_module_table = new (mtClassShared)AOTClassLocationIndexHashtable(true); + _unnamed_module_table = new (mtClassShared)AOTClassLocationIndexHashtable(false); } void AOTClassLocationConfig::dumptime_init_helper(TRAPS) { diff --git a/src/hotspot/share/cds/aotClassLocation.hpp b/src/hotspot/share/cds/aotClassLocation.hpp index c9dfbfaba818..03873b8c1c69 100644 --- a/src/hotspot/share/cds/aotClassLocation.hpp +++ b/src/hotspot/share/cds/aotClassLocation.hpp @@ -282,6 +282,7 @@ class AOTClassLocationConfig : public CHeapObj { template static void dumptime_iterate(FUNC func) { _dumptime_instance->dumptime_iterate_helper(func); } + static int dumptime_get_class_location_index(const char* path, bool is_named_module); AOTClassLocationConfig* write_to_archive() const; diff --git a/src/hotspot/share/cds/aotMapLogger.cpp b/src/hotspot/share/cds/aotMapLogger.cpp index 04f84ef93690..305c112cf4b5 100644 --- a/src/hotspot/share/cds/aotMapLogger.cpp +++ b/src/hotspot/share/cds/aotMapLogger.cpp @@ -433,9 +433,6 @@ void AOTMapLogger::log_metaspace_objects_impl(address region_base, address regio case MetaspaceClosureType::MethodType: log_method((Method*)src, requested_addr, type_name, bytes, current); break; - case MetaspaceClosureType::MethodCountersType: - log_method_counters((MethodCounters*)src, requested_addr, type_name, bytes, current); - break; case MetaspaceClosureType::MethodDataType: log_method_data((MethodData*)src, requested_addr, type_name, bytes, current); break; @@ -507,12 +504,6 @@ void AOTMapLogger::log_const_method(ConstMethod* cm, address requested_addr, con log_debug(aot, map)(_LOG_PREFIX " %s", p2i(requested_addr), type_name, bytes, cm->method()->external_name()); } -void AOTMapLogger::log_method_counters(MethodCounters* mc, address requested_addr, const char* type_name, - int bytes, Thread* current) { - ResourceMark rm(current); - log_debug(aot, map)(_LOG_PREFIX " %s", p2i(requested_addr), type_name, bytes, mc->method()->external_name()); -} - void AOTMapLogger::log_method_data(MethodData* md, address requested_addr, const char* type_name, int bytes, Thread* current) { ResourceMark rm(current); diff --git a/src/hotspot/share/cds/aotMapLogger.hpp b/src/hotspot/share/cds/aotMapLogger.hpp index aab32fbfe175..ee0f29187a68 100644 --- a/src/hotspot/share/cds/aotMapLogger.hpp +++ b/src/hotspot/share/cds/aotMapLogger.hpp @@ -150,8 +150,6 @@ class AOTMapLogger : AllStatic { static void log_constant_pool_cache(ConstantPoolCache* cpc, address requested_addr, const char* type_name, int bytes, Thread* current); static void log_const_method(ConstMethod* cm, address requested_addr, const char* type_name, int bytes, Thread* current); - static void log_method_counters(MethodCounters* mc, address requested_addr, const char* type_name, int bytes, - Thread* current); static void log_method_data(MethodData* md, address requested_addr, const char* type_name, int bytes, Thread* current); static void log_klass(Klass* k, address requested_addr, const char* type_name, int bytes, Thread* current); diff --git a/src/hotspot/share/cds/aotMetaspace.cpp b/src/hotspot/share/cds/aotMetaspace.cpp index a5d6c563a7b0..d8a895555b06 100644 --- a/src/hotspot/share/cds/aotMetaspace.cpp +++ b/src/hotspot/share/cds/aotMetaspace.cpp @@ -1722,13 +1722,14 @@ MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMap return MAP_ARCHIVE_MMAP_FAILURE; } - PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { - // For product build only -- this is for benchmarking the cost of doing relocation. - // For debug builds, the check is done below, after reserving the space, for better test coverage - // (see comment below). + if (ArchiveRelocationMode == 1 && use_requested_addr) { + if (AOTStressArchiveUnmapping) { + aot_log_info(aot)("Map at requested address to stress test unmapping"); + } else { aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); return MAP_ARCHIVE_MMAP_FAILURE; - }); + } + } if (ArchiveRelocationMode == 2 && !use_requested_addr) { aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); @@ -1841,19 +1842,18 @@ MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMap MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; - DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { - // This is for simulating mmap failures at the requested address. In - // debug builds, we do it here (after all archives have possibly been - // mapped), so we can thoroughly test the code for failure handling - // (releasing all allocated resource, etc). - aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); + if (ArchiveRelocationMode == 1 && use_requested_addr && AOTStressArchiveUnmapping) { + // This is for simulating mmap failures at the requested address. We do it here + // (after all archives have possibly been mapped), so we can thoroughly test the + // code for failure handling (releasing all allocated resource, etc). + aot_log_info(aot)("Simulate mapping failure to stress test unmapping"); if (static_result == MAP_ARCHIVE_SUCCESS) { static_result = MAP_ARCHIVE_MMAP_FAILURE; } if (dynamic_result == MAP_ARCHIVE_SUCCESS) { dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; } - }); + } if (static_result == MAP_ARCHIVE_SUCCESS) { if (dynamic_result == MAP_ARCHIVE_SUCCESS) { diff --git a/src/hotspot/share/cds/aotSystemDictionary.cpp b/src/hotspot/share/cds/aotSystemDictionary.cpp index a7631cb32214..a2654d820175 100644 --- a/src/hotspot/share/cds/aotSystemDictionary.cpp +++ b/src/hotspot/share/cds/aotSystemDictionary.cpp @@ -724,19 +724,12 @@ InstanceKlass* AOTSystemDictionary::get_unregistered_class(Symbol* name) { return k != nullptr ? *k : nullptr; } -void AOTSystemDictionary::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) { +void AOTSystemDictionary::copy_unregistered_class_size_and_crc32(InstanceKlass* klass, DumpTimeClassInfo* dt_info) { precond(CDSConfig::is_dumping_with_input_archive()); precond(klass->in_aot_cache()); - - // A shared class must have a RunTimeClassInfo record - const RunTimeClassInfo* record = find_record(&_info_for_static_archive._unregistered_dictionary, - nullptr, klass->name()); - precond(record != nullptr); - precond(record->klass() == klass); - - DumpTimeClassInfo* info = get_info(klass); - info->_clsfile_size = record->crc()->_clsfile_size; - info->_clsfile_crc32 = record->crc()->_clsfile_crc32; + const RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); + dt_info->_clsfile_size = rt_info->crc()->_clsfile_size; + dt_info->_clsfile_crc32 = rt_info->crc()->_clsfile_crc32; } void AOTSystemDictionary::copy_unregistered_classes_for_retraining(JavaThread* current) { @@ -758,10 +751,10 @@ void AOTSystemDictionary::copy_unregistered_classes_for_retraining(JavaThread* c void AOTSystemDictionary::copy_unregistered_class(JavaThread* current, InstanceKlass* k) { precond(k->in_aot_cache()); precond(CDSConfig::is_dumping_with_input_archive()); - init_dumptime_info(k); + DumpTimeClassInfo* info = init_dumptime_info(k); bool added = add_unregistered_class(current, k); assert(added, "must not have duplicates"); - copy_unregistered_class_size_and_crc32(k); + copy_unregistered_class_size_and_crc32(k, info); copy_verification_info_from_input_archive(k); copy_linking_constraints_from_input_archive(k); } @@ -784,13 +777,14 @@ void AOTSystemDictionary::initialize() { } } -void AOTSystemDictionary::init_dumptime_info(InstanceKlass* k) { +DumpTimeClassInfo* AOTSystemDictionary::init_dumptime_info(InstanceKlass* k) { MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); assert(AOTSystemDictionary::class_loading_may_happen(), "sanity"); DumpTimeClassInfo* info = _dumptime_table->allocate_info(k); if (AOTClassFilter::is_aot_tooling_class(k)) { info->set_is_aot_tooling_class(); } + return info; } void AOTSystemDictionary::remove_dumptime_info(InstanceKlass* k) { diff --git a/src/hotspot/share/cds/aotSystemDictionary.hpp b/src/hotspot/share/cds/aotSystemDictionary.hpp index d1098c076c03..62c7fdc33348 100644 --- a/src/hotspot/share/cds/aotSystemDictionary.hpp +++ b/src/hotspot/share/cds/aotSystemDictionary.hpp @@ -230,7 +230,7 @@ class AOTSystemDictionary: public SystemDictionary { Symbol* super_name, bool is_superclass); static void initialize() NOT_CDS_RETURN; - static void init_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN; + static DumpTimeClassInfo* init_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN_(nullptr); static void init_dumptime_info_from_input_archive(InstanceKlass* k) NOT_CDS_RETURN; static void handle_class_unloading(InstanceKlass* k) NOT_CDS_RETURN; @@ -274,7 +274,7 @@ class AOTSystemDictionary: public SystemDictionary { } static bool add_unregistered_class(Thread* current, InstanceKlass* k); static InstanceKlass* get_unregistered_class(Symbol* name); - static void copy_unregistered_class_size_and_crc32(InstanceKlass* klass); + static void copy_unregistered_class_size_and_crc32(InstanceKlass* klass, DumpTimeClassInfo* dt_info); static void copy_unregistered_classes_for_retraining(JavaThread* current); static void copy_unregistered_class(JavaThread* current, InstanceKlass* k); diff --git a/src/hotspot/share/cds/archiveBuilder.cpp b/src/hotspot/share/cds/archiveBuilder.cpp index 0f7472d2c56c..b990e074e50e 100644 --- a/src/hotspot/share/cds/archiveBuilder.cpp +++ b/src/hotspot/share/cds/archiveBuilder.cpp @@ -547,8 +547,9 @@ ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(obj)) { // Don't dump existing shared metadata again. return point_to_it; + } else if (ref->type() == MetaspaceClosureType::MethodCountersType) { + return set_to_null; } else if (ref->type() == MetaspaceClosureType::MethodDataType || - ref->type() == MetaspaceClosureType::MethodCountersType || ref->type() == MetaspaceClosureType::KlassTrainingDataType || ref->type() == MetaspaceClosureType::MethodTrainingDataType || ref->type() == MetaspaceClosureType::CompileTrainingDataType) { @@ -963,9 +964,6 @@ void ArchiveBuilder::make_training_data_shareable() { } else if (info.type() == MetaspaceClosureType::MethodDataType) { MethodData* buffered_mdo = (MethodData*)info.buffered_addr(); buffered_mdo->remove_unshareable_info(); - } else if (info.type() == MetaspaceClosureType::MethodCountersType) { - MethodCounters* buffered_mc = (MethodCounters*)info.buffered_addr(); - buffered_mc->remove_unshareable_info(); } }; _src_obj_table.iterate_all(clean_td); diff --git a/src/hotspot/share/cds/cdsConfig.cpp b/src/hotspot/share/cds/cdsConfig.cpp index b23850c86437..f9041de97591 100644 --- a/src/hotspot/share/cds/cdsConfig.cpp +++ b/src/hotspot/share/cds/cdsConfig.cpp @@ -509,7 +509,7 @@ void CDSConfig::check_aotmode_off() { void CDSConfig::check_aotmode_auto_or_on() { if (AOTMode != nullptr && strcmp(AOTMode, "on") == 0) { - warning("Option -XX:AOTMode-on was deprecated in version 28 and will likely be " + warning("Option -XX:AOTMode=on was deprecated in version 28 and will likely be " "removed in a future release. Use option -XX:AOTMode=required instead."); } diff --git a/src/hotspot/share/cds/cdsHeapVerifier.cpp b/src/hotspot/share/cds/cdsHeapVerifier.cpp index c90a0aa4ce0b..e73bd5437c90 100644 --- a/src/hotspot/share/cds/cdsHeapVerifier.cpp +++ b/src/hotspot/share/cds/cdsHeapVerifier.cpp @@ -170,7 +170,8 @@ CDSHeapVerifier::CDSHeapVerifier() : _archived_objs(0), _problems(0) if (CDSConfig::is_dumping_aot_linked_classes()) { add_shared_secret_accessors(); } - ClassLoaderDataGraph::classes_do(this); + + ClassLoaderDataGraph::loaded_classes_do_keepalive(this); } // We allow only "stateless" accessors in the SharedSecrets class to be AOT-initialized, for example, diff --git a/src/hotspot/share/cds/cds_globals.hpp b/src/hotspot/share/cds/cds_globals.hpp index dad475030c12..d8b72ab193b4 100644 --- a/src/hotspot/share/cds/cds_globals.hpp +++ b/src/hotspot/share/cds/cds_globals.hpp @@ -99,6 +99,11 @@ "do not map the archive") \ range(0, 2) \ \ + product(bool, AOTStressArchiveUnmapping, false, DIAGNOSTIC, \ + "Iff ArchiveRelocationMode is 1, always map the archive at " \ + "the preferred address, unmap it, and then map at alternative " \ + "address") \ + \ /*========== New "AOT" flags =========================================*/ \ /* The following 3 flags are aliases of -Xshare:dump, */ \ /* -XX:SharedArchiveFile=..., etc. See CDSConfig::check_flag_aliases()*/ \ diff --git a/src/hotspot/share/cds/filemap.cpp b/src/hotspot/share/cds/filemap.cpp index ef17417ffea9..25d45d3c1af4 100644 --- a/src/hotspot/share/cds/filemap.cpp +++ b/src/hotspot/share/cds/filemap.cpp @@ -87,63 +87,70 @@ #define O_BINARY 0 // otherwise do nothing. #endif -inline void CDSMustMatchFlags::do_print(outputStream* st, bool v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, bool v) { st->print("%s", v ? "true" : "false"); } #ifdef _LP64 -inline void CDSMustMatchFlags::do_print(outputStream* st, uint v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, uint v) { st->print("%u", v); } -inline void CDSMustMatchFlags::do_print(outputStream* st, int v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, int v) { st->print("%d", v); } #endif -inline void CDSMustMatchFlags::do_print(outputStream* st, intx v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, intx v) { st->print("%zd", v); } -inline void CDSMustMatchFlags::do_print(outputStream* st, uintx v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, uintx v) { st->print("%zu", v); } -inline void CDSMustMatchFlags::do_print(outputStream* st, double v) { +inline void AOTMustMatchFlags::do_print(outputStream* st, double v) { st->print("%f", v); } -void CDSMustMatchFlags::init() { +void AOTMustMatchFlags::init() { assert(CDSConfig::is_dumping_archive(), "sanity"); - _max_name_width = 0; - -#define INIT_CDS_MUST_MATCH_FLAG(n) \ - _v_##n = n; \ - _max_name_width = MAX2(_max_name_width,strlen(#n)); - CDS_MUST_MATCH_FLAGS_DO(INIT_CDS_MUST_MATCH_FLAG); -#undef INIT_CDS_MUST_MATCH_FLAG -} - -bool CDSMustMatchFlags::runtime_check() const { -#define CHECK_CDS_MUST_MATCH_FLAG(n) \ - if (_v_##n != n) { \ - ResourceMark rm; \ - stringStream ss; \ - ss.print("VM option %s is different between dumptime (", #n); \ - do_print(&ss, _v_ ## n); \ - ss.print(") and runtime ("); \ - do_print(&ss, n); \ - ss.print(")"); \ - aot_log_info(aot)("%s", ss.as_string()); \ + +#define INIT_AOT_MUST_MATCH_FLAG(n) \ + _v_##n = n; + AOT_MUST_MATCH_FLAGS_DO(INIT_AOT_MUST_MATCH_FLAG); +#undef INIT_AOT_MUST_MATCH_FLAG +} + +template +bool AOTMustMatchFlags::check_flag(T saved, T actual, const char* name) { + if (saved != actual) { + ResourceMark rm; + stringStream ss; + ss.print("The %s's %s setting (", CDSConfig::type_of_archive_being_loaded(), name); + do_print(&ss, saved); + ss.print(") does not equal the current setting ("); + do_print(&ss, actual); + ss.print(")"); + AOTMetaspace::report_loading_error("%s", ss.as_string()); + return false; + } else { + return true; + } +} + +bool AOTMustMatchFlags::runtime_check() const { +#define CHECK_AOT_MUST_MATCH_FLAG(n) \ + if (!check_flag(_v_##n, n, #n)) { \ return false; \ } - CDS_MUST_MATCH_FLAGS_DO(CHECK_CDS_MUST_MATCH_FLAG); -#undef CHECK_CDS_MUST_MATCH_FLAG + AOT_MUST_MATCH_FLAGS_DO(CHECK_AOT_MUST_MATCH_FLAG); +#undef CHECK_AOT_MUST_MATCH_FLAG return true; } -void CDSMustMatchFlags::print_info() const { +void AOTMustMatchFlags::print_info() const { LogTarget(Info, cds) lt; if (lt.is_enabled()) { LogStream ls(lt); @@ -152,14 +159,13 @@ void CDSMustMatchFlags::print_info() const { } } -void CDSMustMatchFlags::print(outputStream* st) const { -#define PRINT_CDS_MUST_MATCH_FLAG(n) \ - st->print("- %-s ", #n); \ - st->sp(int(_max_name_width - strlen(#n))); \ - do_print(st, _v_##n); \ +void AOTMustMatchFlags::print(outputStream* st) const { +#define PRINT_AOT_MUST_MATCH_FLAG(n) \ + st->print("- %-41s ", #n ":"); \ + do_print(st, _v_##n); \ st->cr(); - CDS_MUST_MATCH_FLAGS_DO(PRINT_CDS_MUST_MATCH_FLAG); -#undef PRINT_CDS_MUST_MATCH_FLAG + AOT_MUST_MATCH_FLAGS_DO(PRINT_AOT_MUST_MATCH_FLAG); +#undef PRINT_AOT_MUST_MATCH_FLAG } // Fill in the fileMapInfo structure with data about this VM instance. @@ -304,9 +310,6 @@ void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment, copy_base_archive_name(CDSConfig::input_static_archive_path()); } _core_region_alignment = core_region_alignment; - _obj_alignment = ObjectAlignmentInBytes; - _compact_strings = CompactStrings; - _compact_headers = UseCompactObjectHeaders; #if INCLUDE_CDS_JAVA_HEAP if (CDSConfig::is_dumping_heap()) { _object_streaming_mode = AOTHeap::is_writing_streaming_mode(); @@ -381,11 +384,8 @@ void FileMapHeader::print(outputStream* st) { st->print_cr("============ end regions ======== "); st->print_cr("- core_region_alignment: %zu", _core_region_alignment); - st->print_cr("- obj_alignment: %d", _obj_alignment); st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base)); st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift); - st->print_cr("- compact_strings: %d", _compact_strings); - st->print_cr("- compact_headers: %d", _compact_headers); st->print_cr("- max_heap_size: %zu", _max_heap_size); st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode); st->print_cr("- compressed_oops: %d", _compressed_oops); @@ -816,10 +816,6 @@ bool FileMapInfo::init_from_file(int fd) { } } - if (!header()->check_must_match_flags()) { - return false; - } - return true; } @@ -2003,87 +1999,33 @@ int FileMapHeader::compute_crc() { return crc; } +// This is for flags that are checked only under certain conditions. +#define CHECK_OTHER_MUST_MATCH_FLAG(saved, flag) \ + if (!AOTMustMatchFlags::check_flag(saved, flag, #flag)) { return false; } + // This function should only be called during run time with UseSharedSpaces enabled. bool FileMapHeader::validate() { const char* file_type = CDSConfig::type_of_archive_being_loaded(); - if (_obj_alignment != ObjectAlignmentInBytes) { - AOTMetaspace::report_loading_error("The %s's ObjectAlignmentInBytes of %d" - " does not equal the current ObjectAlignmentInBytes of %d.", - file_type, _obj_alignment, ObjectAlignmentInBytes); + + // Check --enable-preview first, since it modifies many of the flags in _must_match. + if (!FileMapHeader::check_enable_preview()) { return false; } - if (_compact_strings != CompactStrings) { - AOTMetaspace::report_loading_error("The %s's CompactStrings setting (%s)" - " does not equal the current CompactStrings setting (%s).", file_type, - _compact_strings ? "enabled" : "disabled", - CompactStrings ? "enabled" : "disabled"); + + if (!_must_match.runtime_check()) { return false; } - if (TrainingData::have_data()) { - if (_type_profile_level != TypeProfileLevel) { - AOTMetaspace::report_loading_error("The %s's TypeProfileLevel setting (%d)" - " does not equal the current TypeProfileLevel setting (%d).", file_type, - _type_profile_level, TypeProfileLevel); - return false; - } - if (_type_profile_args_limit != TypeProfileArgsLimit) { - AOTMetaspace::report_loading_error("The %s's TypeProfileArgsLimit setting (%d)" - " does not equal the current TypeProfileArgsLimit setting (%d).", file_type, - _type_profile_args_limit, TypeProfileArgsLimit); - return false; - } - if (_type_profile_parms_limit != TypeProfileParmsLimit) { - AOTMetaspace::report_loading_error("The %s's TypeProfileParmsLimit setting (%d)" - " does not equal the current TypeProfileParmsLimit setting (%d).", file_type, - _type_profile_parms_limit, TypeProfileParmsLimit); - return false; - - } - if (_type_profile_width != TypeProfileWidth) { - AOTMetaspace::report_loading_error("The %s's TypeProfileWidth setting (%d)" - " does not equal the current TypeProfileWidth setting (%d).", file_type, - (int)_type_profile_width, (int)TypeProfileWidth); - return false; - - } - if (_bci_profile_width != BciProfileWidth) { - AOTMetaspace::report_loading_error("The %s's BciProfileWidth setting (%d)" - " does not equal the current BciProfileWidth setting (%d).", file_type, - (int)_bci_profile_width, (int)BciProfileWidth); - return false; - } - if (_type_profile_casts != TypeProfileCasts) { - AOTMetaspace::report_loading_error("The %s's TypeProfileCasts setting (%s)" - " does not equal the current TypeProfileCasts setting (%s).", file_type, - _type_profile_casts ? "enabled" : "disabled", - TypeProfileCasts ? "enabled" : "disabled"); - - return false; - } - if (_profile_traps != ProfileTraps) { - AOTMetaspace::report_loading_error("The %s's ProfileTraps setting (%s)" - " does not equal the current ProfileTraps setting (%s).", file_type, - _profile_traps ? "enabled" : "disabled", - ProfileTraps ? "enabled" : "disabled"); - - return false; - } - if (_profile_exception_handlers != ProfileExceptionHandlers) { - AOTMetaspace::report_loading_error("The %s's ProfileExceptionHandlers setting (%s)" - " does not equal the current ProfileExceptionHandlers setting (%s).", file_type, - _profile_exception_handlers ? "enabled" : "disabled", - ProfileExceptionHandlers ? "enabled" : "disabled"); - - return false; - } - if (_spec_trap_limit_extra_entries != SpecTrapLimitExtraEntries) { - AOTMetaspace::report_loading_error("The %s's SpecTrapLimitExtraEntries setting (%d)" - " does not equal the current SpecTrapLimitExtraEntries setting (%d).", file_type, - _spec_trap_limit_extra_entries, SpecTrapLimitExtraEntries); - return false; - - } + if (TrainingData::have_data()) { + CHECK_OTHER_MUST_MATCH_FLAG(_type_profile_level, TypeProfileLevel); + CHECK_OTHER_MUST_MATCH_FLAG(_type_profile_args_limit, TypeProfileArgsLimit); + CHECK_OTHER_MUST_MATCH_FLAG(_type_profile_parms_limit, TypeProfileParmsLimit); + CHECK_OTHER_MUST_MATCH_FLAG(_type_profile_width, TypeProfileWidth); + CHECK_OTHER_MUST_MATCH_FLAG(_bci_profile_width, BciProfileWidth); + CHECK_OTHER_MUST_MATCH_FLAG(_type_profile_casts, TypeProfileCasts); + CHECK_OTHER_MUST_MATCH_FLAG(_profile_traps, ProfileTraps); + CHECK_OTHER_MUST_MATCH_FLAG(_profile_exception_handlers, ProfileExceptionHandlers); + CHECK_OTHER_MUST_MATCH_FLAG(_spec_trap_limit_extra_entries, SpecTrapLimitExtraEntries); } if (_cpu_features_offset != -1) { @@ -2117,13 +2059,9 @@ bool FileMapHeader::validate() { } - if (!_verify_local && BytecodeVerificationLocal) { - // we cannot load boot classes, so there's no point of using the CDS archive - AOTMetaspace::report_loading_error("The %s's BytecodeVerificationLocal setting (%s)" - " does not equal the current BytecodeVerificationLocal setting (%s).", file_type, - _verify_local ? "enabled" : "disabled", - BytecodeVerificationLocal ? "enabled" : "disabled"); - return false; + if (!_verify_local) { + // If we cannot load boot classes, there's no point of using the CDS archive + CHECK_OTHER_MUST_MATCH_FLAG(_verify_local, BytecodeVerificationLocal); } // For backwards compatibility, we don't check the BytecodeVerificationRemote setting @@ -2147,32 +2085,6 @@ bool FileMapHeader::validate() { return false; } - if (is_static()) { - const char* err = nullptr; - if (Arguments::is_valhalla_enabled()) { - if (!_has_valhalla_patched_classes) { - err = "not created"; - } - } else { - if (_has_valhalla_patched_classes) { - err = "created"; - } - } - if (err != nullptr) { - log_warning(cds)("This archive was %s with --enable-preview. It is " - "incompatible with the current JVM setting", err); - return false; - } - } - - if (compact_headers() != UseCompactObjectHeaders) { - aot_log_warning(aot)("Unable to use %s.\nThe %s's UseCompactObjectHeaders setting (%s)" - " does not equal the current UseCompactObjectHeaders setting (%s).", file_type, file_type, - _compact_headers ? "enabled" : "disabled", - UseCompactObjectHeaders ? "enabled" : "disabled"); - return false; - } - if (is_static()) { // Only the static archive can contain the full module graph. if (!_has_full_module_graph) { @@ -2199,6 +2111,26 @@ bool FileMapHeader::validate() { return true; } +bool FileMapHeader::check_enable_preview() const { + const char* err = nullptr; + if (Arguments::is_valhalla_enabled()) { + if (!_has_valhalla_patched_classes) { + err = "not created"; + } + } else { + if (_has_valhalla_patched_classes) { + err = "created"; + } + } + if (err != nullptr) { + AOTMetaspace::report_loading_error("This %s was %s with --enable-preview. It is " + "incompatible with the current JVM setting", + CDSConfig::type_of_archive_being_loaded(), err); + return false; + } + return true; +} + bool FileMapInfo::validate_header() { if (!header()->validate()) { return false; diff --git a/src/hotspot/share/cds/filemap.hpp b/src/hotspot/share/cds/filemap.hpp index 40e7d7d468b8..94ff1fdda27f 100644 --- a/src/hotspot/share/cds/filemap.hpp +++ b/src/hotspot/share/cds/filemap.hpp @@ -30,6 +30,7 @@ #include "cds/aotMetaspace.hpp" #include "cds/aotStreamedHeap.hpp" #include "cds/archiveUtils.hpp" +#include "cppstdlib/type_traits.hpp" #include "include/cds.h" #include "logging/logLevel.hpp" #include "memory/allocation.hpp" @@ -102,28 +103,32 @@ class FileMapRegion: private CDSFileMapRegion { void print(outputStream* st, int region_index); }; -#define CDS_MUST_MATCH_FLAGS_DO(f) \ +#define AOT_MUST_MATCH_FLAGS_DO(f) \ + f(CompactStrings) \ + f(DiagnoseSyncOnValueBasedClasses) \ + f(FlatArrayElementMaxOops) \ + f(FlatteningBudget) \ + f(ObjectAlignmentInBytes) \ + f(RestrictReservedStack) \ f(UseArrayFlattening) \ + f(UseCompactObjectHeaders) \ f(UseFieldFlattening) \ - f(ValueTypePassFieldsAsArgs) \ - f(ValueTypeReturnedAsFields) \ - f(UseNullFreeNonAtomicValueFlattening) \ - f(UseNullFreeAtomicValueFlattening) \ f(UseNullableAtomicValueFlattening) \ f(UseNullableNonAtomicValueFlattening) \ - f(FlatteningBudget) \ - f(FlatArrayElementMaxOops) \ - f(RestrictReservedStack) \ - f(DiagnoseSyncOnValueBasedClasses) - + f(UseNullFreeAtomicValueFlattening) \ + f(UseNullFreeNonAtomicValueFlattening) \ + f(ValueTypePassFieldsAsArgs) \ + f(ValueTypeReturnedAsFields) \ + /* end */ -class CDSMustMatchFlags { +class AOTMustMatchFlags { private: - size_t _max_name_width; -#define DECLARE_CDS_MUST_MATCH_FLAG(n) \ - decltype(n) _v_##n; - CDS_MUST_MATCH_FLAGS_DO(DECLARE_CDS_MUST_MATCH_FLAG); -#undef DECLARE_CDS_MUST_MATCH_FLAG + +// std::remove_const_t is necessary because UseCompactObjectHeaders is a const in 32-bit builds. +#define DECLARE_AOT_MUST_MATCH_FLAG(n) \ + std::remove_const_t _v_##n; + AOT_MUST_MATCH_FLAGS_DO(DECLARE_AOT_MUST_MATCH_FLAG); +#undef DECLARE_AOT_MUST_MATCH_FLAG inline static void do_print(outputStream* st, bool v); LP64_ONLY(inline static void do_print(outputStream* st, uint v);) @@ -134,9 +139,15 @@ class CDSMustMatchFlags { void print_info() const; public: + template static bool check_flag(T saved, T actual, const char* name); + void init(); bool runtime_check() const; void print(outputStream* st) const; + + int obj_alignment() const { return _v_ObjectAlignmentInBytes; } + bool compact_strings() const { return _v_CompactStrings; } + bool compact_headers() const { return _v_UseCompactObjectHeaders; } }; class FileMapHeader: private CDSFileMapHeaderBase { @@ -148,11 +159,8 @@ class FileMapHeader: private CDSFileMapHeaderBase { // They are compared with the runtime states to see if the archive // can be used. size_t _core_region_alignment; // how shared archive should be aligned - int _obj_alignment; // value of ObjectAlignmentInBytes address _narrow_oop_base; // compressed oop encoding base int _narrow_oop_shift; // compressed oop encoding shift - bool _compact_strings; // value of CompactStrings - bool _compact_headers; // value of UseCompactObjectHeaders uintx _max_heap_size; // java max heap size during dumping CompressedOops::Mode _narrow_oop_mode; // compressed oop encoding mode bool _object_streaming_mode; // dump was created for object streaming @@ -180,7 +188,7 @@ class FileMapHeader: private CDSFileMapHeaderBase { bool _aot_class_linking_value; // The value of the AOTClassLinking variable when this archive was created bool _has_full_module_graph; // Does this CDS archive contain the full archived module graph? bool _has_valhalla_patched_classes; // Is this archived dumped with --enable-preview? - CDSMustMatchFlags _must_match; // These flags must be the same between dumptime and runtime + AOTMustMatchFlags _must_match; // These flags must be the same between dumptime and runtime size_t _rw_ptrmap_start_pos; // The first bit in the ptrmap corresponds to this position in the rw region size_t _ro_ptrmap_start_pos; // The first bit in the ptrmap corresponds to this position in the ro region @@ -205,6 +213,8 @@ class FileMapHeader: private CDSFileMapHeaderBase { return AOTCompressedPointers::decode_not_null(narrowp, reinterpret_cast
(mapped_base_address())); } + bool check_enable_preview() const; + public: // Accessors -- fields declared in GenericCDSFileMapHeader unsigned int magic() const { return _generic_header._magic; } @@ -222,12 +232,13 @@ class FileMapHeader: private CDSFileMapHeaderBase { void set_base_archive_name_size(unsigned int s) { _generic_header._base_archive_name_size = s; } bool is_static() const { return magic() == CDS_ARCHIVE_MAGIC; } + bool is_aot_configuration() const { return magic() == AOT_CONFIGURATION_MAGIC; } size_t core_region_alignment() const { return _core_region_alignment; } - int obj_alignment() const { return _obj_alignment; } + int obj_alignment() const { return _must_match.obj_alignment(); } address narrow_oop_base() const { return _narrow_oop_base; } int narrow_oop_shift() const { return _narrow_oop_shift; } - bool compact_strings() const { return _compact_strings; } - bool compact_headers() const { return _compact_headers; } + bool compact_strings() const { return _must_match.compact_strings(); } + bool compact_headers() const { return _must_match.compact_headers(); } uintx max_heap_size() const { return _max_heap_size; } CompressedOops::Mode narrow_oop_mode() const { return _narrow_oop_mode; } char* cloned_vtables() const { return decode(_cloned_vtables); } @@ -302,10 +313,6 @@ class FileMapHeader: private CDSFileMapHeaderBase { return (0 <= region && region < NUM_CDS_REGIONS); } - bool check_must_match_flags() const { - return _must_match.runtime_check(); - } - void print(outputStream* st); }; diff --git a/src/hotspot/share/ci/ciField.cpp b/src/hotspot/share/ci/ciField.cpp index bcfeafc97765..dcd1b4cb5d1c 100644 --- a/src/hotspot/share/ci/ciField.cpp +++ b/src/hotspot/share/ci/ciField.cpp @@ -509,9 +509,10 @@ bool ciField::is_autobox_cache() { } bool ciField::empty_null_free_initialized_value_field(bool method_is_safe) { + // Skip volatile fields because their memory barriers need to remain. ciType* field_type = type(); - return is_null_free() && field_type->is_value_klass() && field_type->as_value_klass()->is_empty() && - (method_is_safe || is_flat()); + return is_null_free() && !is_volatile() && field_type->is_value_klass() && + field_type->as_value_klass()->is_empty() && (method_is_safe || is_flat()); } // ------------------------------------------------------------------ diff --git a/src/hotspot/share/classfile/classLoader.cpp b/src/hotspot/share/classfile/classLoader.cpp index 039a1d2b68b1..4fb4430ab60d 100644 --- a/src/hotspot/share/classfile/classLoader.cpp +++ b/src/hotspot/share/classfile/classLoader.cpp @@ -1306,6 +1306,7 @@ void ClassLoader::record_result(JavaThread* current, InstanceKlass* ik, const ClassFileStream* stream, bool redefined) { assert(CDSConfig::is_dumping_archive(), "sanity"); assert(stream != nullptr, "sanity"); + assert(AOTClassLocationConfig::dumptime_is_ready(), "sanity"); if (ik->is_hidden()) { record_hidden_class(ik); @@ -1333,80 +1334,43 @@ void ClassLoader::record_result(JavaThread* current, InstanceKlass* ik, assert(has_jrt_entry(), "CDS dumping does not support exploded JDK build"); - ResourceMark rm(current); int classpath_index = -1; - bool found_invalid = false; - - PackageEntry* pkg_entry = ik->package(); - if (!AOTClassLocationConfig::dumptime_is_ready()) { - // The shared path table is set up after module system initialization. - // The path table contains no entry before that. Any classes loaded prior - // to the setup of the shared path table must be from the modules image. - assert(stream->from_boot_loader_modules_image(), "stream must be loaded by boot loader from modules image"); + if (stream->from_boot_loader_modules_image() || string_starts_with(src, "jrt:")) { + assert(AOTClassLocationConfig::dumptime()->class_location_at(0)->is_modules_image(), "sanity check"); classpath_index = 0; } else { - // Save the path from the file: protocol or the module name from the jrt: protocol - // if no protocol prefix is found, path is the same as stream->source(). This path - // must be valid since the class has been successfully parsed. + ResourceMark rm(current); const char* path = ClassLoader::uri_to_path(src); - assert(path != nullptr, "sanity"); - AOTClassLocationConfig::dumptime_iterate([&] (AOTClassLocation* cl) { - int i = cl->index(); - // for index 0 and the stream->source() is the modules image or has the jrt: protocol. - // The class must be from the runtime modules image. - if (cl->is_modules_image() && (stream->from_boot_loader_modules_image() || string_starts_with(src, "jrt:"))) { - classpath_index = i; - } else if (os::same_files(cl->path(), path)) { - // If the path (from the class stream source) is the same as the shared - // class or module path, then we have a match. - // src may come from the App/Platform class loaders, which would canonicalize - // the file name. We cannot use strcmp to check for equality against cs->path(). - // We must use os::same_files (which is faster than canonicalizing cs->path()). - + PackageEntry* pkg_entry = ik->package(); + if ((pkg_entry != nullptr) && !pkg_entry->in_unnamed_module()) { + // A class in a named module from the --module-path. Note that classes from the modules image + // are handled above and get an index of 0. + classpath_index = AOTClassLocationConfig::dumptime_get_class_location_index(path, /*is_named_module=*/ true); + } else { + // A class in an unnamed module + int i = AOTClassLocationConfig::dumptime_get_class_location_index(path, /*is_named_module=*/ false); + assert(i != 0, "must not be from module image"); + if (i > 0) { + AOTClassLocation const* cl = AOTClassLocationConfig::dumptime()->class_location_at(i); // null pkg_entry and pkg_entry in an unnamed module implies the class // is from the -cp or boot loader append path which consists of -Xbootclasspath/a // and jvmti appended entries. if ((pkg_entry == nullptr) || (pkg_entry->in_unnamed_module())) { - // Ensure the index is within the -cp range before assigning - // to the classpath_index. if (SystemDictionary::is_system_class_loader(loader) && cl->from_app_classpath()) { classpath_index = i; - } else { - if (cl->from_boot_classpath()) { - if (loader != nullptr) { - // Probably loaded by jdk/internal/loader/ClassLoaders$BootClassLoader. Don't archive - // such classes. - found_invalid = true; - } else { - classpath_index = i; - } - } - } - } else { - // A class from a named module from the --module-path. Ensure the index is - // within the --module-path range before assigning to the classpath_index. - if ((pkg_entry != nullptr) && !(pkg_entry->in_unnamed_module()) && cl->from_module_path()) { + } else if (loader == nullptr && cl->from_boot_classpath()) { classpath_index = i; } } } - if (classpath_index >= 0 || found_invalid) { - return false; // Break the AOTClassLocationConfig::dumptime_iterate() loop. - } else { - return true; // Keep iterating - } - }); + } } - if (found_invalid) { - assert(classpath_index == -1, "sanity"); - } + // Note: classpath_index will be -1 if it's not found inside AOTClassLocationConfig, and + // such a class will not be archived. - const char* const class_name = ik->name()->as_C_string(); - const char* const file_name = file_name_for_class_name(class_name, - ik->name()->utf8_length()); - assert(file_name != nullptr, "invariant"); + log_debug(aot, path)("classpath_index %s = %d", ik->external_name(), classpath_index); record_result_for_builtin_loader(checked_cast(classpath_index), ik, redefined); } @@ -1637,6 +1601,12 @@ char* ClassLoader::get_canonical_path(const char* orig, Thread* thread) { ResourceMark rm(thread); // os::native_path writes into orig_copy char* orig_copy = ResourceArea::strdup(thread, orig); +#if defined(_WINDOWS) + if (strncmp("\\\\?\\", orig_copy, 4) == 0) { + // Work around JDK-8397366 + orig_copy += 4; + } +#endif if ((CanonicalizeEntry)(os::native_path(orig_copy), canonical_path, JVM_MAXPATHLEN) < 0) { return nullptr; } diff --git a/src/hotspot/share/compiler/compilationPolicy.cpp b/src/hotspot/share/compiler/compilationPolicy.cpp index 44db8b346d7d..4c1f2e727c10 100644 --- a/src/hotspot/share/compiler/compilationPolicy.cpp +++ b/src/hotspot/share/compiler/compilationPolicy.cpp @@ -117,9 +117,16 @@ void CompilationPolicy::maybe_compile_early(const methodHandle& m, MethodTrainin // Consider replacing conservatively compiled AOT Preload code with faster AOT code or normal JITed code nmethod* nm = m->code(); bool recompile = (nm != nullptr) && nm->aot_preloaded(); + // Method::set_code() publishes Method::_code before updating highest_comp_level. + // As a result, highest_comp_level() can temporarily be lower than nm->comp_level(). CompLevel cur_level = static_cast(m->highest_comp_level()); + if (nm != nullptr) { + cur_level = MAX2(cur_level, static_cast(nm->comp_level())); + } CompLevel next_level = trained_transition(m, cur_level, mtd, THREAD); - if ((next_level != cur_level || recompile) && can_be_compiled(m, next_level) && !CompileBroker::compilation_is_in_queue(m)) { + if ((next_level != cur_level || recompile) && + is_compile(next_level) && can_be_compiled(m, next_level) && + !CompileBroker::compilation_is_in_queue(m)) { // We are here because some of CTD have all init dependencies satisfied. CompileTrainingData* ctd = mtd->compile_data_for_aot_code(next_level); if (ctd == nullptr || (ctd->init_deps_left_acquire() > 0)) { diff --git a/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp b/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp index 5fa2edf4f424..7c4d4300da67 100644 --- a/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp +++ b/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp @@ -206,6 +206,7 @@ Node* G1BarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) c // mechanism. Also we need to add a memory barrier to prevent commoning reads // from this field across safepoints, since GC can change its value. bool need_read_barrier = ((on_weak || on_phantom) && !no_keepalive); + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop() && need_read_barrier) { access.set_barrier_data(G1C2BarrierPre); } @@ -226,23 +227,38 @@ void G1BarrierSetC2::eliminate_gc_barrier_data(Node* node) const { } } +static TypePtr::PTR meet_ptr_of_oops_in_store_l_special(const MemNode* store) { + const Type* oops_meet = store->in(StoreLSpecialNode::FirstOop)->bottom_type(); + if (!store->in(StoreLSpecialNode::SecondOop)->is_top()) { + oops_meet = oops_meet->meet(store->in(StoreLSpecialNode::SecondOop)->bottom_type()); + } + const TypePtr* oops_meet_as_ptr = oops_meet->make_ptr(); + return oops_meet_as_ptr->ptr(); +} + static void refine_barrier_by_new_val_type(const Node* n) { if (n->Opcode() != Op_StoreP && - n->Opcode() != Op_StoreN) { + n->Opcode() != Op_StoreN && + n->Opcode() != Op_StoreLSpecial) { return; } MemNode* store = n->as_Mem(); - const Node* newval = n->in(MemNode::ValueIn); - assert(newval != nullptr, ""); - const Type* newval_bottom = newval->bottom_type(); - TypePtr::PTR newval_type = newval_bottom->make_ptr()->ptr(); uint8_t barrier_data = store->barrier_data(); - if (!newval_bottom->isa_oopptr() && - !newval_bottom->isa_narrowoop() && - newval_type != TypePtr::Null) { - // newval is neither an OOP nor null, so there is no barrier to refine. - assert(barrier_data == 0, "non-OOP stores should have no barrier data"); - return; + TypePtr::PTR newval_type; + if (n->Opcode() == Op_StoreLSpecial) { + newval_type = meet_ptr_of_oops_in_store_l_special(store); + } else { + const Node* newval = n->in(MemNode::ValueIn); + assert(newval != nullptr, ""); + const Type* newval_bottom = newval->bottom_type(); + newval_type = newval_bottom->make_ptr()->ptr(); + if (!newval_bottom->is_oopptr() && + !newval_bottom->is_narrowoop() && + newval_type != TypePtr::Null) { + // newval is neither an OOP nor null, so there is no barrier to refine. + assert(barrier_data == 0, "non-OOP stores should have no barrier data"); + return; + } } if (barrier_data == 0) { // No barrier to refine. @@ -289,28 +305,34 @@ bool G1BarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const { uint G1BarrierSetC2::estimated_barrier_size(const Node* node) const { uint8_t barrier_data = MemNode::barrier_data(node); uint nodes = 0; + uint factor = 1; + if (node->Opcode() == Op_StoreLSpecial && !node->in(StoreLSpecialNode::SecondOop)->is_top()) { + // assigning two oops will make two barrier sets + factor = 2; + } if ((barrier_data & G1C2BarrierPre) != 0) { // Only consider the fast path for the barrier that is // actually inlined into the main code stream. // The slow path is laid out separately and does not // directly affect performance. // It has a cost of 6 (AddP, LoadB, Cmp, Bool, If, IfProj). - nodes += 6; + nodes += 6 * factor; } if ((barrier_data & G1C2BarrierPost) != 0) { // Approximate the number of nodes needed; an if costs 4 nodes (Cmp, Bool, // If, If projection), any other (Assembly) instruction is approximated with // a cost of 1. - nodes += 4 // base cost for the card write containing getting base offset, address calculation and the card write; - + 6 // same region check: Uncompress (new_val) oop, xor, shr, (cmp), jmp - + 4 // new_val is null check - + (UseCondCardMark ? 4 : 0); // card not clean check. + uint post_nodes = 4 // base cost for the card write containing getting base offset, address calculation and the card write; + + 6 // same region check: Uncompress (new_val) oop, xor, shr, (cmp), jmp + + 4 // new_val is null check + + (UseCondCardMark ? 4 : 0); // card not clean check. + nodes += post_nodes * factor; } return nodes; } bool G1BarrierSetC2::can_initialize_object(const StoreNode* store) const { - assert(store->Opcode() == Op_StoreP || store->Opcode() == Op_StoreN, "OOP store expected"); + assert(store->Opcode() == Op_StoreP || store->Opcode() == Op_StoreN || store->Opcode() == Op_StoreLSpecial, "OOP store expected"); // It is OK to move the store across the object initialization boundary only // if it does not have any barrier, or if it has barriers that can be safely // elided (because of the compensation steps taken on the allocation slow path @@ -351,6 +373,7 @@ Node* G1BarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) co Node* G1BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val, Node* new_val, const Type* value_type) const { + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type); } @@ -360,6 +383,7 @@ Node* G1BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access Node* G1BarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val, Node* new_val, const Type* value_type) const { + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type); } @@ -368,6 +392,7 @@ Node* G1BarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& acces } Node* G1BarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const { + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return BarrierSetC2::atomic_xchg_at_resolved(access, new_val, value_type); } @@ -538,6 +563,7 @@ void G1BarrierSetC2::analyze_dominating_barriers() const { switch (mach->ideal_Opcode()) { case Op_StoreP: case Op_StoreN: + case Op_StoreLSpecial: case Op_CompareAndExchangeP: case Op_CompareAndSwapP: case Op_GetAndSetP: diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp index 5e08a7f5b286..ec08b49d2d5c 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp @@ -84,7 +84,6 @@ #include "gc/shared/isGCActiveMark.hpp" #include "gc/shared/locationPrinter.inline.hpp" #include "gc/shared/oopStorageParState.hpp" -#include "gc/shared/partialArrayState.hpp" #include "gc/shared/referenceProcessor.inline.hpp" #include "gc/shared/suspendibleThreadSet.hpp" #include "gc/shared/taskqueue.inline.hpp" @@ -1330,7 +1329,6 @@ G1CollectedHeap::G1CollectedHeap() : _cm(nullptr), _cr(nullptr), _task_queues(nullptr), - _partial_array_state_manager(nullptr), _ref_processor_stw(nullptr), _is_alive_closure_stw(this), _is_subject_to_discovery_stw(this), @@ -1364,15 +1362,9 @@ G1CollectedHeap::G1CollectedHeap() : _task_queues->register_queue(i, q); } - _partial_array_state_manager = new PartialArrayStateManager(num_queues); - _gc_tracer_stw->initialize(); } -PartialArrayStateManager* G1CollectedHeap::partial_array_state_manager() const { - return _partial_array_state_manager; -} - G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description, size_t size, size_t translation_factor) { diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp index 501897b4db3b..e3d33004a5e3 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp @@ -83,7 +83,6 @@ class GCMemoryManager; class G1HeapRegion; class MemoryPool; class nmethod; -class PartialArrayStateManager; class ReferenceProcessor; class STWGCTimer; class WorkerThreads; @@ -824,9 +823,8 @@ class G1CollectedHeap : public CollectedHeap { // The concurrent refiner. G1ConcurrentRefine* _cr; - // Reusable parallel task queues and partial array manager. + // Reusable parallel task queues. G1ScannerTasksQueueSet* _task_queues; - PartialArrayStateManager* _partial_array_state_manager; // ("Weak") Reference processing support. // @@ -892,8 +890,6 @@ class G1CollectedHeap : public CollectedHeap { G1ScannerTasksQueueSet* task_queues() const; G1ScannerTasksQueue* task_queue(uint i) const; - PartialArrayStateManager* partial_array_state_manager() const; - // Create a G1CollectedHeap. // Must call the initialize method afterwards. // May not return if something goes wrong. diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp index 61a31982c3ae..b7a70f800a07 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp @@ -451,7 +451,6 @@ G1ConcurrentMark::G1ConcurrentMark(G1CollectedHeap* g1h, _tasks(nullptr), _task_queues(new G1CMTaskQueueSet(_max_num_tasks)), _terminator(_max_num_tasks, _task_queues), - _partial_array_state_manager(new PartialArrayStateManager(_max_num_tasks)), _first_overflow_barrier_sync(), _second_overflow_barrier_sync(), @@ -554,10 +553,6 @@ bool G1ConcurrentMark::is_in_reset_for_next_cycle() const { return cm_thread()->is_in_reset_for_next_cycle(); } -PartialArrayStateManager* G1ConcurrentMark::partial_array_state_manager() const { - return _partial_array_state_manager; -} - G1ConcurrentMarkThread* G1ConcurrentMark::cm_thread() const { assert(is_fully_initialized(), "must be"); return _cm_thread; @@ -871,21 +866,18 @@ void G1ConcurrentMark::cleanup_for_next_mark() { clear_bitmap(_concurrent_workers, true); - reset_partial_array_state_manager(); + reset_partial_array_splitters(); // Should not have changed state yet (even if a Full GC interrupted us). guarantee(is_in_reset_for_next_cycle(), "invariant"); } -void G1ConcurrentMark::reset_partial_array_state_manager() { +void G1ConcurrentMark::reset_partial_array_splitters() { + // All concurrent and remark workers have stopped using partial-array states. + // Reset every splitter before marking resumes: stolen tasks may have placed + // slots from one splitter's arena on another splitter's free-list. for (uint i = 0; i < _max_num_tasks; ++i) { - _tasks[i]->unregister_partial_array_splitter(); - } - - partial_array_state_manager()->reset(); - - for (uint i = 0; i < _max_num_tasks; ++i) { - _tasks[i]->register_partial_array_splitter(); + _tasks[i]->reset_partial_array_splitter(); } } @@ -2249,14 +2241,8 @@ void G1CMTask::reset_for_restart() { TASKQUEUE_STATS_ONLY(_task_queue->stats.reset()); } -void G1CMTask::register_partial_array_splitter() { - - ::new (&_partial_array_splitter) PartialArraySplitter(_cm->partial_array_state_manager(), - _cm->max_num_tasks()); -} - -void G1CMTask::unregister_partial_array_splitter() { - _partial_array_splitter.~PartialArraySplitter(); +void G1CMTask::reset_partial_array_splitter() { + _partial_array_splitter.reset(); } bool G1CMTask::should_exit_termination() { @@ -3013,7 +2999,7 @@ G1CMTask::G1CMTask(uint worker_id, _cm(cm), _mark_bitmap(nullptr), _task_queue(task_queue), - _partial_array_splitter(_cm->partial_array_state_manager(), _cm->max_num_tasks()), + _partial_array_splitter(_cm->max_num_tasks()), _mark_stats_cache(mark_stats, G1RegionMarkStatsCache::RegionMarkStatsCacheSize), _calls(0), _time_target_ms(0.0), diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp index 157e3bc6abdd..0b11bdcf976b 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp @@ -361,8 +361,6 @@ class G1ConcurrentMark : public CHeapObj { G1CMTaskQueueSet* _task_queues; // Task queue set TaskTerminator _terminator; // For termination - PartialArrayStateManager* _partial_array_state_manager; - // Two sync barriers that are used to synchronize tasks when an // overflow occurs. The algorithm is the following. All tasks enter // the first one to ensure that they have all stopped manipulating @@ -631,8 +629,6 @@ class G1ConcurrentMark : public CHeapObj { // Calculates the number of concurrent GC threads to be used in the marking phase. uint calc_active_marking_workers(); - PartialArrayStateManager* partial_array_state_manager() const; - // Resets the global marking data structures, as well as the // task local ones; should be called during concurrent start. void reset(); @@ -644,9 +640,9 @@ class G1ConcurrentMark : public CHeapObj { // to be called concurrently to the mutator. It will yield to safepoint requests. void cleanup_for_next_mark(); - // Recycle the memory that has been requested by allocators associated with - // this manager. - void reset_partial_array_state_manager(); + // Reclaim partial-array state memory after all marking workers have stopped. + // Reset every allocator before marking resumes. + void reset_partial_array_splitters(); // Clear the next marking bitmap during safepoint. void clear_bitmap(WorkerThreads* workers); @@ -893,11 +889,9 @@ class G1CMTask : public TerminatorTerminator { void reset(G1CMBitMap* mark_bitmap); // Minimal reset of the task, making it ready for continuing to mark. void reset_for_restart(); - // Register/unregister Partial Array Splitter Allocator with the PartialArrayStateManager. - // This allows us to discard memory arenas used for partial object array states at the end - // of a concurrent mark cycle. - void register_partial_array_splitter(); - void unregister_partial_array_splitter(); + // Reclaim states only after all marking/remark workers have stopped using + // them. Every task's splitter must reset before marking resumes. + void reset_partial_array_splitter(); // Clears all the fields that correspond to a claimed region. void clear_region_fields(); diff --git a/src/hotspot/share/gc/g1/g1FullCollector.cpp b/src/hotspot/share/gc/g1/g1FullCollector.cpp index 2838d3a25852..da79a514b879 100644 --- a/src/hotspot/share/gc/g1/g1FullCollector.cpp +++ b/src/hotspot/share/gc/g1/g1FullCollector.cpp @@ -119,7 +119,6 @@ G1FullCollector::G1FullCollector(G1CollectedHeap* heap, _has_compaction_targets(false), _has_humongous(false), _marking_task_queues(_num_workers), - _partial_array_state_manager(nullptr), _preserved_marks_set(true), _serial_compaction_point(this, nullptr), _humongous_compaction_point(this, nullptr), @@ -143,8 +142,6 @@ G1FullCollector::G1FullCollector(G1CollectedHeap* heap, _compaction_tops = NEW_C_HEAP_ARRAY(Atomic, _heap->max_num_regions(), mtGC); ::new (_compaction_tops) Atomic[heap->max_num_regions()]{}; - _partial_array_state_manager = new PartialArrayStateManager(_num_workers); - for (uint i = 0; i < _num_workers; i++) { _markers[i] = new G1FullGCMarker(this, i, _live_stats); _compaction_points[i] = new G1FullGCCompactionPoint(this, _preserved_marks_set.get(i)); @@ -156,18 +153,12 @@ G1FullCollector::G1FullCollector(G1CollectedHeap* heap, _region_attr_table.initialize(heap->reserved(), G1HeapRegion::GrainBytes); } -PartialArrayStateManager* G1FullCollector::partial_array_state_manager() const { - return _partial_array_state_manager; -} - G1FullCollector::~G1FullCollector() { for (uint i = 0; i < _num_workers; i++) { delete _markers[i]; delete _compaction_points[i]; } - delete _partial_array_state_manager; - FREE_C_HEAP_ARRAY(_markers); FREE_C_HEAP_ARRAY(_compaction_points); FREE_C_HEAP_ARRAY(_compaction_tops); diff --git a/src/hotspot/share/gc/g1/g1FullCollector.hpp b/src/hotspot/share/gc/g1/g1FullCollector.hpp index 605556a2ba64..f76dfe351430 100644 --- a/src/hotspot/share/gc/g1/g1FullCollector.hpp +++ b/src/hotspot/share/gc/g1/g1FullCollector.hpp @@ -68,7 +68,6 @@ class G1FullCollector : StackObj { G1FullGCMarker** _markers; G1FullGCCompactionPoint** _compaction_points; G1MarkTasksQueueSet _marking_task_queues; - PartialArrayStateManager* _partial_array_state_manager; PreservedMarksSet _preserved_marks_set; G1FullGCCompactionPoint _serial_compaction_point; G1FullGCCompactionPoint _humongous_compaction_point; @@ -112,8 +111,6 @@ class G1FullCollector : StackObj { return _live_stats[region_index].live_words(); } - PartialArrayStateManager* partial_array_state_manager() const; - void before_marking_update_attribute_table(G1HeapRegion* hr); inline bool is_compacting(oop obj) const; diff --git a/src/hotspot/share/gc/g1/g1FullGCMarker.cpp b/src/hotspot/share/gc/g1/g1FullGCMarker.cpp index aeab92625a41..4f5fdaa48685 100644 --- a/src/hotspot/share/gc/g1/g1FullGCMarker.cpp +++ b/src/hotspot/share/gc/g1/g1FullGCMarker.cpp @@ -39,7 +39,7 @@ G1FullGCMarker::G1FullGCMarker(G1FullCollector* collector, _worker_id(worker_id), _bitmap(collector->mark_bitmap()), _task_queue(), - _partial_array_splitter(collector->partial_array_state_manager(), collector->workers()), + _partial_array_splitter(collector->workers()), _mark_closure(this, ClassLoaderData::_claim_stw_fullgc_mark, G1CollectedHeap::heap()->ref_processor_stw()), _stack_closure(this), _cld_closure(mark_closure(), ClassLoaderData::_claim_stw_fullgc_mark), diff --git a/src/hotspot/share/gc/g1/g1ParScanThreadState.cpp b/src/hotspot/share/gc/g1/g1ParScanThreadState.cpp index f644625cbb42..3c318bf34c5f 100644 --- a/src/hotspot/share/gc/g1/g1ParScanThreadState.cpp +++ b/src/hotspot/share/gc/g1/g1ParScanThreadState.cpp @@ -78,7 +78,7 @@ G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, _surviving_young_words(nullptr), _surviving_words_length(collection_set->num_young_regions() + 1), _old_gen_is_full(false), - _partial_array_splitter(g1h->partial_array_state_manager(), num_workers), + _partial_array_splitter(num_workers), _string_dedup_requests(), _max_num_optional_regions(collection_set->num_optional_regions()), _numa(g1h->numa()), diff --git a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp index 6fb563c9d037..d40b9438a9e9 100644 --- a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp +++ b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp @@ -44,7 +44,6 @@ #include "gc/g1/g1RemSet.hpp" #include "gc/g1/g1YoungGCPostEvacuateTasks.hpp" #include "gc/shared/bufferNode.hpp" -#include "gc/shared/partialArrayState.hpp" #include "jfr/jfrEvents.hpp" #include "oops/access.inline.hpp" #include "oops/compressedOops.inline.hpp" @@ -904,8 +903,6 @@ class G1PostEvacuateCollectionSetCleanupTask2::DestroyPssTask : public G1Abstrac void do_work(uint worker_id) override { _per_thread_states->destroy_worker_states(); - // This must be here after above destroyed the per-thread allocators. - G1CollectedHeap::heap()->partial_array_state_manager()->reset(); } }; diff --git a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.hpp b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.hpp index 95d0fee6ad73..e506f701b5b1 100644 --- a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.hpp +++ b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.hpp @@ -56,7 +56,7 @@ class G1PostEvacuateCollectionSetCleanupTask1 : public G1BatchedTask { // Second set of post evacuate collection set tasks containing (s means serial): // - Eagerly Reclaim Humongous Objects (s) // - Update Derived Pointers (s) -// - Destroy PSS (s) + Reset the reusable PartialArrayStateManager +// - Destroy PSS (s) // - Clear Retained Region Data (on evacuation failure) // - Free Collection Set // - Resize TLABs and Swap Card Table diff --git a/src/hotspot/share/gc/parallel/psCompactionManager.cpp b/src/hotspot/share/gc/parallel/psCompactionManager.cpp index f8f23dabf8cd..d272da23dc33 100644 --- a/src/hotspot/share/gc/parallel/psCompactionManager.cpp +++ b/src/hotspot/share/gc/parallel/psCompactionManager.cpp @@ -46,7 +46,6 @@ ParCompactionManager** ParCompactionManager::_manager_array = nullptr; ParCompactionManager::PSMarkTasksQueueSet* ParCompactionManager::_marking_stacks = nullptr; ParCompactionManager::RegionTaskQueueSet* ParCompactionManager::_region_task_queues = nullptr; -PartialArrayStateManager* ParCompactionManager::_partial_array_state_manager = nullptr; ObjectStartArray* ParCompactionManager::_start_array = nullptr; ParMarkBitMap* ParCompactionManager::_mark_bitmap = nullptr; @@ -58,7 +57,7 @@ PreservedMarksSet* ParCompactionManager::_preserved_marks_set = nullptr; ParCompactionManager::ParCompactionManager(PreservedMarks* preserved_marks, ReferenceProcessor* ref_processor, uint parallel_gc_threads) - :_partial_array_splitter(_partial_array_state_manager, parallel_gc_threads), + :_partial_array_splitter(parallel_gc_threads), _mark_and_push_closure(this, ref_processor) { ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); @@ -82,9 +81,6 @@ void ParCompactionManager::initialize(ParMarkBitMap* mbm) { assert(_manager_array == nullptr, "Attempt to initialize twice"); _manager_array = NEW_C_HEAP_ARRAY(ParCompactionManager*, parallel_gc_threads, mtGC); - assert(_partial_array_state_manager == nullptr, "Attempt to initialize twice"); - _partial_array_state_manager - = new PartialArrayStateManager(parallel_gc_threads); _marking_stacks = new PSMarkTasksQueueSet(parallel_gc_threads); _region_task_queues = new RegionTaskQueueSet(parallel_gc_threads); diff --git a/src/hotspot/share/gc/parallel/psCompactionManager.hpp b/src/hotspot/share/gc/parallel/psCompactionManager.hpp index 5a66bebe2b2a..949f3019f773 100644 --- a/src/hotspot/share/gc/parallel/psCompactionManager.hpp +++ b/src/hotspot/share/gc/parallel/psCompactionManager.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,6 @@ class ParCompactionManager : public CHeapObj { static RegionTaskQueueSet* _region_task_queues; static PSOldGen* _old_gen; - static PartialArrayStateManager* _partial_array_state_manager; PartialArraySplitter _partial_array_splitter; PSMarkTaskQueue _marking_stack; diff --git a/src/hotspot/share/gc/parallel/psPromotionManager.cpp b/src/hotspot/share/gc/parallel/psPromotionManager.cpp index 628935ba4d53..426fc81e4cfe 100644 --- a/src/hotspot/share/gc/parallel/psPromotionManager.cpp +++ b/src/hotspot/share/gc/parallel/psPromotionManager.cpp @@ -53,7 +53,6 @@ PSPromotionManager::PSScannerTasksQueueSet* PSPromotionManager::_stack_array_dep PreservedMarksSet* PSPromotionManager::_preserved_marks_set = nullptr; PSOldGen* PSPromotionManager::_old_gen = nullptr; MutableSpace* PSPromotionManager::_young_space = nullptr; -PartialArrayStateManager* PSPromotionManager::_partial_array_state_manager = nullptr; void PSPromotionManager::initialize() { ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); @@ -63,10 +62,6 @@ void PSPromotionManager::initialize() { const uint promotion_manager_num = ParallelGCThreads; - assert(_partial_array_state_manager == nullptr, "Attempt to initialize twice"); - _partial_array_state_manager - = new PartialArrayStateManager(promotion_manager_num); - // To prevent false sharing, we pad the PSPromotionManagers // and make sure that the first instance starts at a cache line. assert(_manager_array == nullptr, "Attempt to initialize twice"); @@ -160,7 +155,7 @@ PartialArrayTaskStats* PSPromotionManager::partial_array_task_stats() { // Most members are initialized either by initialize() or reset(). PSPromotionManager::PSPromotionManager() - : _partial_array_splitter(_partial_array_state_manager, ParallelGCThreads) + : _partial_array_splitter(ParallelGCThreads) { // We set the old lab's start array. _old_lab.set_start_array(old_gen()->start_array()); diff --git a/src/hotspot/share/gc/parallel/psPromotionManager.hpp b/src/hotspot/share/gc/parallel/psPromotionManager.hpp index dd91fccd27c7..4e74e9880e93 100644 --- a/src/hotspot/share/gc/parallel/psPromotionManager.hpp +++ b/src/hotspot/share/gc/parallel/psPromotionManager.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,7 +81,6 @@ class PSPromotionManager { PSScannerTasksQueue _claimed_stack_depth; - static PartialArrayStateManager* _partial_array_state_manager; PartialArraySplitter _partial_array_splitter; uint _min_array_size_for_chunking; diff --git a/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp index a31bfe5bff0f..dd696599a608 100644 --- a/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp @@ -76,7 +76,7 @@ bool C2Access::needs_cpu_membar() const { // the barriers get omitted and the unsafe reference begins to "pollute" // the alias analysis of the rest of the graph, either Compile::can_alias // or Compile::must_alias will throw a diagnostic assert.) - if (is_mixed || !is_unordered || (mismatched && !_addr.type()->isa_aryptr())) { + if (is_mixed || !is_unordered || (mismatched && !_addr.type()->is_aryptr())) { return true; } } else { @@ -149,6 +149,7 @@ Node* BarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) cons bool mismatched = (decorators & C2_MISMATCHED) != 0; bool unaligned = (decorators & C2_UNALIGNED) != 0; bool unsafe = (decorators & C2_UNSAFE_ACCESS) != 0; + bool store_special = (decorators & C2_SPECIAL_ACCESS) != 0; bool requires_atomic_access = (decorators & MO_UNORDERED) == 0; MemNode::MemOrd mo = access.mem_node_mo(); @@ -161,7 +162,7 @@ Node* BarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) cons GraphKit* kit = parse_access.kit(); store = kit->store_to_memory(kit->control(), access.addr().node(), val.node(), bt, mo, requires_atomic_access, unaligned, mismatched, - unsafe, access.barrier_data()); + unsafe, store_special, access.barrier_data()); } else { assert(access.is_opt_access(), "either parse or opt access"); C2OptAccess& opt_access = static_cast(access); @@ -419,12 +420,12 @@ void C2Access::fixup_decorators() { _decorators |= C2_UNKNOWN_CONTROL_LOAD; const TypePtr* adr_type = _addr.type(); Node* adr = _addr.node(); - if (!needs_cpu_membar() && adr_type->isa_instptr()) { + if (!needs_cpu_membar() && adr_type->is_instptr()) { assert(adr_type->meet(TypePtr::NULL_PTR) != adr_type->remove_speculative(), "should be not null"); intptr_t offset = Type::OffsetBot; AddPNode::Ideal_base_and_offset(adr, &gvn(), offset); if (offset >= 0) { - int s = Klass::layout_helper_size_in_bytes(adr_type->isa_instptr()->instance_klass()->layout_helper()); + int s = Klass::layout_helper_size_in_bytes(adr_type->as_instptr()->instance_klass()->layout_helper()); if (offset < s) { // Guaranteed to be a valid access, no need to pin it _decorators ^= C2_CONTROL_DEPENDENT_LOAD; @@ -466,6 +467,7 @@ Node* BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* load_store = nullptr; + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop()) { #ifdef _LP64 if (adr->bottom_type()->is_ptr_to_narrowoop()) { @@ -475,7 +477,7 @@ Node* BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, } else #endif { - load_store = new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo); + load_store = new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->as_oopptr(), mo); } } else { switch (access.type()) { @@ -507,6 +509,7 @@ Node* BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, pin_atomic_op(access); #ifdef _LP64 + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop() && adr->bottom_type()->is_ptr_to_narrowoop()) { return kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type())); } @@ -525,6 +528,7 @@ Node* BarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* load_store = nullptr; Node* adr = access.addr().node(); + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop()) { #ifdef _LP64 if (adr->bottom_type()->is_ptr_to_narrowoop()) { @@ -599,6 +603,7 @@ Node* BarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* n const TypePtr* adr_type = access.addr().type(); Node* load_store = nullptr; + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop()) { #ifdef _LP64 if (adr->bottom_type()->is_ptr_to_narrowoop()) { @@ -607,7 +612,7 @@ Node* BarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* n } else #endif { - load_store = new GetAndSetPNode(kit->control(), mem, adr, new_val, adr_type, value_type->is_oopptr()); + load_store = new GetAndSetPNode(kit->control(), mem, adr, new_val, adr_type, value_type->as_oopptr()); } } else { switch (access.type()) { @@ -635,6 +640,7 @@ Node* BarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* n pin_atomic_op(access); #ifdef _LP64 + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (access.is_oop() && adr->bottom_type()->is_ptr_to_narrowoop()) { return kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type())); } @@ -1011,12 +1017,12 @@ static bool is_array_allocation(const Node* phi) { while (true) { const Node* next = nullptr; for (DUIterator_Fast imax, i = current->fast_outs(imax); i < imax; i++) { - if (!current->fast_out(i)->isa_Mach()) { + if (!current->fast_out(i)->is_Mach()) { continue; } const MachNode* succ = current->fast_out(i)->as_Mach(); if (succ->ideal_Opcode() == Op_CheckCastPP) { - if (succ->get_ptr_type()->isa_aryptr()) { + if (succ->get_ptr_type()->is_aryptr()) { // Cast to Java array pointer: phi corresponds to an array allocation. return true; } @@ -1053,10 +1059,10 @@ bool BarrierSetC2::is_allocation(const Node* node) { } intptr_t offset; const Node* const base = get_base_and_offset(fast_mach, offset); - if (base == nullptr || !base->is_Mach() || !is_concrete(offset)) { + const MachNode* const base_mach = Node::isa(base); + if (base_mach == nullptr || !is_concrete(offset)) { return false; } - const MachNode* const base_mach = base->as_Mach(); if (base_mach->ideal_Opcode() != Op_ThreadLocal) { return false; } @@ -1121,7 +1127,7 @@ void BarrierSetC2::elide_dominated_barriers(const Node_List& accesses, if (access_block == mem_block) { // Earlier accesses in the same block if (mem_index < access_index && !block_has_safepoint(mem_block, mem_index + 1, access_index)) { - elide_dominated_barrier(access, mem->is_Mach() ? mem->as_Mach() : nullptr); + elide_dominated_barrier(access, mem->isa_Mach()); } } else if (mem_block->dominates(access_block)) { // Dominating block? Look around for safepoints @@ -1151,7 +1157,7 @@ void BarrierSetC2::elide_dominated_barriers(const Node_List& accesses, } if (!safepoint_found) { - elide_dominated_barrier(access, mem->is_Mach() ? mem->as_Mach() : nullptr); + elide_dominated_barrier(access, mem->isa_Mach()); } } } diff --git a/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp b/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp index 7fe9dc477673..8ca5f87c42d0 100644 --- a/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp +++ b/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp @@ -57,6 +57,8 @@ const DecoratorSet C2_TIGHTLY_COUPLED_ALLOC = DECORATOR_LAST << 9; const DecoratorSet C2_ARRAY_COPY = DECORATOR_LAST << 10; // Loads from immutable memory const DecoratorSet C2_IMMUTABLE_MEMORY = DECORATOR_LAST << 11; +// Accesses two narrow oops, or one narrow oop along with some primitive data at once. +const DecoratorSet C2_SPECIAL_ACCESS = DECORATOR_LAST << 12; class Compile; class ConnectionGraph; @@ -93,7 +95,7 @@ class C2AccessValuePtr: public C2AccessValue { C2AccessValuePtr(Node* node, const TypePtr* type) : C2AccessValue(node, type) {} - const TypePtr* type() const { return _type->is_ptr(); } + const TypePtr* type() const { return _type->as_ptr(); } }; // This class wraps a bunch of context parameters that are passed around in the @@ -124,7 +126,7 @@ class C2Access: public StackObj { Node* base() const { return _base; } C2AccessValuePtr& addr() const { return _addr; } BasicType type() const { return _type; } - bool is_oop() const { return is_reference_type(_type); } + bool is_oop() const { return is_reference_type(_type) || (_decorators & C2_SPECIAL_ACCESS) != 0; } bool is_raw() const { return (_decorators & AS_RAW) != 0; } Node* raw_access() const { return _raw_access; } @@ -166,8 +168,8 @@ class C2ParseAccess: public C2Access { Node* control() const; const ValueTypeNode* vt() const { return _vt; } - virtual PhaseGVN& gvn() const; - virtual bool is_parse_access() const { return true; } + PhaseGVN& gvn() const override; + bool is_parse_access() const override { return true; } }; // This class wraps a bunch of context parameters that are passed around in the diff --git a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp index eda65eccdf45..769f31fa7dfe 100644 --- a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp @@ -52,7 +52,9 @@ Node* CardTableBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& vt = static_cast(access).vt(); } - if (vt == nullptr && (!access.is_oop() || tightly_coupled_alloc || (!in_heap && !anonymous))) { + // A parse-time store can omit the post barrier only when ReduceInitialCardMarks is enabled + const bool omit_for_tightly_coupled = tightly_coupled_alloc && (!access.is_parse_access() || use_ReduceInitialCardMarks()); + if (vt == nullptr && (!access.is_oop() || omit_for_tightly_coupled || (!in_heap && !anonymous))) { return BarrierSetC2::store_at_resolved(access, val); } @@ -85,6 +87,7 @@ Node* CardTableBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& Node* CardTableBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val, Node* new_val, const Type* value_type) const { + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type); } @@ -100,6 +103,7 @@ Node* CardTableBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess Node* new_val, const Type* value_type) const { GraphKit* kit = access.kit(); + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type); } @@ -129,6 +133,7 @@ Node* CardTableBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess Node* CardTableBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const { Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, new_val, value_type); + assert((access.decorators() & C2_SPECIAL_ACCESS) == 0, "access shouldn't be special"); if (!access.is_oop()) { return result; } diff --git a/src/hotspot/share/gc/shared/gc_globals.hpp b/src/hotspot/share/gc/shared/gc_globals.hpp index 2eeee2b0cac6..518da57832ff 100644 --- a/src/hotspot/share/gc/shared/gc_globals.hpp +++ b/src/hotspot/share/gc/shared/gc_globals.hpp @@ -205,18 +205,6 @@ constexpr uint MaxGCCardSizeInBytes = NOT_LP64(512) LP64_ONLY(1024); "for reference processing for parallel stop-the-world garbage " \ "collectors. Specify 0 to force use of all available threads.") \ \ - product(uint, InitiatingHeapOccupancyPercent, 45, \ - "The percent occupancy (IHOP) of the current old generation " \ - "capacity above which a concurrent mark cycle will be initiated " \ - "Its value may change over time if adaptive IHOP is enabled, " \ - "otherwise the value remains constant. " \ - "In the latter case a value of 0 will result as frequent as " \ - "possible concurrent marking cycles. A value of 100 disables " \ - "concurrent marking. " \ - "Fragmentation waste in the old generation is not considered " \ - "free space in this calculation. (G1 collector only)") \ - range(0, 100) \ - \ develop(bool, ScavengeALot, false, \ "Force scavenge at every Nth exit from the runtime system " \ "(N=ScavengeALotInterval)") \ diff --git a/src/hotspot/share/gc/shared/partialArraySplitter.cpp b/src/hotspot/share/gc/shared/partialArraySplitter.cpp index 68f494eb67ec..3813ff430f2b 100644 --- a/src/hotspot/share/gc/shared/partialArraySplitter.cpp +++ b/src/hotspot/share/gc/shared/partialArraySplitter.cpp @@ -26,13 +26,17 @@ #include "gc/shared/partialArrayState.hpp" #include "utilities/macros.hpp" -PartialArraySplitter::PartialArraySplitter(PartialArrayStateManager* manager, - uint num_workers) - : _allocator(manager), +PartialArraySplitter::PartialArraySplitter(uint num_workers) + : _allocator(), _stepper(num_workers) TASKQUEUE_STATS_ONLY(COMMA _stats()) {} +void PartialArraySplitter::reset() { + _allocator.reset(); + TASKQUEUE_STATS_ONLY(_stats.reset();) +} + #if TASKQUEUE_STATS PartialArrayTaskStats* PartialArraySplitter::stats() { return &_stats; diff --git a/src/hotspot/share/gc/shared/partialArraySplitter.hpp b/src/hotspot/share/gc/shared/partialArraySplitter.hpp index 017e5696004d..ff86a98dd2ab 100644 --- a/src/hotspot/share/gc/shared/partialArraySplitter.hpp +++ b/src/hotspot/share/gc/shared/partialArraySplitter.hpp @@ -35,6 +35,13 @@ // Each worker uses its own splitter to scan arrays in parallel. // Queued tasks share an atomic progress record; each claim returns a // disjoint, self-contained chunk and decrements the record's remaining chunk count. +// +// Each splitter owns its allocator, but work stealing can put slots from one +// splitter's arena on another splitter's free-list. Before resetting or +// destroying any splitter, all workers that can exchange partial-array tasks +// must have stopped using states. All their splitters must be reset or +// destroyed before any worker resumes processing. Cleanup never traverses +// free-lists, whose entries may belong to an already reclaimed arena. class PartialArraySplitter { PartialArrayStateAllocator _allocator; PartialArrayTaskStepper _stepper; @@ -45,12 +52,15 @@ class PartialArraySplitter { void enqueue(Queue* queue, PartialArrayState* state, uint count); public: - PartialArraySplitter(PartialArrayStateManager* manager, - uint num_workers); + explicit PartialArraySplitter(uint num_workers); ~PartialArraySplitter() = default; NONCOPYABLE(PartialArraySplitter); + // Reclaim states and reset statistics. Requires the worker quiescence and + // coordinated cleanup described above. + void reset(); + // A chunk remains valid after its progress record has been recycled. It // does not own or keep the array alive; that is the collector's responsibility. struct Claim { diff --git a/src/hotspot/share/gc/shared/partialArrayState.cpp b/src/hotspot/share/gc/shared/partialArrayState.cpp index a437a81ac7da..91f626e8dd75 100644 --- a/src/hotspot/share/gc/shared/partialArrayState.cpp +++ b/src/hotspot/share/gc/shared/partialArrayState.cpp @@ -57,18 +57,16 @@ class PartialArrayStateAllocator::FreeListEntry { NONCOPYABLE(FreeListEntry); }; -PartialArrayStateAllocator::PartialArrayStateAllocator(PartialArrayStateManager* manager) - : _manager(manager), - _free_list(), - _arena(manager->register_allocator()) +PartialArrayStateAllocator::PartialArrayStateAllocator() + : _free_list(), + _arena(mtGC) {} -PartialArrayStateAllocator::~PartialArrayStateAllocator() { - // We don't need to clean up the free list. Deallocating the entries - // does nothing, since we're using arena allocation. Instead, leave it - // to the manager to release the memory. - // Inform the manager that an allocator is no longer in use. - _manager->release_allocator(); +void PartialArrayStateAllocator::reset() { + _free_list = nullptr; + // Restore the arena to its freshly constructed state, i.e. destructor-then-constructor. + _arena.~Arena(); + ::new (&_arena) Arena(mtGC); } PartialArrayState* PartialArrayStateAllocator::allocate(objArrayOop array, @@ -78,7 +76,7 @@ PartialArrayState* PartialArrayStateAllocator::allocate(objArrayOop array, void* p; FreeListEntry* head = _free_list; if (head == nullptr) { - p = NEW_ARENA_OBJ(_arena, PartialArrayState); + p = NEW_ARENA_OBJ(&_arena, PartialArrayState); } else { _free_list = head->_next; head->~FreeListEntry(); @@ -98,40 +96,3 @@ void PartialArrayStateAllocator::release(PartialArrayState* state) { _free_list = ::new (state) FreeListEntry(_free_list); } } - -PartialArrayStateManager::PartialArrayStateManager(uint max_allocators) - : _arenas(NEW_C_HEAP_ARRAY(Arena, max_allocators, mtGC)), - _max_allocators(max_allocators), - _registered_allocators(0) - DEBUG_ONLY(COMMA _released_allocators(0)) -{} - -PartialArrayStateManager::~PartialArrayStateManager() { - reset(); - FREE_C_HEAP_ARRAY(_arenas); -} - -Arena* PartialArrayStateManager::register_allocator() { - assert(_released_allocators.load_relaxed() == 0, "allocator destruction has begun"); - uint idx = _registered_allocators.fetch_then_add(1u, memory_order_relaxed); - assert(idx < _max_allocators, "exceeded configured max number of allocators"); - return ::new (&_arenas[idx]) Arena(mtGC); -} - -#ifdef ASSERT -void PartialArrayStateManager::release_allocator() { - uint old = _released_allocators.fetch_then_add(1u, memory_order_relaxed); - assert(old < _registered_allocators.load_relaxed(), "too many releases"); -} -#endif // ASSERT - -void PartialArrayStateManager::reset() { - uint count = _registered_allocators.load_relaxed(); - assert(count == _released_allocators.load_relaxed(), - "some allocators still active"); - for (uint i = 0; i < count; ++i) { - _arenas[i].~Arena(); - } - _registered_allocators.store_relaxed(0u); - DEBUG_ONLY(_released_allocators.store_relaxed(0u);) -} diff --git a/src/hotspot/share/gc/shared/partialArrayState.hpp b/src/hotspot/share/gc/shared/partialArrayState.hpp index 207c6ce0dec1..ddc4d72fcea0 100644 --- a/src/hotspot/share/gc/shared/partialArrayState.hpp +++ b/src/hotspot/share/gc/shared/partialArrayState.hpp @@ -26,15 +26,14 @@ #define SHARE_GC_SHARED_PARTIALARRAYSTATE_HPP #include "memory/allocation.hpp" +#include "memory/arena.hpp" #include "oops/oopsHierarchy.hpp" #include "runtime/atomic.hpp" #include "utilities/debug.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/macros.hpp" -class Arena; class PartialArrayStateAllocator; -class PartialArrayStateManager; // Instances of this class are used to represent processing progress for an // array task in a taskqueue. When a sufficiently large array needs to be @@ -86,107 +85,52 @@ class PartialArrayState { // This class provides memory management for PartialArrayStates. // -// States are initially arena allocated from the manager, using a per-thread -// allocator. This allows the entire set of allocated states to be discarded -// without the need to keep track of or find them under some circumstances. +// Each per-thread allocator owns an arena for allocating states. This allows +// the entire set of allocated states to be discarded without the need to keep +// track of or find them under some circumstances. // For example, if G1 concurrent marking is aborted and needs to restart // because of a full marking queue, the queue doesn't need to be searched for // tasks referring to states to allow releasing them. Instead the queue // contents can just be discarded, and the memory for the no longer referenced -// states will eventually be reclaimed when the arena is reset. +// states will be reclaimed when the allocator is reset or destroyed. // // The allocators each provide a free-list of states. When a state is // released and its remaining chunk count has reached zero, it is added to the -// allocator's free-list, for use by future allocation requests. This causes -// the maximum number of allocated states to be based on the number of -// in-progress arrays, rather than the total number of arrays that need to be -// processed. +// allocator's free-list, for use by future allocation requests. +// +// A state may be allocated from one allocator's arena and recycled on another +// allocator's free-list after work stealing. Reclamation follows the owning +// splitter's lifetime contract and is coordinated by the collector. +// Before reclaiming any arena, all workers that can exchange partial-array tasks +// must have stopped using states. All their allocators must be reset/destroyed +// before processing resumes. Cleanup does not traverse free-lists, whose +// entries may belong to an already reclaimed arena. // // An allocator object is not thread-safe. -class PartialArrayStateAllocator : public CHeapObj { +class PartialArrayStateAllocator { class FreeListEntry; - PartialArrayStateManager* _manager; FreeListEntry* _free_list; - Arena* _arena; + Arena _arena; public: - explicit PartialArrayStateAllocator(PartialArrayStateManager* manager); - ~PartialArrayStateAllocator(); + PartialArrayStateAllocator(); + ~PartialArrayStateAllocator() = default; NONCOPYABLE(PartialArrayStateAllocator); + // Reclaim states and reconstruct the arena. Called only by the owning + // splitter after all workers have stopped using states. + void reset(); + PartialArrayState* allocate(objArrayOop array, size_t index, size_t length, size_t chunk_size); // Decrement the state's remaining chunk count by one. If it reaches zero, // recycle on this allocator's free-list. The caller must have finished - // accessing the state. The state must belong to the same manager. + // accessing the state. void release(PartialArrayState* state); }; -// This class provides memory management for PartialArrayStates. -// -// States are allocated using an allocator object. Those allocators in turn -// may request memory for a state from their associated manager. The manager -// is responsible for obtaining and releasing memory used for states by the -// associated allocators. -// -// A state may be allocated by one allocator, but end up on the free-list of a -// different allocator. This can happen because a task referring to the state -// may be stolen from the queue where it was initially added. This is permitted -// because a state's memory won't be reclaimed until all of the allocators -// associated with the manager that is ultimately providing the memory have -// been deleted and the manager is reset. -// -// A manager is used in two distinct and non-overlapping phases. -// -// - allocating: This is the initial phase. During this phase, new allocators -// may be created, and allocators may request memory from the manager. -// -// - releasing: When an allocator is destroyed the manager transitions to this -// phase. It remains in this phase until all extent allocators associated with -// this manager have been destroyed. During this phase, new allocators may not -// be created, nor may extent allocators request memory from this manager. -// -// Once all the associated allocators have been destroyed the releasing phase -// ends and the manager may be reset or deleted. Resetting transitions back -// to the allocating phase. -class PartialArrayStateManager : public CHeapObj { - friend class PartialArrayStateAllocator; - - // Use an arena for each allocator, for thread-safe concurrent allocation by - // different allocators. - Arena* _arenas; - - // Limit on the number of allocators this manager supports. - uint _max_allocators; - - // The number of allocators that have been registered/released. - // Atomic to support concurrent registration, and concurrent release. - // Phasing restriction forbids registration concurrent with release. - Atomic _registered_allocators; - DEBUG_ONLY(Atomic _released_allocators;) - - // These are all for sole use of the befriended allocator class. - Arena* register_allocator(); - void release_allocator() NOT_DEBUG_RETURN; - -public: - explicit PartialArrayStateManager(uint max_allocators); - - // Release the memory that has been requested by allocators associated with - // this manager. - // precondition: all associated allocators have been deleted. - ~PartialArrayStateManager(); - - NONCOPYABLE(PartialArrayStateManager); - - // Recycle the memory that has been requested by allocators associated with - // this manager. - // precondition: all associated allocators have been deleted. - void reset(); -}; - #endif // SHARE_GC_SHARED_PARTIALARRAYSTATE_HPP diff --git a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp index 507fdc4777b0..20061cb2647b 100644 --- a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp @@ -320,7 +320,7 @@ uint8_t ShenandoahBarrierSetC2::refine_store(Node* n, uint8_t bd) { // Type system tells us something about nullity? const Type* newval_bottom = newval->bottom_type(); - assert(newval_bottom->isa_oopptr() || newval_bottom->isa_narrowoop() || + assert(newval_bottom->is_oopptr() || newval_bottom->is_narrowoop() || newval_bottom == TypePtr::NULL_PTR, "Should be an oop store"); const TypePtr* newval_type = newval_bottom->make_ptr(); assert(newval_type != nullptr, "Should have been filtered before"); @@ -569,9 +569,9 @@ bool ShenandoahBarrierSetC2::clone_needs_barrier(const TypeOopPtr* src_type, boo return false; } - if (src_type->isa_instptr() != nullptr) { + if (src_type->is_instptr()) { // Instance: need barrier only if there is a possibility of having an oop anywhere in it. - ciInstanceKlass* ik = src_type->is_instptr()->instance_klass(); + ciInstanceKlass* ik = src_type->as_instptr()->instance_klass(); if ((src_type->klass_is_exact() || !ik->has_subklass()) && !ik->has_injected_fields() && !ik->has_object_fields()) { if (!src_type->klass_is_exact()) { @@ -581,9 +581,9 @@ bool ShenandoahBarrierSetC2::clone_needs_barrier(const TypeOopPtr* src_type, boo } return false; } - } else if (src_type->isa_aryptr() != nullptr) { + } else if (src_type->is_aryptr()) { // Array: need barrier only if array is oop-bearing. - BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type(); + BasicType src_elem = src_type->as_aryptr()->elem()->array_element_basic_type(); if (is_reference_type(src_elem, true) && src_type->is_not_flat()) { is_oop_array = true; } else if (!src_type->is_not_flat()) { @@ -598,7 +598,7 @@ bool ShenandoahBarrierSetC2::clone_needs_barrier(const TypeOopPtr* src_type, boo } void ShenandoahBarrierSetC2::clone(GraphKit* kit, Node* src_base, Node* dst_base, Node* size, bool is_array) const { - const TypeOopPtr* src_type = kit->gvn().type(src_base)->is_oopptr(); + const TypeOopPtr* src_type = kit->gvn().type(src_base)->as_oopptr(); bool is_oop_array = false; if (!clone_needs_barrier(src_type, is_oop_array)) { @@ -641,7 +641,7 @@ void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCo Node* const dest_offset = ac->in(ArrayCopyNode::DestPos); Node* length = ac->in(ArrayCopyNode::Length); - const TypeOopPtr* src_type = phase->igvn().type(src)->is_oopptr(); + const TypeOopPtr* src_type = phase->igvn().type(src)->as_oopptr(); bool is_oop_array = false; if (!clone_needs_barrier(src_type, is_oop_array)) { @@ -663,7 +663,7 @@ void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCo // This is the full clone, so offsets should equal each other and be at array base. assert(src_offset == dest_offset, "should be equal"); const jlong offset = src_offset->get_long(); - const TypeAryPtr* const ary_ptr = src->get_ptr_type()->isa_aryptr(); + const TypeAryPtr* const ary_ptr = src->get_ptr_type()->as_aryptr(); BasicType bt = ary_ptr->elem()->array_element_basic_type(); if (offset != arrayOopDesc::base_offset_in_bytes(bt)) { // Something is off with flat arrays. Go to runtime instead. @@ -816,12 +816,12 @@ void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase p bool is_native = (bd & ShenandoahBitNative) != 0; bool is_referent = adr_type != nullptr && - adr_type->isa_instptr() && - adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) && - adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset(); + adr_type->is_instptr() && + adr_type->as_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) && + adr_type->as_instptr()->offset() == java_lang_ref_Reference::referent_offset(); - bool is_oop_addr = (adr_type != nullptr) && (adr_type->isa_oopptr() || adr_type->isa_narrowoop()); - bool is_raw_addr = (adr_type != nullptr) && (adr_type->isa_rawptr() || adr_type->isa_klassptr()); + bool is_oop_addr = (adr_type != nullptr) && (adr_type->is_oopptr() || adr_type->is_narrowoop()); + bool is_raw_addr = (adr_type != nullptr) && (adr_type->is_rawptr() || adr_type->is_klassptr()); verify_gc_barrier_assert(!expect_some_real || (bd == 0) || (bd & ShenandoahBitsReal) != 0, "Without real barriers, metadata should be stripped at this point", bd, n); diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp index 88b5292e38f8..4ffceedf73e4 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp @@ -64,6 +64,10 @@ ShenandoahAdaptiveHeuristics::ShenandoahAdaptiveHeuristics(ShenandoahSpaceInfo* _last_trigger(OTHER), _available(Moving_Average_Samples), _headroom_adjustment(0) { + if (ShenandoahHeuristicsFlag::value() == ShenandoahHeuristicsFlag::Heuristic::PASSIVE && !UnlockDiagnosticVMOptions) { + vm_exit_during_initialization(err_msg( + "Heuristics \"Passive\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.")); + } } void ShenandoahAdaptiveHeuristics::initialize() { diff --git a/src/hotspot/share/gc/shenandoah/mode/shenandoahGenerationalMode.cpp b/src/hotspot/share/gc/shenandoah/mode/shenandoahGenerationalMode.cpp index 6a0e6c84700a..0d7b7de8596b 100644 --- a/src/hotspot/share/gc/shenandoah/mode/shenandoahGenerationalMode.cpp +++ b/src/hotspot/share/gc/shenandoah/mode/shenandoahGenerationalMode.cpp @@ -66,6 +66,9 @@ void ShenandoahGenerationalMode::initialize_flags() const { case ShenandoahHeuristicsFlag::Heuristic::STATIC: // Nothing to do, static mode just checks min free threshold which adaptive also does break; + case ShenandoahHeuristicsFlag::Heuristic::PASSIVE: + // This is also acceptable, but will be handled in the regulator thread + break; case ShenandoahHeuristicsFlag::Heuristic::COMPACT: // Configure flags in accordance with the heuristic ShenandoahCompactHeuristics::configure(); diff --git a/src/hotspot/share/gc/shenandoah/mode/shenandoahMode.cpp b/src/hotspot/share/gc/shenandoah/mode/shenandoahMode.cpp index 8eea2aa4f599..594c9b9c9ec7 100644 --- a/src/hotspot/share/gc/shenandoah/mode/shenandoahMode.cpp +++ b/src/hotspot/share/gc/shenandoah/mode/shenandoahMode.cpp @@ -53,6 +53,9 @@ ShenandoahHeuristics* ShenandoahMode::initialize_heuristics(ShenandoahSpaceInfo* case ShenandoahHeuristicsFlag::Heuristic::STATIC: return new ShenandoahStaticHeuristics(space_info); case ShenandoahHeuristicsFlag::Heuristic::ADAPTIVE: + case ShenandoahHeuristicsFlag::Heuristic::PASSIVE: + // Passive flag gets regular heuristics for collection set construction, but + // adaptive heuristic triggers will be suppressed. return new ShenandoahAdaptiveHeuristics(space_info); case ShenandoahHeuristicsFlag::Heuristic::COMPACT: return new ShenandoahCompactHeuristics(space_info); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp index 753d564a647f..99d523f3e0b3 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp @@ -24,6 +24,7 @@ #include "code/relocInfo.hpp" +#include "gc/shenandoah/shenandoahBarrierSet.inline.hpp" #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp" #include "gc/shenandoah/shenandoahBarrierSetNMethod.hpp" #include "gc/shenandoah/shenandoahClosures.inline.hpp" @@ -132,3 +133,15 @@ void ShenandoahBarrierSetNMethod::arm_all_nmethods() { // All currently allocated stack chunks now need to be fixed up. ShenandoahStackChunkGCData::change_epoch_id(); } + +oop ShenandoahBarrierSetNMethod::oop_load_no_keepalive(const nmethod* nm, int index) { + // nmethod oops are fixed by nmethod entry barriers. Do not allow LRB to fix the nmethod slots here. + oop obj = RawAccess<>::oop_load(nm->oop_addr_at(index)); + return ShenandoahBarrierSet::barrier_set()->oop_load_post(IN_NATIVE | ON_STRONG_OOP_REF | AS_NO_KEEPALIVE, obj, (oop*)nullptr); +} + +oop ShenandoahBarrierSetNMethod::oop_load_phantom(const nmethod* nm, int index) { + // nmethod oops are fixed by nmethod entry barriers. Do not allow LRB to fix the nmethod slots here. + oop obj = RawAccess<>::oop_load(nm->oop_addr_at(index)); + return ShenandoahBarrierSet::barrier_set()->oop_load_post(IN_NATIVE | ON_PHANTOM_OOP_REF, obj, (oop*)nullptr); +} diff --git a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.hpp b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.hpp index 36ee39330bba..99d57ec5f932 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.hpp @@ -46,6 +46,9 @@ class ShenandoahBarrierSetNMethod : public BarrierSetNMethod { void finalize_relocations(nmethod* nm) override; void arm_all_nmethods() override; + + oop oop_load_no_keepalive(const nmethod* nm, int index) override; + oop oop_load_phantom(const nmethod* nm, int index) override; }; #endif // SHARE_GC_SHENANDOAH_SHENANDOAHBARRIERSETNMETHOD_HPP diff --git a/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp b/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp index 6991916dd951..c985acece6a8 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp @@ -45,6 +45,16 @@ ShenandoahControlThread::ShenandoahControlThread() { create_and_start(); } +bool ShenandoahControlThread::should_start_gc(ShenandoahHeuristics* const heuristics) { + if (heuristics->has_metaspace_oom()) { + // metaspace oom bypasses passive heuristic trigger suppression + return heuristics->should_start_gc(); + } + + return ShenandoahHeuristicsFlag::value() != ShenandoahHeuristicsFlag::Heuristic::PASSIVE + && heuristics->should_start_gc(); +} + void ShenandoahControlThread::run_service() { ShenandoahHeap* const heap = ShenandoahHeap::heap(); constexpr GCMode default_mode = concurrent_normal; @@ -81,7 +91,7 @@ void ShenandoahControlThread::run_service() { // Unload and clean up everything heap->set_unload_classes(heuristics->can_unload_classes()); } - } else if (heuristics->should_start_gc()) { + } else if (should_start_gc(heuristics)) { // Nobody requested a cycle, but heuristics want to run one mode = default_mode; cause = default_cause; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahControlThread.hpp b/src/hotspot/share/gc/shenandoah/shenandoahControlThread.hpp index ac9d6f365a8a..3aa7073ae69c 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahControlThread.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahControlThread.hpp @@ -30,6 +30,7 @@ #include "gc/shenandoah/shenandoahSharedVariables.hpp" class ShenandoahGeneration; +class ShenandoahHeuristics; class ShenandoahControlThread: public ShenandoahController { typedef enum { @@ -50,6 +51,8 @@ class ShenandoahControlThread: public ShenandoahController { void notify_alloc_stall(GCCause::Cause cause) override; private: + static bool should_start_gc(ShenandoahHeuristics* heuristics); + void service_concurrent_normal_cycle(GCCause::Cause cause); void service_stw_full_cycle(GCCause::Cause cause); }; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahMark.hpp b/src/hotspot/share/gc/shenandoah/shenandoahMark.hpp index b3e42305b55b..162763bdf629 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahMark.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahMark.hpp @@ -97,8 +97,9 @@ class ShenandoahMark: public StackObj { ALWAYSINLINE static void mark_non_generational_ref(T *p, ShenandoahObjToScanQueue* q, ShenandoahMarkingContext* const mark_context, bool weak); + template ALWAYSINLINE - static void mark_ref(ShenandoahObjToScanQueue* q, ShenandoahMarkingContext* const mark_context, bool weak, oop obj); + static void mark_ref(T* p, ShenandoahObjToScanQueue* q, ShenandoahMarkingContext* const mark_context, bool weak, oop obj); ALWAYSINLINE static void dedup_string(oop obj, StringDedup::Requests* const req); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahMark.inline.hpp b/src/hotspot/share/gc/shenandoah/shenandoahMark.inline.hpp index 668b951abd1a..3421dcdfc328 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahMark.inline.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahMark.inline.hpp @@ -343,11 +343,8 @@ void ShenandoahMark::mark_through_ref(T *p, ShenandoahObjToScanQueue* q, Shenand ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap(); oop obj = CompressedOops::decode_not_null(o); - shenandoah_assert_not_forwarded(p, obj); - shenandoah_assert_not_in_cset_except(p, obj, heap->cancelled_gc()); if (in_generation(heap, obj)) { - mark_ref(q, mark_context, weak, obj); - shenandoah_assert_marked(p, obj); + mark_ref(p, q, mark_context, weak, obj); if (REDIRTY && heap->has_affiliation(p, OLD_GENERATION)) { // We are redirtying the remembered set, the object iterator // may visit class metadata that lives outside the heap so we cannot @@ -361,8 +358,7 @@ void ShenandoahMark::mark_through_ref(T *p, ShenandoahObjToScanQueue* q, Shenand } } else if (old_q != nullptr) { // Young mark, bootstrapping old_q or concurrent with old_q marking. - mark_ref(old_q, mark_context, weak, obj); - shenandoah_assert_marked(p, obj); + mark_ref(p, old_q, mark_context, weak, obj); } else if (GENERATION == OLD) { // Old mark, found a young pointer. if (heap->is_in_reserved(p)) { @@ -386,21 +382,16 @@ void ShenandoahMark::mark_through_ref(narrowOop *p, S template void ShenandoahMark::mark_non_generational_ref(T* p, ShenandoahObjToScanQueue* q, - ShenandoahMarkingContext* const mark_context, bool weak) { + ShenandoahMarkingContext* const mark_context, bool weak) { oop o = RawAccess<>::oop_load(p); if (!CompressedOops::is_null(o)) { oop obj = CompressedOops::decode_not_null(o); - - shenandoah_assert_not_forwarded(p, obj); - shenandoah_assert_not_in_cset_except(p, obj, ShenandoahHeap::heap()->cancelled_gc() || ShenandoahHeap::heap()->has_self_forwarded_objects()); - - mark_ref(q, mark_context, weak, obj); - - shenandoah_assert_marked(p, obj); + mark_ref(p, q, mark_context, weak, obj); } } -inline void ShenandoahMark::mark_ref(ShenandoahObjToScanQueue* q, +template +inline void ShenandoahMark::mark_ref(T* p, ShenandoahObjToScanQueue* q, ShenandoahMarkingContext* const mark_context, bool weak, oop obj) { bool skip_live = false; @@ -412,6 +403,10 @@ inline void ShenandoahMark::mark_ref(ShenandoahObjToScanQueue* q, } if (marked) { ShenandoahPrefetch::prefetch(obj); + shenandoah_assert_not_forwarded(p, obj); + shenandoah_assert_not_in_cset_except(p, obj, ShenandoahHeap::heap()->cancelled_gc() || ShenandoahHeap::heap()->has_self_forwarded_objects()); + shenandoah_assert_marked(p, obj); + bool pushed = q->push(ShenandoahMarkTask(obj, skip_live, weak)); assert(pushed, "overflow queue should always succeed pushing"); } diff --git a/src/hotspot/share/gc/shenandoah/shenandoahRegulatorThread.cpp b/src/hotspot/share/gc/shenandoah/shenandoahRegulatorThread.cpp index 23bb91df86cc..ad42b0b8b815 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahRegulatorThread.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahRegulatorThread.cpp @@ -96,7 +96,8 @@ void ShenandoahRegulatorThread::regulate_young_and_global_cycles() { if (should_start_metaspace_gc() && request_concurrent_gc(_heap->global_generation())) { // Some of vmTestbase/metaspace tests depend on following line to count GC cycles _global_heuristics->log_trigger("%s", GCCause::to_string(GCCause::_metadata_GC_threshold)); - } else if (_old_heuristics->should_start_gc() && request_concurrent_gc(_heap->global_generation())) { + } else if (ShenandoahHeuristicsFlag::value() != ShenandoahHeuristicsFlag::Heuristic::PASSIVE + && _old_heuristics->should_start_gc() && request_concurrent_gc(_heap->global_generation())) { log_debug(gc, thread)("Heuristics request for global collection accepted."); } else if (start_young_cycle()) { log_debug(gc, thread)("Heuristics request for young collection accepted."); @@ -133,11 +134,13 @@ void ShenandoahRegulatorThread::regulator_sleep() { } bool ShenandoahRegulatorThread::start_old_cycle() const { - return _old_heuristics->should_start_gc() && request_concurrent_gc(_heap->old_generation()); + return ShenandoahHeuristicsFlag::value() != ShenandoahHeuristicsFlag::Heuristic::PASSIVE + && _old_heuristics->should_start_gc() && request_concurrent_gc(_heap->old_generation()); } bool ShenandoahRegulatorThread::start_young_cycle() const { - return _young_heuristics->should_start_gc() && request_concurrent_gc(_heap->young_generation()); + return ShenandoahHeuristicsFlag::value() != ShenandoahHeuristicsFlag::Heuristic::PASSIVE + && _young_heuristics->should_start_gc() && request_concurrent_gc(_heap->young_generation()); } bool ShenandoahRegulatorThread::request_concurrent_gc(ShenandoahGeneration* generation) const { diff --git a/src/hotspot/share/gc/shenandoah/shenandoah_globals.hpp b/src/hotspot/share/gc/shenandoah/shenandoah_globals.hpp index 38a290ec5a02..88ef26615f58 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoah_globals.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoah_globals.hpp @@ -175,10 +175,10 @@ "of regions that would be used, within min/max region size " \ "limits.") \ \ - product(ccstr, ShenandoahGCMode, "satb", \ + product(ccstr, ShenandoahGCMode, "generational", \ "GC mode to use. Among other things, this defines which " \ "barriers are in in use. Possible values are:" \ - " satb - snapshot-at-the-beginning concurrent GC (three pass mark-evac-update);" \ + " satb - single generation, concurrent GCs" \ " passive - stop the world full GC only (diagnostic mode);" \ " generational - generational concurrent GC") \ \ diff --git a/src/hotspot/share/oops/flatArrayOop.hpp b/src/hotspot/share/oops/flatArrayOop.hpp index 6349539fe55c..01dd00837013 100644 --- a/src/hotspot/share/oops/flatArrayOop.hpp +++ b/src/hotspot/share/oops/flatArrayOop.hpp @@ -40,7 +40,7 @@ class flatArrayOopDesc : public objArrayOopDesc { inline FlatArrayKlass* klass() const; void* base() const; - static size_t base_offset_in_bytes(); + static int base_offset_in_bytes(); void* value_at_addr(int index, jint lh) const; size_t value_offset(int index, jint lh) const; size_t value_offset_from_base(int index, jint lh) const; diff --git a/src/hotspot/share/oops/flatArrayOop.inline.hpp b/src/hotspot/share/oops/flatArrayOop.inline.hpp index e4233999c4b6..310dee35bca9 100644 --- a/src/hotspot/share/oops/flatArrayOop.inline.hpp +++ b/src/hotspot/share/oops/flatArrayOop.inline.hpp @@ -42,8 +42,8 @@ inline FlatArrayKlass* flatArrayOopDesc::klass() const { inline void* flatArrayOopDesc::base() const { return arrayOopDesc::base(T_FLAT_ELEMENT); } -inline size_t flatArrayOopDesc::base_offset_in_bytes() { - return static_cast(arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT)); +inline int flatArrayOopDesc::base_offset_in_bytes() { + return arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT); } inline void* flatArrayOopDesc::value_at_addr(int index, jint lh) const { diff --git a/src/hotspot/share/oops/method.cpp b/src/hotspot/share/oops/method.cpp index f9c6abac607e..1b64c14e0e2b 100644 --- a/src/hotspot/share/oops/method.cpp +++ b/src/hotspot/share/oops/method.cpp @@ -455,12 +455,6 @@ void Method::metaspace_pointers_do(MetaspaceClosure* it) { void Method::remove_unshareable_info() { unlink_method(); - if (method_data() != nullptr) { - method_data()->remove_unshareable_info(); - } - if (method_counters() != nullptr) { - method_counters()->remove_unshareable_info(); - } if (CDSConfig::is_dumping_adapters() && _adapter != nullptr) { _adapter->remove_unshareable_info(); _adapter = nullptr; @@ -470,12 +464,6 @@ void Method::remove_unshareable_info() { void Method::restore_unshareable_info(TRAPS) { assert(is_method() && is_valid_method(this), "ensure C++ vtable is restored"); - if (method_data() != nullptr) { - method_data()->restore_unshareable_info(CHECK); - } - if (method_counters() != nullptr) { - method_counters()->restore_unshareable_info(CHECK); - } if (_adapter != nullptr) { assert(_adapter->is_linked(), "must be"); _from_compiled_entry = _adapter->get_c2i_entry(); @@ -1288,11 +1276,6 @@ void Method::unlink_method() { clear_method_data(); clear_method_counters(); - clear_is_not_c1_compilable(); - clear_is_not_c1_osr_compilable(); - clear_is_not_c2_compilable(); - clear_is_not_c2_osr_compilable(); - clear_queued_for_compilation(); remove_unshareable_flags(); } diff --git a/src/hotspot/share/oops/methodCounters.cpp b/src/hotspot/share/oops/methodCounters.cpp index 03accf0f8f7c..32f4b9ad20f4 100644 --- a/src/hotspot/share/oops/methodCounters.cpp +++ b/src/hotspot/share/oops/methodCounters.cpp @@ -111,12 +111,6 @@ void MethodCounters::set_aot_preload_code_entry(AOTCodeEntry* entry) { precond(entry == nullptr || entry->for_preload()); _aot_preload_code_entry = entry; } - -void MethodCounters::remove_unshareable_info() { -} -void MethodCounters::restore_unshareable_info(TRAPS) { - _method_training_data = method_training_data_sentinel(); -} #endif // INCLUDE_CDS void MethodCounters::print_on(outputStream* st) const { diff --git a/src/hotspot/share/oops/methodCounters.hpp b/src/hotspot/share/oops/methodCounters.hpp index 35f96baa6e9b..a45d9b84ca14 100644 --- a/src/hotspot/share/oops/methodCounters.hpp +++ b/src/hotspot/share/oops/methodCounters.hpp @@ -163,6 +163,9 @@ class MethodCounters : public Metadata { MethodTrainingData* method_training_data() const { return reinterpret_cast(_method_training_data); } + void clear_method_training_data() { + _method_training_data = nullptr; + } bool init_method_training_data(MethodTrainingData* td) { MethodTrainingData* cur = method_training_data(); if (cur == td) { @@ -180,8 +183,6 @@ class MethodCounters : public Metadata { return _aot_preload_code_entry; } - void remove_unshareable_info(); - void restore_unshareable_info(TRAPS); #endif // Printing diff --git a/src/hotspot/share/oops/trainingData.cpp b/src/hotspot/share/oops/trainingData.cpp index f826d4600385..eabeca333c15 100644 --- a/src/hotspot/share/oops/trainingData.cpp +++ b/src/hotspot/share/oops/trainingData.cpp @@ -233,7 +233,7 @@ void MethodTrainingData::print_on(outputStream* st, bool name_only) const { if (_iterations[NEXT]._level_mask) { st->print(" LMN%d", _iterations[NEXT]._level_mask); } - st->print(" mc=%p mdo=%p", _final_counters, _final_profile); + st->print(" mdo=%p", _final_profile); } CompileTrainingData* CompileTrainingData::make(CompileTask* task) { @@ -374,9 +374,9 @@ void KlassTrainingData::prepare(Visitor& visitor) { return; } visitor.visit(this); - for (int i = 0; i < comp_dep_count(); i++) { - CompileTrainingData* ctd = comp_dep(i); - visitor.visit_later(ctd);; + for (int i = 0; i < _comp_deps.length(); i++) { + CompileTrainingData* ctd = _comp_deps.at(i); + visitor.visit_later(ctd); } _comp_deps.prepare(); } @@ -412,8 +412,8 @@ void KlassTrainingData::merge(Visitor& visitor) { return; } visitor.visit(this); - for (int i = 0; i < comp_dep_count(); i++) { - CompileTrainingData* ctd = comp_dep(i); + for (int i = 0; i < _comp_deps.length(); i++) { + CompileTrainingData* ctd = _comp_deps.at(i); visitor.visit_later(ctd); } } @@ -435,8 +435,8 @@ void MethodTrainingData::prepare(Visitor& visitor) { } visitor.visit(this); visitor.visit_later(klass()); - if (has_holder()) { - _final_counters = holder()->method_counters(); + // Assembly must retain the profile captured during recording. + if (need_data() && has_holder()) { _final_profile = holder()->method_data(); assert(_final_profile == nullptr || _final_profile->method() == holder(), ""); _invocation_count = holder()->invocation_count(); @@ -583,16 +583,11 @@ void TrainingData::init_dumptime_table(TRAPS) { td->merge(merge_visitor); }); _dumptime_training_data_dictionary = new DumptimeTrainingDataDictionary(); - Visitor prepare_visitor(training_data_set()->size()); training_data_set()->iterate([&](TrainingData* td) { - td->prepare(prepare_visitor); if (!td->is_CompileTrainingData()) { _dumptime_training_data_dictionary->append(td); } }); - prepare_visitor.finish([&](TrainingData* td) { - td->prepare(prepare_visitor); - }); TrainingDataLocker::snapshot(); } @@ -650,6 +645,10 @@ void TrainingData::cleanup_training_data() { visitor.finish([&](TrainingData* td) { td->cleanup(visitor); }); + // Prune references only after all holders have been cleaned. + visitor.iterate_visited([](TrainingData* td) { + td->remove_invalid_references(); + }); // Throw away all elements with empty keys int j = 0; for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) { @@ -663,6 +662,15 @@ void TrainingData::cleanup_training_data() { j++; } _dumptime_training_data_dictionary->trunc_to(j); + + Visitor prepare_visitor(_dumptime_training_data_dictionary->length()); + for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) { + TrainingData* td = _dumptime_training_data_dictionary->at(i).training_data(); + td->prepare(prepare_visitor); + } + prepare_visitor.finish([&](TrainingData* td) { + td->prepare(prepare_visitor); + }); } } @@ -677,6 +685,10 @@ void TrainingData::cleanup_after_redefinition() { visitor.finish([&](TrainingData* td) { td->cleanup(visitor); }); + // Prune references only after all holders have been cleaned. + visitor.iterate_visited([](TrainingData* td) { + td->remove_invalid_references(); + }); } } @@ -703,11 +715,17 @@ void MethodTrainingData::cleanup(Visitor& visitor) { return; } visitor.visit(this); + visitor.visit_later(klass()); if (has_holder()) { if (is_excluded(holder()->method_holder())) { log_debug(aot, training)("Cleanup MTD %s::%s", name()->as_klass_external_name(), signature()->as_utf8()); + // MethodCounters can be archived even when training data for their + // holder is excluded (for example, for a custom-loader class). + MethodCounters* counters = holder()->method_counters(); + if (counters != nullptr) { + counters->clear_method_training_data(); + } _final_profile = nullptr; - _final_counters = nullptr; _holder = nullptr; key()->make_empty(); } @@ -727,8 +745,8 @@ void MethodTrainingData::cleanup(Visitor& visitor) { void KlassTrainingData::verify() { guarantee(!has_holder() || !is_excluded(holder()), "Bad holder"); - for (int i = 0; i < comp_dep_count(); i++) { - CompileTrainingData* ctd = comp_dep(i); + for (int i = 0; i < _comp_deps.length(); i++) { + CompileTrainingData* ctd = _comp_deps.at(i); if (!ctd->_init_deps.contains(this)) { print_on(tty); tty->cr(); ctd->print_on(tty); tty->cr(); @@ -745,8 +763,8 @@ void MethodTrainingData::verify(bool verify_dep_counter) { } void CompileTrainingData::verify(bool verify_dep_counter) { - for (int i = 0; i < init_dep_count(); i++) { - KlassTrainingData* ktd = init_dep(i); + for (int i = 0; i < _init_deps.length(); i++) { + KlassTrainingData* ktd = _init_deps.at(i); if (ktd->has_holder() && ktd->holder()->defined_by_other_loaders()) { LogStreamHandle(Info, training) log; if (log.is_enabled()) { @@ -757,7 +775,7 @@ void CompileTrainingData::verify(bool verify_dep_counter) { } if (!ktd->_comp_deps.contains(this)) { print_on(tty); tty->cr(); - ktd->print_on(tty); tty->print(" deps: %d", ktd->comp_dep_count()); tty->cr(); + ktd->print_on(tty); tty->print(" deps: %d", ktd->_comp_deps.length()); tty->cr(); } guarantee(ktd->_comp_deps.contains(this), ""); } @@ -781,6 +799,59 @@ void CompileTrainingData::cleanup(Visitor& visitor) { } visitor.visit(this); visitor.visit_later(method()); + for (int i = 0; i < _init_deps.length(); i++) { + visitor.visit_later(_init_deps.at(i)); + } + // CI record arguments are MethodTrainingData entries, which are cleanup roots. +} + +void KlassTrainingData::remove_invalid_references() { + if (!is_valid()) { + _comp_deps.clear(); + return; + } + int j = 0; + for (int i = 0; i < _comp_deps.length(); i++) { + CompileTrainingData* ctd = _comp_deps.at(i); + if (ctd->is_valid()) { + if (i != j) { + _comp_deps.at_put(j, ctd); + } + j++; + } + } + _comp_deps.trunc_to(j); +} + +void MethodTrainingData::remove_invalid_references() { + for (int i = 0; i < CompLevel_count - 1; i++) { + for (int iteration = CURRENT; iteration <= NEXT; iteration++) { + CompileTrainingData*& ctd = _iterations[iteration]._last_toplevel_compiles[i]; + if (ctd != nullptr && !ctd->is_valid()) { + ctd = nullptr; + } + } + } +} + +void CompileTrainingData::remove_invalid_references() { + if (!is_valid()) { + _init_deps.clear(); + _ci_records.clear(); + return; + } + int j = 0; + for (int i = 0; i < _init_deps.length(); i++) { + KlassTrainingData* ktd = _init_deps.at(i); + if (ktd->is_valid()) { + if (i != j) { + _init_deps.at_put(j, ktd); + } + j++; + } + } + _init_deps.trunc_to(j); + _ci_records.remove_invalid_references(); } void TrainingData::serialize(SerializeClosure* soc) { @@ -887,7 +958,6 @@ void MethodTrainingData::metaspace_pointers_do(MetaspaceClosure* iter) { iter->push(&(_iterations[NEXT]._last_toplevel_compiles[i])); } iter->push(&_final_profile); - iter->push(&_final_counters); } void CompileTrainingData::metaspace_pointers_do(MetaspaceClosure* iter) { @@ -917,9 +987,6 @@ void KlassTrainingData::remove_unshareable_info() { void MethodTrainingData::remove_unshareable_info() { TrainingData::remove_unshareable_info(); - if (_final_counters != nullptr) { - _final_counters->remove_unshareable_info(); - } if (_final_profile != nullptr) { _final_profile->remove_unshareable_info(); } diff --git a/src/hotspot/share/oops/trainingData.hpp b/src/hotspot/share/oops/trainingData.hpp index 314e708d8293..939265abcd3d 100644 --- a/src/hotspot/share/oops/trainingData.hpp +++ b/src/hotspot/share/oops/trainingData.hpp @@ -251,6 +251,10 @@ class TrainingData : public Metadata { _pending_visit_list.append(td); } template void finish(FUNC f); + template + void iterate_visited(FUNC f) const { + _visited.iterate_all([&](TrainingData* td, bool unused) { f(td); }); + } }; typedef OffsetCompactHashtable TrainingDataDictionary; @@ -330,6 +334,8 @@ class TrainingData : public Metadata { virtual void prepare(Visitor& visitor) = 0; virtual void merge(Visitor& visitor) = 0; virtual void cleanup(Visitor& visitor) = 0; + virtual void remove_invalid_references() = 0; + virtual bool is_valid() const = 0; static void initialize() NOT_CDS_RETURN; @@ -354,15 +360,6 @@ class TrainingData : public Metadata { _deps = nullptr; } } - void at_put(int i, E dep) const { - TrainingDataLocker::assert_locked_or_snapshotted(); - assert(i >= 0 && i < length(), "oob"); - if (_deps_dyn != nullptr) { - return _deps_dyn->at_put(i, dep); - } else if (_deps != nullptr) { - return _deps->at_put(i, dep); - } else ShouldNotReachHere(); - } public: DepList() { _deps_dyn = nullptr; @@ -384,6 +381,15 @@ class TrainingData : public Metadata { return _deps->at(i); } else ShouldNotReachHere(); } + void at_put(int i, E dep) const { + TrainingDataLocker::assert_locked_or_snapshotted(); + assert(i >= 0 && i < length(), "oob"); + if (_deps_dyn != nullptr) { + return _deps_dyn->at_put(i, dep); + } else if (_deps != nullptr) { + return _deps->at_put(i, dep); + } else ShouldNotReachHere(); + } bool append_if_missing(E dep) { TrainingDataLocker::assert_can_add(); copy_on_write_if_necessary(); @@ -404,7 +410,7 @@ class TrainingData : public Metadata { return false; } void clear() { - TrainingDataLocker::assert_can_add(); + TrainingDataLocker::assert_locked_or_snapshotted(); if (_deps_dyn != nullptr) { _deps_dyn->clear(); } @@ -441,6 +447,14 @@ class TrainingData : public Metadata { append(new_dep); } } + void trunc_to(int length) { + TrainingDataLocker::assert_locked_or_snapshotted(); + assert(length >= 0 && length <= this->length(), "oob"); + if (length != this->length()) { + copy_on_write_if_necessary(); + _deps_dyn->trunc_to(length); + } + } #if INCLUDE_CDS void remove_unshareable_info() { @@ -536,6 +550,8 @@ class KlassTrainingData : public TrainingData { virtual void prepare(Visitor& visitor); virtual void merge(Visitor& visitor); virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN; + virtual void remove_invalid_references() NOT_CDS_RETURN; + virtual bool is_valid() const; MetaspaceObj::Type type() const { return KlassTrainingDataType; @@ -564,8 +580,8 @@ class KlassTrainingData : public TrainingData { template void iterate_comp_deps(Function fn) const { // lambda enabled API TrainingDataLocker l; - for (int i = 0; i < comp_dep_count(); i++) { - fn(comp_dep(i)); + for (int i = 0; i < _comp_deps.length(); i++) { + fn(_comp_deps.at(i)); } } }; @@ -665,6 +681,7 @@ class CompileTrainingData : public TrainingData { bool operator==(const Arguments<>&) const { return true; } void metaspace_pointers_do(MetaspaceClosure *iter) { } void prepare(Visitor& visitor) { } + bool is_valid() const { return true; } }; template class Arguments { private: @@ -698,6 +715,14 @@ class CompileTrainingData : public TrainingData { void prepare(Visitor& visitor) { _remaining.prepare(visitor); } + template::value && std::is_base_of::type>::value)> + bool is_valid() const { + return (_first == nullptr || _first->is_valid()) && _remaining.is_valid(); + } + template::value && std::is_base_of::type>::value))> + bool is_valid() const { + return _remaining.is_valid(); + } }; template class ciMemoizedFunction : public StackObj { @@ -723,6 +748,7 @@ class CompileTrainingData : public TrainingData { bool operator==(const Record& that) { return _arguments == that._arguments; } void metaspace_pointers_do(MetaspaceClosure *iter) { _arguments.metaspace_pointers_do(iter); } void prepare(Visitor& visitor) { _arguments.prepare(visitor); } + bool is_valid() const { return _arguments.is_valid(); } }; DepList _data; public: @@ -752,6 +778,22 @@ class CompileTrainingData : public TrainingData { } _data.prepare(); } + void remove_invalid_references() { + int j = 0; + for (int i = 0; i < _data.length(); i++) { + Record record = _data.at(i); + if (record.is_valid()) { + if (i != j) { + _data.at_put(j, record); + } + j++; + } + } + _data.trunc_to(j); + } + void clear() { + _data.clear(); + } void metaspace_pointers_do(MetaspaceClosure *iter) { _data.metaspace_pointers_do(iter); } @@ -771,6 +813,12 @@ class CompileTrainingData : public TrainingData { void prepare(Visitor& visitor) { ciMethod__inline_instructions_size.prepare(visitor); } + void remove_invalid_references() { + ciMethod__inline_instructions_size.remove_invalid_references(); + } + void clear() { + ciMethod__inline_instructions_size.clear(); + } void metaspace_pointers_do(MetaspaceClosure *iter) { ciMethod__inline_instructions_size.metaspace_pointers_do(iter); } @@ -836,6 +884,9 @@ class CompileTrainingData : public TrainingData { virtual void prepare(Visitor& visitor); virtual void merge(Visitor& visitor); virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN; + virtual void remove_invalid_references() NOT_CDS_RETURN; + // Validity depends on the method's holder surviving cleanup. + virtual bool is_valid() const; void print_on(outputStream* st, bool name_only) const; virtual void print_on(outputStream* st) const { print_on(st, false); } @@ -889,7 +940,6 @@ class MethodTrainingData : public TrainingData { }; TrainingIteration _iterations[2]; // CURRENT and NEXT // metadata snapshots of final state: - MethodCounters* _final_counters; MethodData* _final_profile; int _invocation_count; @@ -971,6 +1021,8 @@ class MethodTrainingData : public TrainingData { virtual void prepare(Visitor& visitor); virtual void merge(Visitor& visitor); virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN; + virtual void remove_invalid_references() NOT_CDS_RETURN; + virtual bool is_valid() const; template void iterate_compiles(Function fn) const { // lambda enabled API @@ -1008,4 +1060,9 @@ class MethodTrainingData : public TrainingData { return TrainingData::allocate(m, ktd); } }; + +inline bool KlassTrainingData::is_valid() const { return has_holder(); } +inline bool CompileTrainingData::is_valid() const { return method()->has_holder(); } +inline bool MethodTrainingData::is_valid() const { return has_holder(); } + #endif // SHARE_OOPS_TRAININGDATA_HPP diff --git a/src/hotspot/share/oops/valuePayload.inline.hpp b/src/hotspot/share/oops/valuePayload.inline.hpp index c11264fad245..75e5932def64 100644 --- a/src/hotspot/share/oops/valuePayload.inline.hpp +++ b/src/hotspot/share/oops/valuePayload.inline.hpp @@ -272,8 +272,7 @@ inline void ValuePayload::assert_post_construction_invariants() const { // Accessing nested flat field const ValueKlass* const element_klass = container_flat_array_klass->element_klass(); const int element_offset = - (checked_cast(this->offset()) - - checked_cast(flatArrayOopDesc::base_offset_in_bytes())) % + (this->offset() - flatArrayOopDesc::base_offset_in_bytes()) % container_flat_array_klass->element_byte_size(); const int payload_offset = element_klass->payload_offset(); assert_is_flat_field(element_klass, element_offset + payload_offset); @@ -625,7 +624,7 @@ inline void FlatArrayPayload::set_offset(ptrdiff_t offset) { const ptrdiff_t element_size = _storage._element_size; const ptrdiff_t length = container()->length(); - const ptrdiff_t base_offset = (ptrdiff_t)flatArrayOopDesc::base_offset_in_bytes(); + const ptrdiff_t base_offset = flatArrayOopDesc::base_offset_in_bytes(); const ptrdiff_t min_offset = base_offset - (length == 0 ? 0 : element_size); const ptrdiff_t max_offset = base_offset + length * element_size; diff --git a/src/hotspot/share/opto/addnode.cpp b/src/hotspot/share/opto/addnode.cpp index 72b4a8ea7cb2..957d54f5adcf 100644 --- a/src/hotspot/share/opto/addnode.cpp +++ b/src/hotspot/share/opto/addnode.cpp @@ -593,12 +593,12 @@ Node* AddINode::Ideal(PhaseGVN* phase, bool can_reshape) { // positive y and (x <= -(y << z)) if (op1 == Op_URShiftI && op2 == Op_ConI && in1->in(2)->Opcode() == Op_ConI) { - jint z = phase->type(in1->in(2))->is_int()->get_con() & 0x1f; // only least significant 5 bits matter - jint y = phase->type(in2)->is_int()->get_con(); + jint z = phase->type(in1->in(2))->as_int()->get_con() & 0x1f; // only least significant 5 bits matter + jint y = phase->type(in2)->as_int()->get_con(); if (z < 5 && -5 < y && y < 0) { const Type* t_in11 = phase->type(in1->in(1)); - if( t_in11 != Type::TOP && (t_in11->is_int()->_lo >= -(y << z))) { + if (t_in11 != Type::TOP && (t_in11->as_int()->_lo >= -(y << z))) { Node* a = phase->transform(new AddINode( in1->in(1), phase->intcon(y<in(2)); } @@ -626,8 +626,8 @@ Node* AddINode::Identity(PhaseGVN* phase) { // to be passed a TOP or BOTTOM type, these are filtered out by // pre-check. const Type* AddINode::add_ring(const Type* t0, const Type* t1) const { - const TypeInt* range0 = t0->is_int(); - const TypeInt* range1 = t1->is_int(); + const TypeInt* range0 = t0->as_int(); + const TypeInt* range1 = t1->as_int(); jlong lo_sum = (jlong)range0->_lo + (jlong)range1->_lo; jlong hi_sum = (jlong)range0->_hi + (jlong)range1->_hi; @@ -678,8 +678,8 @@ Node* AddLNode::Identity(PhaseGVN* phase) { // to be passed a TOP or BOTTOM type, these are filtered out by // pre-check. const Type *AddLNode::add_ring( const Type *t0, const Type *t1 ) const { - const TypeLong *r0 = t0->is_long(); // Handy access - const TypeLong *r1 = t1->is_long(); + const TypeLong* r0 = t0->as_long(); // Handy access + const TypeLong* r1 = t1->as_long(); jlong lo = java_add(r0->_lo, r1->_lo); jlong hi = java_add(r0->_hi, r1->_hi); if( !(r0->is_con() && r1->is_con()) ) { @@ -730,7 +730,7 @@ const Type *AddFNode::add_of_identity( const Type *t1, const Type *t2 ) const { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type *AddFNode::add_ring( const Type *t0, const Type *t1 ) const { - if (!t0->isa_float_constant() || !t1->isa_float_constant()) { + if (!t0->is_float_constant() || !t1->is_float_constant()) { return bottom_type(); } return TypeF::make( t0->getf() + t1->getf() ); @@ -747,7 +747,7 @@ const Type* AddHFNode::add_of_identity(const Type* t1, const Type* t2) const { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type* AddHFNode::add_ring(const Type* t0, const Type* t1) const { - if (!t0->isa_half_float_constant() || !t1->isa_half_float_constant()) { + if (!t0->is_half_float_constant() || !t1->is_half_float_constant()) { return bottom_type(); } return TypeH::make(t0->getf() + t1->getf()); @@ -773,7 +773,7 @@ const Type *AddDNode::add_of_identity( const Type *t1, const Type *t2 ) const { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type *AddDNode::add_ring( const Type *t0, const Type *t1 ) const { - if (!t0->isa_double_constant() || !t1->isa_double_constant()) { + if (!t0->is_double_constant() || !t1->is_double_constant()) { return bottom_type(); } return TypeD::make( t0->getd() + t1->getd() ); @@ -802,12 +802,12 @@ Node *AddPNode::Ideal(PhaseGVN *phase, bool can_reshape) { // Type of left input's right input const Type *t = phase->type( addp->in(Offset) ); if( t == Type::TOP ) return nullptr; - const TypeX *t12 = t->is_intptr_t(); + const TypeX* t12 = t->as_intptr_t(); if( t12->is_con() ) { // Left input is an add of a constant? // If the right input is a constant, combine constants const Type *temp_t2 = phase->type( in(Offset) ); if( temp_t2 == Type::TOP ) return nullptr; - const TypeX *t2 = temp_t2->is_intptr_t(); + const TypeX* t2 = temp_t2->as_intptr_t(); Node* address; Node* offset; if( t2->is_con() ) { @@ -864,16 +864,16 @@ const Type *AddPNode::bottom_type() const { return Type::TOP; } - const TypeX* tx = t->is_intptr_t(); + const TypeX* tx = t->as_intptr_t(); intptr_t txoffset = Type::OffsetBot; if (tx->is_con()) { // Left input is an add of a constant? txoffset = tx->get_con(); } - if (tp->isa_aryptr()) { + if (tp->is_aryptr()) { // In the case of a flat value type array, each field has its // own slice so we need to extract the field being accessed from // the address computation - return tp->is_aryptr()->add_field_offset_and_offset(txoffset); + return tp->as_aryptr()->add_field_offset_and_offset(txoffset); } return tp->add_offset(txoffset); } @@ -887,19 +887,19 @@ const Type* AddPNode::Value(PhaseGVN* phase) const { if( t2 == Type::TOP ) return Type::TOP; // Left input is a pointer - const TypePtr *p1 = t1->isa_ptr(); + const TypePtr* p1 = t1->as_ptr(); // Right input is an int - const TypeX *p2 = t2->is_intptr_t(); + const TypeX* p2 = t2->as_intptr_t(); // Add 'em intptr_t p2offset = Type::OffsetBot; if (p2->is_con()) { // Left input is an add of a constant? p2offset = p2->get_con(); } - if (p1->isa_aryptr()) { + if (p1->is_aryptr()) { // In the case of a flat value type array, each field has its // own slice so we need to extract the field being accessed from // the address computation - return p1->is_aryptr()->add_field_offset_and_offset(p2offset); + return p1->as_aryptr()->add_field_offset_and_offset(p2offset); } return p1->add_offset(p2offset); } @@ -1038,7 +1038,7 @@ Node* OrINode::Ideal(PhaseGVN* phase, bool can_reshape) { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type* OrINode::add_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_or(t1->is_int(), t2->is_int()); + return RangeInference::infer_or(t1->as_int(), t2->as_int()); } //============================================================================= @@ -1098,7 +1098,7 @@ Node* OrLNode::Ideal(PhaseGVN* phase, bool can_reshape) { //------------------------------add_ring--------------------------------------- const Type* OrLNode::add_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_or(t1->is_long(), t2->is_long()); + return RangeInference::infer_or(t1->as_long(), t2->as_long()); } //---------------------------Helper ------------------------------------------- @@ -1186,13 +1186,13 @@ const Type* XorINode::Value(PhaseGVN* phase) const { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type* XorINode::add_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_xor(t1->is_int(), t2->is_int()); + return RangeInference::infer_xor(t1->as_int(), t2->as_int()); } //============================================================================= //------------------------------add_ring--------------------------------------- const Type* XorLNode::add_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_xor(t1->is_long(), t2->is_long()); + return RangeInference::infer_xor(t1->as_long(), t2->as_long()); } Node* XorLNode::Ideal(PhaseGVN* phase, bool can_reshape) { @@ -1249,9 +1249,9 @@ Node* MinMaxNode::build_min_max_long(PhaseGVN* phase, Node* a, Node* b, bool is_ } Node* MinMaxNode::build_min_max(Node* a, Node* b, bool is_max, bool is_unsigned, const Type* t, PhaseGVN& gvn) { - bool is_int = gvn.type(a)->isa_int(); - assert(is_int || gvn.type(a)->isa_long(), "int or long inputs"); - assert(is_int == (gvn.type(b)->isa_int() != nullptr), "inconsistent inputs"); + bool is_int = gvn.type(a)->is_int(); + assert(is_int || gvn.type(a)->is_long(), "int or long inputs"); + assert(is_int == gvn.type(b)->is_int(), "inconsistent inputs"); BasicType bt = is_int ? T_INT: T_LONG; Node* hook = nullptr; if (gvn.is_IterGVN()) { @@ -1263,7 +1263,7 @@ Node* MinMaxNode::build_min_max(Node* a, Node* b, bool is_max, bool is_unsigned, Node* res = nullptr; if (is_int && !is_unsigned) { res = gvn.transform(build_min_max_int(a, b, is_max)); - assert(gvn.type(res)->is_int()->_lo >= t->is_int()->_lo && gvn.type(res)->is_int()->_hi <= t->is_int()->_hi, "type doesn't match"); + assert(gvn.type(res)->as_int()->_lo >= t->as_int()->_lo && gvn.type(res)->as_int()->_hi <= t->as_int()->_hi, "type doesn't match"); } else { Node* cmp = nullptr; if (is_max) { @@ -1281,9 +1281,9 @@ Node* MinMaxNode::build_min_max(Node* a, Node* b, bool is_max, bool is_unsigned, } Node* MinMaxNode::build_min_max_diff_with_zero(Node* a, Node* b, bool is_max, const Type* t, PhaseGVN& gvn) { - bool is_int = gvn.type(a)->isa_int(); - assert(is_int || gvn.type(a)->isa_long(), "int or long inputs"); - assert(is_int == (gvn.type(b)->isa_int() != nullptr), "inconsistent inputs"); + bool is_int = gvn.type(a)->is_int(); + assert(is_int || gvn.type(a)->is_long(), "int or long inputs"); + assert(is_int == gvn.type(b)->is_int(), "inconsistent inputs"); BasicType bt = is_int ? T_INT: T_LONG; Node* zero = gvn.integercon(0, bt); Node* hook = nullptr; @@ -1361,7 +1361,7 @@ static ConstAddOperands as_add_with_constant(Node* n) { if (c_type == Type::TOP) { return ConstAddOperands(nullptr, 0); } - return ConstAddOperands(x, c_type->is_int()->get_con()); + return ConstAddOperands(x, c_type->as_int()->get_con()); } Node* MinMaxNode::IdealI(PhaseGVN* phase, bool can_reshape) { @@ -1428,8 +1428,8 @@ Node* MaxINode::Ideal(PhaseGVN* phase, bool can_reshape) { } Node* MaxINode::Identity(PhaseGVN* phase) { - const TypeInt* t1 = phase->type(in(1))->is_int(); - const TypeInt* t2 = phase->type(in(2))->is_int(); + const TypeInt* t1 = phase->type(in(1))->as_int(); + const TypeInt* t2 = phase->type(in(2))->as_int(); // Can we determine the maximum statically? if (t1->_lo >= t2->_hi) { @@ -1445,8 +1445,8 @@ Node* MaxINode::Identity(PhaseGVN* phase) { //------------------------------add_ring--------------------------------------- // Supplied function returns the sum of the inputs. const Type *MaxINode::add_ring( const Type *t0, const Type *t1 ) const { - const TypeInt *r0 = t0->is_int(); // Handy access - const TypeInt *r1 = t1->is_int(); + const TypeInt* r0 = t0->as_int(); // Handy access + const TypeInt* r1 = t1->as_int(); // Otherwise just MAX them bits. return TypeInt::make( MAX2(r0->_lo,r1->_lo), MAX2(r0->_hi,r1->_hi), MAX2(r0->_widen,r1->_widen) ); @@ -1461,8 +1461,8 @@ Node* MinINode::Ideal(PhaseGVN* phase, bool can_reshape) { } Node* MinINode::Identity(PhaseGVN* phase) { - const TypeInt* t1 = phase->type(in(1))->is_int(); - const TypeInt* t2 = phase->type(in(2))->is_int(); + const TypeInt* t1 = phase->type(in(1))->as_int(); + const TypeInt* t2 = phase->type(in(2))->as_int(); // Can we determine the minimum statically? if (t1->_lo >= t2->_hi) { @@ -1477,8 +1477,8 @@ Node* MinINode::Identity(PhaseGVN* phase) { //------------------------------add_ring--------------------------------------- // Supplied function returns the sum of the inputs. const Type *MinINode::add_ring( const Type *t0, const Type *t1 ) const { - const TypeInt *r0 = t0->is_int(); // Handy access - const TypeInt *r1 = t1->is_int(); + const TypeInt* r0 = t0->as_int(); // Handy access + const TypeInt* r1 = t1->as_int(); // Otherwise just MIN them bits. return TypeInt::make( MIN2(r0->_lo,r1->_lo), MIN2(r0->_hi,r1->_hi), MAX2(r0->_widen,r1->_widen) ); @@ -1584,15 +1584,15 @@ static Node* fold_subI_no_underflow_pattern(Node* n, PhaseGVN* phase) { } const Type* MaxLNode::add_ring(const Type* t0, const Type* t1) const { - const TypeLong* r0 = t0->is_long(); - const TypeLong* r1 = t1->is_long(); + const TypeLong* r0 = t0->as_long(); + const TypeLong* r1 = t1->as_long(); return TypeLong::make(MAX2(r0->_lo, r1->_lo), MAX2(r0->_hi, r1->_hi), MAX2(r0->_widen, r1->_widen)); } Node* MaxLNode::Identity(PhaseGVN* phase) { - const TypeLong* t1 = phase->type(in(1))->is_long(); - const TypeLong* t2 = phase->type(in(2))->is_long(); + const TypeLong* t1 = phase->type(in(1))->as_long(); + const TypeLong* t2 = phase->type(in(2))->as_long(); // Can we determine maximum statically? if (t1->_lo >= t2->_hi) { @@ -1618,15 +1618,15 @@ Node* MaxLNode::Ideal(PhaseGVN* phase, bool can_reshape) { } const Type* MinLNode::add_ring(const Type* t0, const Type* t1) const { - const TypeLong* r0 = t0->is_long(); - const TypeLong* r1 = t1->is_long(); + const TypeLong* r0 = t0->as_long(); + const TypeLong* r1 = t1->as_long(); return TypeLong::make(MIN2(r0->_lo, r1->_lo), MIN2(r0->_hi, r1->_hi), MAX2(r0->_widen, r1->_widen)); } Node* MinLNode::Identity(PhaseGVN* phase) { - const TypeLong* t1 = phase->type(in(1))->is_long(); - const TypeLong* t2 = phase->type(in(2))->is_long(); + const TypeLong* t1 = phase->type(in(1))->as_long(); + const TypeLong* t2 = phase->type(in(2))->as_long(); // Can we determine minimum statically? if (t1->_lo >= t2->_hi) { @@ -1677,7 +1677,7 @@ Node* MinMaxNode::find_identity_operation(Node* operation, Node* operand) { // If the operations are different return the operand 'A', as Max(A, Min(A, B)) == A if the value isn't floating point. // With floating point values, the identity doesn't hold if B == NaN. const Type* type = bottom_type(); - if (type->isa_int() || type->isa_long()) { + if (type->is_int() || type->is_long()) { return operand; } } diff --git a/src/hotspot/share/opto/addnode.hpp b/src/hotspot/share/opto/addnode.hpp index e87e23898633..0b47419c9e5c 100644 --- a/src/hotspot/share/opto/addnode.hpp +++ b/src/hotspot/share/opto/addnode.hpp @@ -230,7 +230,7 @@ class AddPNode : public Node { AddPNode(Node* base, Node* ptr, Node* off) : Node(nullptr, base, ptr, off) { init_class_id(Class_AddP); assert((ptr->bottom_type() == Type::TOP) || - ((base == Compile::current()->top()) == (ptr->bottom_type()->make_ptr()->isa_oopptr() == nullptr)), + ((base == Compile::current()->top()) == (!ptr->bottom_type()->make_ptr()->is_oopptr())), "base input only needed for heap addresses"); } diff --git a/src/hotspot/share/opto/arraycopynode.cpp b/src/hotspot/share/opto/arraycopynode.cpp index 289ae5011f26..6f86b5432122 100644 --- a/src/hotspot/share/opto/arraycopynode.cpp +++ b/src/hotspot/share/opto/arraycopynode.cpp @@ -122,8 +122,8 @@ int ArrayCopyNode::get_count(PhaseGVN *phase) const { return -1; } - if (src_type->isa_instptr()) { - const TypeInstPtr* inst_src = src_type->is_instptr(); + if (src_type->is_instptr()) { + const TypeInstPtr* inst_src = src_type->as_instptr(); ciInstanceKlass* ik = inst_src->instance_klass(); // ciInstanceKlass::nof_nonstatic_fields() doesn't take injected // fields into account. They are rare anyway so easier to simply @@ -223,7 +223,7 @@ Node* ArrayCopyNode::try_clone_instance(PhaseGVN *phase, bool can_reshape, int c } } - const TypeInstPtr* dest_type = phase->type(base_dest)->is_instptr(); + const TypeInstPtr* dest_type = phase->type(base_dest)->as_instptr(); if (dest_type->instance_klass() != ik) { // At parse time, the exact type of the object to clone was not known. That inexact type was captured by the CheckCastPP // of the newly allocated cloned object (in dest). The exact type is now known (in src), but the type for the cloned object @@ -384,7 +384,7 @@ bool ArrayCopyNode::prepare_array_copy(PhaseGVN *phase, bool can_reshape, return false; } - BasicType elem = ary_src->isa_aryptr()->elem()->array_element_basic_type(); + BasicType elem = ary_src->elem()->array_element_basic_type(); if (is_reference_type(elem, true)) { elem = T_OBJECT; } @@ -404,7 +404,7 @@ bool ArrayCopyNode::prepare_array_copy(PhaseGVN *phase, bool can_reshape, // If the clone copy is decomposed into load-stores - the address is adjusted to // point at where the array starts. const Type* toff = phase->type(src_offset); - int offset = toff->isa_long() ? (int) toff->is_long()->get_con() : (int) toff->is_int()->get_con(); + int offset = toff->is_long() ? static_cast(toff->as_long()->get_con()) : toff->as_int()->get_con(); int diff = arrayOopDesc::base_offset_in_bytes(elem) - offset; assert(diff >= 0, "clone should not start after 1st array element"); if (diff > 0) { @@ -417,12 +417,49 @@ bool ArrayCopyNode::prepare_array_copy(PhaseGVN *phase, bool can_reshape, return true; } +// Check whether the fast path arraycopy can be used: +// - Return false: We could not prove that the fast path is safe +// - Return true: We might use the fast path +// +// Note that we do not need to check atomicity for flat arrays. Atomic flat layouts can only have an element size of +// 1, 2, 4, or 8 bytes. We can use the corresponding primitive arraycopy stubs which copy the elements atomically. +// Flat arrays with elements larger than 8 bytes cannot have an atomic layout. +bool ArrayCopyNode::can_use_arraycopy_fast_path(const TypeAryPtr* src_ary, const TypeAryPtr* dest_ary) const { + assert(src_ary != nullptr, "src must be an array pointer"); + assert(dest_ary != nullptr, "dest must be an array pointer"); + + if (!src_ary->has_compatible_arraycopy_layout(dest_ary)) { + // We cannot prove that src and dest have compatible layouts. + return false; + } + + if (src_ary->is_not_flat()) { + assert(dest_ary->is_not_flat(), "same reference layout"); + return true; + } + + // Additional checks for flat arrays. + assert(src_ary->exact_klass() == dest_ary->exact_klass(), "same layout"); + assert(dest_ary->is_flat(), "same flatness"); + assert(src_ary->is_null_free() == dest_ary->is_null_free(), "same nullness"); + assert(is_reference_type(dest_ary->elem()->array_element_basic_type(), true), "must be for flat arrays"); + + if (src_ary->elem()->value_klass()->contains_oops()) { + BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); + bool needs_barriers = bs->array_copy_requires_gc_barriers(is_alloc_tightly_coupled(), T_OBJECT, false, false, + BarrierSetC2::Optimization); + // When a flat array contains oops, we require GC barriers which we cannot handle + return !needs_barriers; + } + return true; +} + const TypeAryPtr* ArrayCopyNode::get_address_type(PhaseGVN* phase, const TypePtr* atp, Node* n) { if (atp == TypeOopPtr::BOTTOM) { atp = phase->type(n)->isa_ptr(); } // adjust atp to be the correct array element address type - return atp->add_offset(Type::OffsetBot)->is_aryptr(); + return atp->add_offset(Type::OffsetBot)->as_aryptr(); } void ArrayCopyNode::array_copy_test_overlap(GraphKit& kit, bool disjoint_bases, int count, Node*& backward_ctl) { @@ -643,7 +680,7 @@ Node *ArrayCopyNode::Ideal(PhaseGVN *phase, bool can_reshape) { const Type* src_type = phase->type(src); const Type* dest_type = phase->type(dest); - if (src_type->isa_aryptr() && dest_type->isa_instptr()) { + if (src_type->is_aryptr() && dest_type->is_instptr()) { // clone used for load of unknown value type can't be optimized at // this point return nullptr; @@ -783,9 +820,9 @@ bool ArrayCopyNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) cons if (dest->is_top()) { return false; } - const TypeOopPtr* dest_t = phase->type(dest)->is_oopptr(); + const TypeOopPtr* dest_t = phase->type(dest)->as_oopptr(); assert(!dest_t->is_known_instance() || _dest_type->is_known_instance(), "result of EA not recorded"); - assert(in(ArrayCopyNode::Src)->is_top() || !phase->type(in(ArrayCopyNode::Src))->is_oopptr()->is_known_instance() || + assert(in(ArrayCopyNode::Src)->is_top() || !phase->type(in(ArrayCopyNode::Src))->as_oopptr()->is_known_instance() || _src_type->is_known_instance(), "result of EA not recorded"); if (_dest_type != TypeOopPtr::BOTTOM || t_oop->is_known_instance()) { @@ -797,10 +834,10 @@ bool ArrayCopyNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) cons } bool ArrayCopyNode::may_modify_helper(const TypeOopPtr* t_oop, Node* n, PhaseValues* phase, ArrayCopyNode*& ac) { - if (n != nullptr && - n->is_ArrayCopy() && - n->as_ArrayCopy()->may_modify(t_oop, phase)) { - ac = n->as_ArrayCopy(); + if (ArrayCopyNode* n_copy = isa(n); + n_copy != nullptr && + n_copy->may_modify(t_oop, phase)) { + ac = n_copy; return true; } return false; @@ -859,7 +896,7 @@ bool ArrayCopyNode::modifies(intptr_t offset_lo, intptr_t offset_hi, PhaseValues return !must_modify; } - BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type(); + BasicType ary_elem = ary_t->elem()->array_element_basic_type(); if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT; uint header; diff --git a/src/hotspot/share/opto/arraycopynode.hpp b/src/hotspot/share/opto/arraycopynode.hpp index 1b8d4a210c5d..888a4b929d64 100644 --- a/src/hotspot/share/opto/arraycopynode.hpp +++ b/src/hotspot/share/opto/arraycopynode.hpp @@ -129,6 +129,7 @@ class ArrayCopyNode : public CallNode { static bool may_modify_helper(const TypeOopPtr* t_oop, Node* n, PhaseValues* phase, ArrayCopyNode*& ac); public: + bool can_use_arraycopy_fast_path(const TypeAryPtr* src_ary, const TypeAryPtr* dest_ary) const; static Node* load(BarrierSetC2* bs, PhaseGVN *phase, Node*& ctl, MergeMemNode* mem, Node* addr, const TypePtr* adr_type, const Type *type, BasicType bt); private: void store(BarrierSetC2* bs, PhaseGVN *phase, Node*& ctl, MergeMemNode* mem, Node* addr, const TypePtr* adr_type, Node* val, const Type *type, BasicType bt); diff --git a/src/hotspot/share/opto/block.cpp b/src/hotspot/share/opto/block.cpp index 9138965c8c74..8aa81a205bcb 100644 --- a/src/hotspot/share/opto/block.cpp +++ b/src/hotspot/share/opto/block.cpp @@ -1136,7 +1136,7 @@ void PhaseCFG::postalloc_expand(PhaseRegAlloc* _ra) { uint req = n->req(); remove.clear(); for (uint k = 0; k < req; ++k) { - if (n->in(k) && n->in(k)->is_MachTemp()) { + if (Node::is(n->in(k))) { remove.push(n->in(k)); // MachTemps which are inputs to the old node have to be removed. n->in(k)->del_req(0); j--; diff --git a/src/hotspot/share/opto/buildOopMap.cpp b/src/hotspot/share/opto/buildOopMap.cpp index ccf0756eab72..0ec61019a094 100644 --- a/src/hotspot/share/opto/buildOopMap.cpp +++ b/src/hotspot/share/opto/buildOopMap.cpp @@ -213,7 +213,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i memset(dup_check,0,OptoReg::stack0()) ); OopMap *omap = new OopMap( framesize, max_inarg_slot ); - MachCallNode *mcall = n->is_MachCall() ? n->as_MachCall() : nullptr; + MachCallNode* mcall = n->isa_MachCall(); JVMState* jvms = n->jvms(); // For all registers do... @@ -235,7 +235,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i assert( def, "since live better have reaching def" ); if (def->is_MachTemp()) { - assert(!def->bottom_type()->isa_oop_ptr(), + assert(!def->bottom_type()->is_oopptr(), "ADLC only assigns OOP types to MachTemp defs corresponding to xRegN operands"); // Exclude MachTemp definitions even if they are typed as oops. continue; @@ -243,7 +243,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i // Classify the reaching def as oop, derived, callee-save, dead, or other const Type *t = def->bottom_type(); - if( t->isa_oop_ptr() ) { // Oop or derived? + if (t->is_oopptr()) { // Oop or derived? assert( !OptoReg::is_valid(_callees[reg]), "oop can't be callee save" ); #ifdef _LP64 // 64-bit pointers record oop-ishness on 2 aligned adjacent registers. @@ -264,7 +264,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i regalloc->C->record_method_not_compilable(ss.as_string()); continue; } - if (t->is_ptr()->offset() == 0) { // Not derived? + if (t->as_ptr()->offset() == 0) { // Not derived? if( mcall ) { // Outgoing argument GC mask responsibility belongs to the callee, // not the caller. Inspect the inputs to the call, to see if @@ -324,7 +324,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i omap->set_derived_oop(r, b); } - } else if( t->isa_narrowoop() ) { + } else if (t->is_narrowoop()) { assert( !OptoReg::is_valid(_callees[reg]), "oop can't be callee save" ); // Check for a legal reg name in the oopMap and bailout if it is not. if (!omap->legal_vm_reg_name(r)) { @@ -358,7 +358,7 @@ OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, i } else { // Other - some reaching non-oop value #ifdef ASSERT - if (t->isa_rawptr()) { + if (t->is_rawptr()) { ResourceMark rm; Unique_Node_List worklist; worklist.push(def); @@ -485,7 +485,7 @@ static void do_liveness(PhaseRegAlloc* regalloc, PhaseCFG* cfg, Block_List* work if( OptoReg::is_valid(first) ) clr_live_bit(tmp_live,first); if( OptoReg::is_valid(second) ) clr_live_bit(tmp_live,second); - MachNode *m = n->is_Mach() ? n->as_Mach() : nullptr; + MachNode* m = n->isa_Mach(); // Check if m is potentially a CISC alternate instruction (i.e, possibly // synthesized by RegAlloc from a conventional instruction and a @@ -519,7 +519,7 @@ static void do_liveness(PhaseRegAlloc* regalloc, PhaseCFG* cfg, Block_List* work // with these, but are presuming (with trepidation) that not any of // them are oops. This can be fixed by making get_base_and_disp() // look at a specific input instead of all inputs. - assert(!def->bottom_type()->isa_oop_ptr(), "expecting non-oop mem input"); + assert(!def->bottom_type()->is_oopptr(), "expecting non-oop mem input"); } else if (base != fp || offset == Type::OffsetBot) { // Do nothing: the fp operand is either not from a memory use // (base == nullptr) OR the fp is used in a non-memory context diff --git a/src/hotspot/share/opto/callGenerator.cpp b/src/hotspot/share/opto/callGenerator.cpp index dc1ee79297a0..5c755be98730 100644 --- a/src/hotspot/share/opto/callGenerator.cpp +++ b/src/hotspot/share/opto/callGenerator.cpp @@ -71,8 +71,7 @@ void CallGenerator::mark_projs_not_dead_loop_safe(Node* ret) const { CallNode* call = call_node(); if (ret->is_Proj() && ret->in(0) == call) { ret->mark_not_dead_loop_safe(); - } else if (ret->isa_ValueType()) { - ValueTypeNode* vt = ret->as_ValueType(); + } else if (ValueTypeNode* vt = ret->isa_ValueType(); vt != nullptr) { Node* oop = vt->get_oop(); if (oop->is_Proj() && oop->in(0) == call) { oop->mark_not_dead_loop_safe(); @@ -1303,7 +1302,7 @@ CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* Node* member_name = kit.argument(nargs - 1); if (member_name->Opcode() == Op_ConP) { input_not_const = false; - const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr(); + const TypeOopPtr* oop_ptr = member_name->bottom_type()->as_oopptr(); ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget(); if (!ciMethod::is_consistent_info(callee, target)) { diff --git a/src/hotspot/share/opto/callnode.cpp b/src/hotspot/share/opto/callnode.cpp index cd722763eead..a1026c696595 100644 --- a/src/hotspot/share/opto/callnode.cpp +++ b/src/hotspot/share/opto/callnode.cpp @@ -369,42 +369,42 @@ static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, c const Type *t = n->bottom_type(); switch (t->base()) { case Type::Int: - st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con()); + st->print(" %s%d]=#" INT32_FORMAT, msg, i, t->as_int()->get_con()); break; case Type::AnyPtr: assert( t == TypePtr::NULL_PTR || n->in_dump(), "" ); - st->print(" %s%d]=#null",msg,i); + st->print(" %s%d]=#null", msg, i); break; case Type::AryPtr: case Type::InstPtr: - st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop())); + st->print(" %s%d]=#Ptr" INTPTR_FORMAT, msg, i, p2i(t->as_oopptr()->const_oop())); break; case Type::KlassPtr: case Type::AryKlassPtr: case Type::InstKlassPtr: - st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->exact_klass())); + st->print(" %s%d]=#Ptr" INTPTR_FORMAT, msg, i, p2i(t->make_ptr()->as_klassptr()->exact_klass())); break; case Type::MetadataPtr: - st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata())); + st->print(" %s%d]=#Ptr" INTPTR_FORMAT, msg, i, p2i(t->make_ptr()->as_metadataptr()->metadata())); break; case Type::NarrowOop: - st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop())); + st->print(" %s%d]=#Ptr" INTPTR_FORMAT, msg, i, p2i(t->make_ptr()->as_oopptr()->const_oop())); break; case Type::RawPtr: - st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr())); + st->print(" %s%d]=#Raw" INTPTR_FORMAT, msg, i, p2i(t->as_rawptr())); break; case Type::DoubleCon: - st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d); + st->print(" %s%d]=#%fD", msg, i, t->as_double_constant()->_d); break; case Type::FloatCon: - st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f); + st->print(" %s%d]=#%fF", msg, i, t->as_float_constant()->_f); break; case Type::Long: - st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con())); + st->print(" %s%d]=#" INT64_FORMAT, msg, i, (int64_t)(t->as_long()->get_con())); break; case Type::Half: case Type::Top: - st->print(" %s%d]=_",msg,i); + st->print(" %s%d]=_", msg, i); break; default: ShouldNotReachHere(); } @@ -473,7 +473,7 @@ void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) st->cr(); st->print(" # ScObj" INT32_FORMAT " ", i); SafePointScalarObjectNode* spobj = scobjs.at(i); - ciKlass* cik = spobj->bottom_type()->is_oopptr()->exact_klass(); + ciKlass* cik = spobj->bottom_type()->as_oopptr()->exact_klass(); assert(cik->is_instance_klass() || cik->is_array_klass(), "Not supported allocation."); ciInstanceKlass *iklass = nullptr; @@ -865,7 +865,7 @@ bool CallNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) const { // different signatures. Look for the second pointer argument, // that is the destination of the copy. for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) { - if (args->field_at(i)->isa_ptr()) { + if (args->field_at(i)->is_ptr()) { j++; if (j == 2) { dest = in(i); @@ -874,11 +874,11 @@ bool CallNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) const { } } guarantee(dest != nullptr, "Call had only one ptr in, broken IR!"); - if (phase->type(dest)->isa_rawptr()) { + if (phase->type(dest)->is_rawptr()) { // may happen for an arraycopy that initializes a newly allocated object. Conservatively return true; return true; } - if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->is_oopptr(), t_oop, phase)) { + if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->as_oopptr(), t_oop, phase)) { return true; } return false; @@ -889,11 +889,11 @@ bool CallNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) const { return false; } if (t_oop->is_ptr_to_boxed_value() && is_CallStaticJava()) { - ciKlass* boxing_klass = t_oop->is_instptr()->instance_klass(); + ciKlass* boxing_klass = t_oop->as_instptr()->instance_klass(); if (as_CallStaticJava()->is_boxing_method()) { // Skip unrelated boxing methods. Node* proj = proj_out_or_null(TypeFunc::Parms); - if ((proj == nullptr) || (phase->type(proj)->is_instptr()->instance_klass() != boxing_klass)) { + if ((proj == nullptr) || (phase->type(proj)->as_instptr()->instance_klass() != boxing_klass)) { return false; } } @@ -983,7 +983,7 @@ CallProjections* CallNode::extract_projections(bool separate_io_proj, bool do_as // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj projs->fallthrough_proj = pn; const Node* cn = pn->unique_ctrl_out_or_null(); - if (cn != nullptr && cn->is_Catch()) { + if (is(cn)) { for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) { CatchProjNode* cpn = cn->fast_out(k)->as_CatchProj(); assert(allow_handlers || !cpn->is_handler_proj(), "not allowed"); @@ -1097,8 +1097,7 @@ void CallJavaNode::copy_call_debug_info(PhaseIterGVN* phase, SafePointNode* sfpt for (uint i = old_dbg_start; i < sfpt->req(); i++) { Node* old_in = sfpt->in(i); // Clone old SafePointScalarObjectNodes, adjusting their field contents. - if (old_in != nullptr && old_in->is_SafePointScalarObject()) { - SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject(); + if (SafePointScalarObjectNode* old_sosn = isa(old_in); old_sosn != nullptr) { bool new_node; Node* new_in = old_sosn->clone(sosn_map, new_node); if (new_node) { // New node? @@ -1253,21 +1252,21 @@ int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) { #ifndef PRODUCT if (!(call->req() > TypeFunc::Parms && call->in(TypeFunc::Parms) != nullptr && - call->in(TypeFunc::Parms)->bottom_type()->isa_int() && - call->in(TypeFunc::Parms)->bottom_type()->is_int()->is_con())) { + call->in(TypeFunc::Parms)->bottom_type()->is_int() && + call->in(TypeFunc::Parms)->bottom_type()->as_int()->is_con())) { assert(in_dump() != 0, "OK if dumping"); tty->print("[bad uncommon trap]"); return 0; } #endif - return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con(); + return call->in(TypeFunc::Parms)->bottom_type()->as_int()->get_con(); } // Split if can cause the flat array branch of an array load with unknown type (see // Parse::array_load) to end in an uncommon trap. In that case, the call to // 'load_unknown_value' is useless. Replace it with an uncommon trap with the same JVMState. bool CallStaticJavaNode::remove_unknown_flat_array_load(PhaseIterGVN* igvn, Node* ctl, Node* mem, Node* unc_arg) { - if (ctl == nullptr || ctl->is_top() || mem == nullptr || mem->is_top() || !mem->is_MergeMem()) { + if (ctl == nullptr || ctl->is_top() || !is(mem)) { return false; } if (ctl->is_Region()) { @@ -1634,12 +1633,12 @@ void CallRuntimeNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs void CallLeafVectorNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const { #ifdef ASSERT - assert(tf()->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte == _num_bits, + assert(tf()->range_sig()->field_at(TypeFunc::Parms)->as_vect()->length_in_bytes() * BitsPerByte == _num_bits, "return vector size must match"); const TypeTuple* d = tf()->domain_sig(); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { Node* arg = in(i); - assert(arg->bottom_type()->is_vect()->length_in_bytes() * BitsPerByte == _num_bits, + assert(arg->bottom_type()->as_vect()->length_in_bytes() * BitsPerByte == _num_bits, "vector argument size must match"); } #endif @@ -2134,7 +2133,7 @@ Node* AllocateNode::make_ideal_mark(PhaseGVN* phase, Node* control, Node* mem) { if (UseCompactObjectHeaders || Arguments::is_valhalla_enabled()) { Node* klass_node = in(AllocateNode::KlassNode); Node* proto_adr = phase->transform(AddPNode::make_with_base(phase->C->top(), klass_node, phase->MakeConX(in_bytes(Klass::prototype_header_offset())))); - mark_node = LoadNode::make(*phase, control, mem, proto_adr, phase->type(proto_adr)->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered); + mark_node = LoadNode::make(*phase, control, mem, proto_adr, phase->type(proto_adr)->as_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered); } else { // For now only enable fast locking for non-array types mark_node = phase->MakeConX(markWord::prototype().value()); @@ -2334,11 +2333,10 @@ static Node *next_control(Node *ctrl) { // bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock, GrowableArray &lock_ops) { - ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : nullptr; + ProjNode* ctrl_proj = ctrl->isa_Proj(); if (ctrl_proj != nullptr && ctrl_proj->_con == TypeFunc::Control) { - Node *n = ctrl_proj->in(0); - if (n != nullptr && n->is_Unlock()) { - UnlockNode *unlock = n->as_Unlock(); + Node* n = ctrl_proj->in(0); + if (UnlockNode* unlock = isa(n); unlock != nullptr) { Node* lock_obj = lock->obj_node(); Node* unlock_obj = unlock->obj_node(); if (lock_obj->eqv_uncast(unlock_obj) && @@ -2373,8 +2371,7 @@ bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* loc lock1_node = proj->unique_out(); } } - if (lock1_node != nullptr && lock1_node->is_Lock()) { - LockNode *lock1 = lock1_node->as_Lock(); + if (LockNode* lock1 = isa(lock1_node); lock1 != nullptr) { Node* lock_obj = lock->obj_node(); Node* lock1_obj = lock1->obj_node(); if (lock_obj->eqv_uncast(lock1_obj) && @@ -2728,12 +2725,12 @@ bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeO return dest_t->instance_id() == t_oop->instance_id(); } - if (dest_t->isa_instptr() && !dest_t->is_instptr()->instance_klass()->equals(phase->C->env()->Object_klass())) { + if (dest_t->is_instptr() && !dest_t->as_instptr()->instance_klass()->equals(phase->C->env()->Object_klass())) { // clone - if (t_oop->isa_aryptr()) { + if (t_oop->is_aryptr()) { return false; } - if (!t_oop->isa_instptr()) { + if (!t_oop->is_instptr()) { return true; } if (dest_t->maybe_java_subtype_of(t_oop) || t_oop->maybe_java_subtype_of(dest_t)) { @@ -2743,23 +2740,23 @@ bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeO return false; } - if (dest_t->isa_aryptr()) { + if (dest_t->is_aryptr()) { // arraycopy or array clone - if (t_oop->isa_instptr()) { + if (t_oop->is_instptr()) { return false; } - if (!t_oop->isa_aryptr()) { + if (!t_oop->is_aryptr()) { return true; } - const Type* elem = dest_t->is_aryptr()->elem(); + const Type* elem = dest_t->as_aryptr()->elem(); if (elem == Type::BOTTOM) { // An array but we don't know what elements are return true; } - dest_t = dest_t->is_aryptr()->with_field_offset(Type::OffsetBot)->add_offset(Type::OffsetBot)->is_oopptr(); - t_oop = t_oop->is_aryptr()->with_field_offset(Type::OffsetBot); + dest_t = dest_t->as_aryptr()->with_field_offset(Type::OffsetBot)->add_offset(Type::OffsetBot)->as_oopptr(); + t_oop = t_oop->as_aryptr()->with_field_offset(Type::OffsetBot); uint dest_alias = phase->C->get_alias_index(dest_t); uint t_oop_alias = phase->C->get_alias_index(t_oop); diff --git a/src/hotspot/share/opto/callnode.hpp b/src/hotspot/share/opto/callnode.hpp index 7fbc4a5431e9..142c350da3ce 100644 --- a/src/hotspot/share/opto/callnode.hpp +++ b/src/hotspot/share/opto/callnode.hpp @@ -392,7 +392,7 @@ class SafePointNode : public MultiNode { void verify_input(const JVMState* jvms, uint idx) const { assert(verify_jvms(jvms), "jvms must match"); Node* n = in(idx); - assert((!n->bottom_type()->isa_long() && !n->bottom_type()->isa_double()) || + assert((!n->bottom_type()->is_long() && !n->bottom_type()->is_double()) || in(idx + 1)->is_top(), "2nd half of long/double"); } @@ -841,7 +841,7 @@ class CallNode : public SafePointNode { const TypeTuple* r = tf()->range_sig(); return (!tf()->returns_value_type_as_fields() && r->cnt() > TypeFunc::Parms && - r->field_at(TypeFunc::Parms)->isa_ptr()); + r->field_at(TypeFunc::Parms)->is_ptr()); } // Collect all the interesting edges from a call for use in @@ -936,8 +936,8 @@ class CallStaticJavaNode : public CallJavaNode { method != nullptr && method->is_method_handle_intrinsic() && r->cnt() > TypeFunc::Parms && - r->field_at(TypeFunc::Parms)->isa_oopptr() && - r->field_at(TypeFunc::Parms)->is_oopptr()->can_be_value_type()) { + r->field_at(TypeFunc::Parms)->is_oopptr() && + r->field_at(TypeFunc::Parms)->as_oopptr()->can_be_value_type()) { // Make sure this call is processed by PhaseMacroExpand::expand_mh_intrinsic_return C->add_macro_node(this); } @@ -1277,8 +1277,7 @@ class AllocateArrayNode : public AllocateNode { // Return null if no allocation is recognized. static AllocateArrayNode* Ideal_array_allocation(Node* ptr) { AllocateNode* allo = Ideal_allocation(ptr); - return (allo == nullptr || !allo->is_AllocateArray()) - ? nullptr : allo->as_AllocateArray(); + return isa(allo); } }; diff --git a/src/hotspot/share/opto/castnode.cpp b/src/hotspot/share/opto/castnode.cpp index 4ed2fe54b4d9..6375ec0a18a1 100644 --- a/src/hotspot/share/opto/castnode.cpp +++ b/src/hotspot/share/opto/castnode.cpp @@ -97,7 +97,7 @@ const Type* ConstraintCastNode::Value(PhaseGVN* phase) const { } case Op_CastPP: if (in_type == TypePtr::NULL_PTR && - _type->isa_ptr() && _type->is_ptr()->_ptr == TypePtr::NotNull) { + _type->is_ptr() && _type->as_ptr()->_ptr == TypePtr::NotNull) { assert(ft == Type::TOP, "special case #3"); break; } @@ -177,7 +177,7 @@ TypeNode* ConstraintCastNode::dominating_cast(PhaseGVN* gvn, PhaseTransform* pt) if (is_CastII() && as_CastII()->has_range_check()) { return nullptr; } - if (type()->isa_rawptr() && (gvn->type_or_null(val) == nullptr || gvn->type(val)->isa_oopptr())) { + if (type()->is_rawptr() && (gvn->type_or_null(val) == nullptr || gvn->type(val)->is_oopptr())) { return nullptr; } for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) { @@ -204,8 +204,8 @@ TypeNode* ConstraintCastNode::dominating_cast(PhaseGVN* gvn, PhaseTransform* pt) bool ConstraintCastNode::higher_equal_types(PhaseGVN* phase, const Node* other) const { const Type* t = phase->type(other); - if ((t->isa_rawptr() && (type()->isa_oopptr() || type()->isa_klassptr())) || - ((t->isa_oopptr() || t->isa_klassptr()) && type()->isa_rawptr())) { + if ((t->is_rawptr() && (type()->is_oopptr() || type()->is_klassptr())) || + ((t->is_oopptr() || t->is_klassptr()) && type()->is_rawptr())) { assert(is_CheckCastPP(), "unrelated types from %s", Name()); return false; } @@ -229,7 +229,7 @@ Node* ConstraintCastNode::pin_node_under_control_impl() const { Node* ConstraintCastNode::ideal_cast_of_value_type_node(PhaseGVN* phase) { ValueTypeNode* vt = in(1)->as_ValueType(); - if (type()->isa_rawptr() != nullptr) { + if (type()->is_rawptr()) { return nullptr; } @@ -375,7 +375,7 @@ void CastIINode::remove_range_check_cast(Compile* C) { bool CastLLNode::is_inner_loop_backedge(IfProjNode* proj) { if (proj != nullptr) { Node* ctrl_use = proj->unique_ctrl_out_or_null(); - if (ctrl_use != nullptr && ctrl_use->Opcode() == Op_Loop && + if (is_exact(ctrl_use) && ctrl_use->in(2) == proj && ctrl_use->as_Loop()->is_loop_nest_inner_loop()) { return true; @@ -445,12 +445,12 @@ Node* CastLLNode::Ideal(PhaseGVN* phase, bool can_reshape) { // transform (CastLL (ConvI2L ..)) into (ConvI2L (CastII ..)) if the type of the CastLL is narrower than the type of // the ConvI2L. Node* in1 = in(1); - if (in1 != nullptr && in1->Opcode() == Op_ConvI2L) { + if (is_exact(in1)) { const Type* t = Value(phase); const Type* t_in = phase->type(in1); if (t != Type::TOP && t_in != Type::TOP) { - const TypeLong* tl = t->is_long(); - const TypeLong* t_in_l = t_in->is_long(); + const TypeLong* tl = t->as_long(); + const TypeLong* t_in_l = t_in->as_long(); assert(t_in_l->contains(tl), "CastLL type should be narrower than or equal to the type of its input"); assert((tl != t_in_l) == t_in_l->strictly_contains(tl), "if type differs then this nodes's type must be narrower"); if (tl != t_in_l) { @@ -474,7 +474,7 @@ Node* CastLLNode::Ideal(PhaseGVN* phase, bool can_reshape) { //------------------------------Identity--------------------------------------- // If input is already higher or equal to cast type, then this is an identity. Node* CheckCastPPNode::Identity(PhaseGVN* phase) { - if (in(1)->is_ValueType() && _type->isa_instptr() && phase->type(in(1))->value_klass()->is_subtype_of(_type->is_instptr()->instance_klass())) { + if (in(1)->is_ValueType() && _type->is_instptr() && phase->type(in(1))->value_klass()->is_subtype_of(_type->as_instptr()->instance_klass())) { return in(1); } return ConstraintCastNode::Identity(phase); @@ -500,20 +500,20 @@ void CastPPNode::verify_type(const Type* in_type, const Type* out_type) { if (in_type == TypePtr::NULL_PTR || out_type == TypePtr::NULL_PTR) { return; } - if (!in_type->isa_oopptr() && !out_type->isa_oopptr()) { + if (!in_type->is_oopptr() && !out_type->is_oopptr()) { return; } - assert(in_type->isa_oopptr() && out_type->isa_oopptr(), "must be both oops or both non-oops"); - if (in_type->isa_aryptr() && out_type->isa_aryptr()) { - const Type* e1 = in_type->is_aryptr()->elem(); - const Type* e2 = out_type->is_aryptr()->elem(); + assert(in_type->is_oopptr() && out_type->is_oopptr(), "must be both oops or both non-oops"); + if (in_type->is_aryptr() && out_type->is_aryptr()) { + const Type* e1 = in_type->as_aryptr()->elem(); + const Type* e2 = out_type->as_aryptr()->elem(); assert(e1->basic_type() == e2->basic_type(), "must both be arrays of the same primitive type or both be oops arrays"); return; } - assert(in_type->isa_instptr() && out_type->isa_instptr(), "must be both array oops or both non-array oops"); - assert(in_type->is_instptr()->instance_klass() == out_type->is_instptr()->instance_klass(), "must not cast to a different type"); + assert(in_type->is_instptr() && out_type->is_instptr(), "must be both array oops or both non-array oops"); + assert(in_type->as_instptr()->instance_klass() == out_type->as_instptr()->instance_klass(), "must not cast to a different type"); #endif // ASSERT } @@ -525,7 +525,7 @@ const Type* CheckCastPPNode::Value(PhaseGVN* phase) const { const Type *inn = phase->type(in(1)); if( inn == Type::TOP ) return Type::TOP; // No information yet - if (inn->isa_oopptr() && _type->isa_oopptr()) { + if (inn->is_oopptr() && _type->is_oopptr()) { return ConstraintCastNode::Value(phase); } @@ -534,11 +534,11 @@ const Type* CheckCastPPNode::Value(PhaseGVN* phase) const { const Type *result = _type; if (in_type != nullptr && my_type != nullptr) { // TODO 8302672 - if (!StressReflectiveCode && my_type->isa_aryptr() && in_type->isa_aryptr()) { + if (!StressReflectiveCode && my_type->is_aryptr() && in_type->is_aryptr()) { // Propagate array properties (not flat/null-free) // Don't do this when StressReflectiveCode is enabled because it might lead to // a dying data path while the corresponding flat/null-free check is not folded. - my_type = my_type->is_aryptr()->update_properties(in_type->is_aryptr()); + my_type = my_type->as_aryptr()->update_properties(in_type->as_aryptr()); if (my_type == nullptr) { return Type::TOP; // Inconsistent properties } @@ -570,7 +570,7 @@ const Type* CastX2PNode::Value(PhaseGVN* phase) const { const Type* t = phase->type(in(1)); if (t == Type::TOP) return Type::TOP; if (t->base() == Type_X && t->singleton()) { - uintptr_t bits = (uintptr_t) t->is_intptr_t()->get_con(); + uintptr_t bits = (uintptr_t) t->as_intptr_t()->get_con(); if (bits == 0) return TypePtr::NULL_PTR; return TypeRawPtr::make((address) bits); } @@ -580,7 +580,7 @@ const Type* CastX2PNode::Value(PhaseGVN* phase) const { //------------------------------Idealize--------------------------------------- static inline bool fits_in_int(const Type* t, bool but_not_min_int = false) { if (t == Type::TOP) return false; - const TypeX* tl = t->is_intptr_t(); + const TypeX* tl = t->as_intptr_t(); jint lo = min_jint; jint hi = max_jint; if (but_not_min_int) ++lo; // caller wants to negate the value w/o overflow @@ -639,7 +639,7 @@ const Type* CastP2XNode::Value(PhaseGVN* phase) const { const Type* t = phase->type(in(1)); if (t == Type::TOP) return Type::TOP; if (t->base() == Type::RawPtr && t->singleton()) { - uintptr_t bits = (uintptr_t) t->is_rawptr()->get_con(); + uintptr_t bits = (uintptr_t) t->as_rawptr()->get_con(); return TypeX::make(bits); } return CastP2XNode::bottom_type(); @@ -657,19 +657,19 @@ Node* CastP2XNode::Identity(PhaseGVN* phase) { Node* ConstraintCastNode::make_cast_for_type(Node* c, Node* in, const Type* type, const DependencyType& dependency, const TypeTuple* types) { - if (type->isa_int()) { + if (type->is_int()) { return new CastIINode(c, in, type, dependency, false, types); - } else if (type->isa_long()) { + } else if (type->is_long()) { return new CastLLNode(c, in, type, dependency, types); - } else if (type->isa_half_float()) { + } else if (type->is_half_float()) { return new CastHHNode(c, in, type, dependency, types); - } else if (type->isa_float()) { + } else if (type->is_float()) { return new CastFFNode(c, in, type, dependency, types); - } else if (type->isa_double()) { + } else if (type->is_double()) { return new CastDDNode(c, in, type, dependency, types); - } else if (type->isa_vect()) { + } else if (type->is_vect()) { return new CastVVNode(c, in, type, dependency, types); - } else if (type->isa_ptr()) { + } else if (type->is_ptr()) { return new CastPPNode(c, in, type, dependency, types); } fatal("unreachable. Invalid cast type."); @@ -698,8 +698,8 @@ Node* ConstraintCastNode::optimize_integer_cast_of_add(PhaseGVN* phase, BasicTyp Node* x = z->in(1); Node* y = z->in(2); - const TypeInteger* tx = phase->type(x)->is_integer(bt); - const TypeInteger* ty = phase->type(y)->is_integer(bt); + const TypeInteger* tx = phase->type(x)->as_integer(bt); + const TypeInteger* ty = phase->type(y)->as_integer(bt); // (Cast (Add x y) tz) is transformed into (Add (Cast x rx) (Cast y ry)) // @@ -764,7 +764,7 @@ Node* ConstraintCastNode::optimize_integer_cast(PhaseGVN* phase, BasicType bt) { } const TypeInteger* ConstraintCastNode::widen_type(const PhaseGVN* phase, const Type* res, BasicType bt) const { - const TypeInteger* this_type = res->is_integer(bt); + const TypeInteger* this_type = res->as_integer(bt); // At VerifyConstraintCasts == 1, we verify the ConstraintCastNodes that are present during code // emission. This allows us detecting possible mis-scheduling due to these nodes being pinned at // the wrong control nodes. @@ -794,7 +794,7 @@ const TypeInteger* ConstraintCastNode::widen_type(const PhaseGVN* phase, const T hi = max_signed_integer(bt); } // Must filter in the same direction as Value - return in_type->filter(TypeInteger::make(lo, hi, w, bt))->is_integer(bt); + return in_type->filter(TypeInteger::make(lo, hi, w, bt))->as_integer(bt); } return this_type; } diff --git a/src/hotspot/share/opto/castnode.hpp b/src/hotspot/share/opto/castnode.hpp index 8998112f0aed..4e511021d12d 100644 --- a/src/hotspot/share/opto/castnode.hpp +++ b/src/hotspot/share/opto/castnode.hpp @@ -334,7 +334,7 @@ class CheckCastPPNode: public ConstraintCastNode { virtual uint ideal_reg() const { return Op_RegP; } private: - virtual bool depends_only_on_test_impl() const { return !type()->isa_rawptr() && ConstraintCastNode::depends_only_on_test_impl(); } + virtual bool depends_only_on_test_impl() const { return !type()->is_rawptr() && ConstraintCastNode::depends_only_on_test_impl(); } virtual Node* pin_node_under_control_impl() const; }; diff --git a/src/hotspot/share/opto/cfgnode.cpp b/src/hotspot/share/opto/cfgnode.cpp index f53614b5358a..2ca1e1ab658a 100644 --- a/src/hotspot/share/opto/cfgnode.cpp +++ b/src/hotspot/share/opto/cfgnode.cpp @@ -89,7 +89,7 @@ static Node *merge_region(RegionNode *region, PhaseGVN *phase) { uint rreq = region->req(); for( uint i = 1; i < rreq; i++ ) { Node *r = region->in(i); - if( r && r->Opcode() == Op_Region && // Found a region? + if (Node::is_exact(r) && // Found a region? r->in(0) == r && // Not already collapsed? r != region && // Avoid stupid situations r->outcnt() == 2 ) { // Self user and 'region' user only? @@ -238,15 +238,15 @@ static bool check_if_clipping( const RegionNode *region, IfNode * &bot_if, IfNod Node *in20 = in2->in(0); Node *in30 = in3->in(0); // Check that #1 and #2 are ifTrue and ifFalse from same If - if( in10 != nullptr && in10->is_If() && - in20 != nullptr && in20->is_If() && - in30 != nullptr && in30->is_If() && in10 == in20 && - (in1->Opcode() != in2->Opcode()) ) { - Node *in100 = in10->in(0); - Node *in1000 = (in100 != nullptr && in100->is_Proj()) ? in100->in(0) : nullptr; + if (Node::is(in10) && + Node::is(in20) && + Node::is(in30) && + in10 == in20 && + in1->Opcode() != in2->Opcode()) { + Node* in100 = in10->in(0); + Node* in1000 = Node::is(in100) ? in100->in(0) : nullptr; // Check that control for in10 comes from other branch of IF from in3 - if( in1000 != nullptr && in1000->is_If() && - in30 == in1000 && (in3->Opcode() != in100->Opcode()) ) { + if (Node::is(in1000) && in30 == in1000 && in3->Opcode() != in100->Opcode()) { // Control pattern checks top_if = (IfNode*)in1000; bot_if = (IfNode*)in10; @@ -347,8 +347,7 @@ bool RegionNode::is_possible_unsafe_loop() const { uint i; for (i = 0; i < max; i++) { Node* n = raw_out(i); - if (n != nullptr && n->is_Phi()) { - PhiNode* phi = n->as_Phi(); + if (PhiNode* phi = isa(n); phi != nullptr) { assert(phi->in(0) == this, "sanity check phi"); if (phi->outcnt() == 0) { continue; // Safe case - no loops @@ -510,7 +509,7 @@ bool RegionNode::is_diamond() const { return false; } Node* diamond_if = left_path->in(0); - if (diamond_if == nullptr || !diamond_if->is_If() || diamond_if != right_path->in(0)) { + if (!is(diamond_if) || diamond_if != right_path->in(0)) { // Not an IfNode merging a diamond or TOP. return false; } @@ -532,7 +531,7 @@ bool RegionNode::is_diamond() const { // the CFG, but we can still strip out dead paths. Node *RegionNode::Ideal(PhaseGVN *phase, bool can_reshape) { if( !can_reshape && !in(0) ) return nullptr; // Already degraded to a Copy - assert(!in(0) || !in(0)->is_Root(), "not a specially hidden merge"); + assert(!is(in(0)), "not a specially hidden merge"); // Check for RegionNode with no Phi users and both inputs come from either // arm of the same IF. If found, then the control-flow split is useless. @@ -545,8 +544,8 @@ Node *RegionNode::Ideal(PhaseGVN *phase, bool can_reshape) { for (uint i = 1; i < req()-1; i++) { Node *if1 = in(i); if( !if1 ) continue; - Node *iff = if1->in(0); - if( !iff || !iff->is_If() ) continue; + IfNode* iff = isa(if1->in(0)); + if (iff == nullptr) continue; for( uint j=i+1; jin(0) == iff && if1->Opcode() != in(j)->Opcode() ) { @@ -910,7 +909,7 @@ bool RegionNode::optimize_trichotomy(PhaseIterGVN* igvn) { if (req() == 3 && in(1) != nullptr && in(2) != nullptr) { // Shape 1: Check if one of the inputs is a region that merges two control // inputs and has no other users (especially no Phi users). - region = in(1)->isa_Region() ? in(1) : in(2)->isa_Region(); + region = in(1)->is_Region() ? in(1) : in(2)->isa_Region(); if (region == nullptr || region->outcnt() != 2 || region->req() != 3) { return false; // No suitable region input found } @@ -1185,7 +1184,7 @@ PhiNode* PhiNode::split_out_instance(const TypePtr* at, PhaseIterGVN *igvn) cons if (in == nullptr || igvn->type(in) == Type::TOP) continue; Node *opt = MemNode::optimize_simple_memory_chain(in, t_oop, nullptr, igvn); - PhiNode *optphi = opt->is_Phi() ? opt->as_Phi() : nullptr; + PhiNode* optphi = opt->isa_Phi(); if (optphi != nullptr && optphi->out_adr_type() == TypePtr::BOTTOM) { opt = node_map[optphi->_idx]; if (opt == nullptr) { @@ -1245,9 +1244,9 @@ void PhiNode::verify_adr_type(bool recursive) const { // Flat array elements shouldn't get their own memory slice until flat_accesses_share_alias is cleared. // It could be the graph has no loads/stores and flat_accesses_share_alias is never cleared. EA could still // create per-element Phis but that wouldn't be a problem as there are no memory accesses for that array. - assert(_adr_type == nullptr || _adr_type->isa_aryptr() == nullptr || - _adr_type->is_aryptr()->is_known_instance() || - !_adr_type->is_aryptr()->is_flat() || + assert(_adr_type == nullptr || !_adr_type->is_aryptr() || + _adr_type->as_aryptr()->is_known_instance() || + !_adr_type->as_aryptr()->is_flat() || !Compile::current()->flat_accesses_share_alias() || _adr_type == TypeAryPtr::INLINES, "flat array element shouldn't get its own slice yet"); @@ -1277,7 +1276,7 @@ const Type* PhiNode::Value(PhaseGVN* phase) const { return Type::TOP; // Check for trip-counted loop. If so, be smarter. - BaseCountedLoopNode* l = r->is_BaseCountedLoop() ? r->as_BaseCountedLoop() : nullptr; + BaseCountedLoopNode* l = r->isa_BaseCountedLoop(); if (l && ((const Node*)l->phi() == this)) { // Trip counted loop! // protect against init_trip() or limit() returning null if (l->can_be_counted_loop(phase)) { @@ -1390,13 +1389,13 @@ const Type* PhiNode::Value(PhaseGVN* phase) const { else { if (jt != ft && jt->base() == ft->base()) { - if (jt->isa_int() && - jt->is_int()->_lo == ft->is_int()->_lo && - jt->is_int()->_hi == ft->is_int()->_hi) + if (jt->is_int() && + jt->as_int()->_lo == ft->as_int()->_lo && + jt->as_int()->_hi == ft->as_int()->_hi) jt = ft; - if (jt->isa_long() && - jt->is_long()->_lo == ft->is_long()->_lo && - jt->is_long()->_hi == ft->is_long()->_hi) + if (jt->is_long() && + jt->as_long()->_lo == ft->as_long()->_lo && + jt->as_long()->_hi == ft->as_long()->_hi) jt = ft; } if (jt != ft) { @@ -1481,9 +1480,8 @@ void PhiNode::verify_type_stability(const PhaseGVN* const phase, const Type* con // Does this Phi represent a simple well-shaped diamond merge? Return the // index of the true path or 0 otherwise. int PhiNode::is_diamond_phi() const { - Node* region = in(0); - assert(region != nullptr && region->is_Region(), "phi must have region"); - if (!region->as_Region()->is_diamond()) { + RegionNode* region = as(in(0)); + if (!region->is_diamond()) { return 0; } @@ -1517,9 +1515,8 @@ bool PhiNode::try_clean_memory_phi(PhaseIterGVN* igvn) { RegionNode* region = in(0)->as_Region(); for (uint i = 1; i < 3; i++) { Node* phi_input = in(i); - if (phi_input != nullptr && phi_input->is_MergeMem() && region->in(i)->outcnt() == 1) { + if (MergeMemNode* merge_mem = isa(phi_input); merge_mem != nullptr && region->in(i)->outcnt() == 1) { // Nothing is control-dependent on path #i except the region itself. - MergeMemNode* merge_mem = phi_input->as_MergeMem(); uint j = 3 - i; Node* other_phi_input = in(j); if (other_phi_input != nullptr && other_phi_input == merge_mem->base_memory() && !is_data_loop(region, phi_input, igvn)) { @@ -1650,9 +1647,9 @@ Node* PhiNode::unique_input(PhaseValues* phase, bool uncast) { #ifdef ASSERT Node* m = un->uncast(); #endif - while (un != nullptr && un->req() == 2 && un->is_ConstraintCast()) { + while (is(un) && un->req() == 2) { Node* next = un->in(1); - if (phase->type(next)->isa_rawptr() && phase->type(un)->isa_oopptr()) { + if (phase->type(next)->is_rawptr() && phase->type(un)->is_oopptr()) { // risk exposing raw ptr at safepoint break; } @@ -2045,7 +2042,7 @@ static Node* split_flow_path(PhaseGVN *phase, PhiNode *phi) { // and from half float will return the SHORT basic type, as that wouldn't be returned typically from TypeInt. static BasicType get_convert_type(Node* convert, const Type* type) { int convert_op = convert->Opcode(); - if (type->isa_int() && (convert_op == Op_ConvHF2F || convert_op == Op_ConvF2HF)) { + if (type->is_int() && (convert_op == Op_ConvHF2F || convert_op == Op_ConvF2HF)) { return T_SHORT; } @@ -2361,7 +2358,7 @@ Node* PhiNode::split_through_mergemem(PhaseIterGVN& igvn) { bool PhiNode::wait_for_cast_input_igvn(const PhaseIterGVN* igvn) const { for (uint i = 1, cnt = req(); i < cnt; ++i) { Node* n = in(i); - while (n != nullptr && n->is_ConstraintCast()) { + while (is(n)) { if (igvn->_worklist.member(n)) { return true; } @@ -2375,14 +2372,15 @@ bool PhiNode::wait_for_cast_input_igvn(const PhaseIterGVN* igvn) const { // Return a node which is more "ideal" than the current node. Must preserve // the CFG, but we can still strip out dead paths. Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { - Node *r = in(0); // RegionNode - assert(r != nullptr && r->is_Region(), "this phi must have a region"); - assert(r->in(0) == nullptr || !r->in(0)->is_Root(), "not a specially hidden merge"); + RegionNode* region = as(in(0)); // RegionNode + assert(!is(region->in(0)), "not a specially hidden merge"); // Note: During parsing, phis are often transformed before their regions. // This means we have to use type_or_null to defend against untyped regions. - if( phase->type_or_null(r) == Type::TOP ) // Dead code? + if (phase->type_or_null(region) == Type::TOP) { + // Dead code? return nullptr; // No change + } Node *top = phase->C->top(); bool new_phi = (outcnt() == 0); // transforming new Phi @@ -2402,13 +2400,13 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { Node* progress = nullptr; // Record if any progress made for( uint j = 1; j < req(); ++j ){ // For all paths in // Check unreachable control paths - Node* rc = r->in(j); + Node* rc = region->in(j); Node* n = in(j); // Get the input if (rc == nullptr || phase->type(rc) == Type::TOP) { if (n != top) { // Not already top? PhaseIterGVN *igvn = phase->is_IterGVN(); if (can_reshape && igvn != nullptr) { - igvn->_worklist.push(r); + igvn->_worklist.push(region); } // Nuke it down set_req_X(j, top, phase); @@ -2463,8 +2461,8 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { // Only one not-null unique input path is left. // Determine if this input is backedge of a loop. // (Skip new phis which have no uses and dead regions). - if (outcnt() > 0 && r->in(0) != nullptr) { - if (is_data_loop(r->as_Region(), uin, phase)) { + if (outcnt() > 0 && region->in(0) != nullptr) { + if (is_data_loop(region, uin, phase)) { // Break this data loop to avoid creation of a dead loop. if (can_reshape) { return top; @@ -2486,10 +2484,10 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { // going away Node* cast = nullptr; const TypeTuple* extra_types = collect_types(phase); - if (phi_type->isa_ptr()) { + if (phi_type->is_ptr()) { const Type* uin_type = phase->type(uin); - if (!phi_type->isa_oopptr() && !uin_type->isa_oopptr()) { - cast = new CastPPNode(r, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); + if (!phi_type->is_oopptr() && !uin_type->is_oopptr()) { + cast = new CastPPNode(region, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); } else { // Use a CastPP for a cast to not null and a CheckCastPP for // a cast to a new klass (and both if both null-ness and @@ -2499,7 +2497,7 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { // null, uin's type must be casted to not null if (phi_type->join(TypePtr::NOTNULL) == phi_type->remove_speculative() && uin_type->join(TypePtr::NOTNULL) != uin_type->remove_speculative()) { - cast = new CastPPNode(r, uin, TypePtr::NOTNULL, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); + cast = new CastPPNode(region, uin, TypePtr::NOTNULL, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); } // If the type of phi and uin, both casted to not null, @@ -2511,14 +2509,14 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { cast = phase->transform(cast); n = cast; } - cast = new CheckCastPPNode(r, n, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); + cast = new CheckCastPPNode(region, n, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); } if (cast == nullptr) { - cast = new CastPPNode(r, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); + cast = new CastPPNode(region, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); } } } else { - cast = ConstraintCastNode::make_cast_for_type(r, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); + cast = ConstraintCastNode::make_cast_for_type(region, uin, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing, extra_types); } assert(cast != nullptr, "cast should be set"); cast = phase->transform(cast); @@ -2537,7 +2535,7 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { #ifdef ASSERT if (ident != uin && !ident->is_top() && !must_wait_for_region_in_irreducible_loop(phase)) { // print this output before failing assert - r->dump(3); + region->dump(3); this->dump(3); ident->dump(); uin->dump(); @@ -2600,7 +2598,7 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { if (opt != nullptr) return opt; } - if (in(1) != nullptr && in(1)->Opcode() == Op_AddP && can_reshape) { + if (is_exact(in(1)) && can_reshape) { // Try to undo Phi of AddP: // (Phi (AddP base address offset) (AddP base2 address2 offset2)) // becomes: @@ -2624,8 +2622,7 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { // i.e. AddP with base == address and same offset as first AddP bool doit = true; for (uint i = 2; i < req(); i++) { - if (in(i) == nullptr || - in(i)->Opcode() != Op_AddP || + if (!is_exact(in(i)) || in(i)->in(AddPNode::Base) == nullptr || in(i)->in(AddPNode::Address) == nullptr || in(i)->in(AddPNode::Offset) == nullptr || @@ -2767,11 +2764,11 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { // Make narrow type for new phi. const Type* narrow_t; if (is_decodeN) { - narrow_t = TypeNarrowOop::make(this->bottom_type()->is_ptr()); + narrow_t = TypeNarrowOop::make(this->bottom_type()->as_ptr()); } else { - narrow_t = TypeNarrowKlass::make(this->bottom_type()->is_ptr()); + narrow_t = TypeNarrowKlass::make(this->bottom_type()->as_ptr()); } - PhiNode* new_phi = new PhiNode(r, narrow_t); + PhiNode* new_phi = new PhiNode(region, narrow_t); uint orig_cnt = req(); for (uint i=1; i VB (Phi ...) (Phi ...) - if (EnableVectorReboxing && can_reshape && progress == nullptr && type()->isa_oopptr()) { + if (EnableVectorReboxing && can_reshape && progress == nullptr && type()->is_oopptr()) { progress = merge_through_phi(this, phase->is_IterGVN()); } @@ -2858,7 +2855,7 @@ Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) { if (can_reshape && type() == Type::MEMORY && out_adr_type() == TypePtr::BOTTOM) { PhaseIterGVN* igvn = phase->is_IterGVN(); uint phi_len = req(); - Node* phi_reg = region(); + Node* phi_reg = this->region(); for (DUIterator_Fast imax, i = phi_reg->fast_outs(imax); i < imax; i++) { Node* u = phi_reg->fast_out(i); assert(!u->is_Phi() || (u->in(0) == phi_reg && u->req() == phi_len), "broken Phi/Region subgraph"); @@ -2948,7 +2945,7 @@ class PushValueTypeDown { for (uint j = 0; j < value_type->field_count(); ++j) { Node* field = value_type->field_value(j); const Type* field_type = _phase->type(field); - if (field_type->isa_instptr() && !field_type->is_valueklassptr() && field_type->is_instptr()->can_be_value_type()) { + if (field_type->is_instptr() && !field_type->is_valueklassptr() && field_type->as_instptr()->can_be_value_type()) { _nodes_from_phi.push(field); } } @@ -3123,7 +3120,7 @@ class PushValueTypeDown { for (uint j = 0; j < value_type->field_count(); ++j) { Node* field = value_type->field_value(j); const Type* field_type = _phase->type(field); - if (field_type->isa_instptr() && !field_type->is_valueklassptr() && field_type->is_instptr()->can_be_value_type()) { + if (field_type->is_instptr() && !field_type->is_valueklassptr() && field_type->as_instptr()->can_be_value_type()) { after.push(field); } } @@ -3195,7 +3192,7 @@ class PushValueTypeDown { vt->merge_with(_phase, n->as_ValueType(), i, transform); } // else nothing to do: phis above vt created by clone_with_phis are initialized to top already. } - if (phi == _root_phi && _root_phi->bottom_type()->isa_narrowoop()) { + if (phi == _root_phi && _root_phi->bottom_type()->is_narrowoop()) { return new EncodePNode(_phase->transform(vt), _root_phi->bottom_type()); } return vt; @@ -3341,12 +3338,11 @@ const TypeTuple* PhiNode::collect_types(PhaseGVN* phase) const { if (t != phi_type && t->higher_equal_speculative(phi_type)) { types.insert_sorted(t); } - while (in != nullptr && in->is_ConstraintCast()) { + for (ConstraintCastNode* cast = isa(in); cast != nullptr; cast = isa(in)) { Node* next = in->in(1); - if (phase->type(next)->isa_rawptr() && phase->type(in)->isa_oopptr()) { + if (phase->type(next)->is_rawptr() && phase->type(in)->is_oopptr()) { break; } - ConstraintCastNode* cast = in->as_ConstraintCast(); for (int j = 0; j < cast->extra_types_count(); ++j) { const Type* extra_t = cast->extra_type_at(j); if (extra_t != phi_type && extra_t->higher_equal_speculative(phi_type)) { @@ -3435,9 +3431,9 @@ Node* PhiNode::merge_through_phi(PhiNode* root_phi, PhaseIterGVN* igvn) { Node* in = n->in(idx); if (in == nullptr) { continue; // ignore dead path - } else if (in->isa_Phi()) { + } else if (PhiNode* in_phi = in->isa_Phi(); in_phi != nullptr) { if (!visited.test_set(in->_idx)) { - stack.push(in->as_Phi(), 1); // ignore control + stack.push(in_phi, 1); // ignore control } } else if (in->Opcode() == Op_VectorBox) { VectorBoxNode* vbox = static_cast(in); @@ -3488,9 +3484,8 @@ bool PhiNode::is_data_loop(RegionNode* r, Node* uin, const PhaseGVN* phase) { //------------------------------is_tripcount----------------------------------- bool PhiNode::is_tripcount(BasicType bt) const { - return (in(0) != nullptr && in(0)->is_BaseCountedLoop() && - in(0)->as_BaseCountedLoop()->bt() == bt && - in(0)->as_BaseCountedLoop()->phi() == this); + BaseCountedLoopNode* bcl = isa(in(0)); + return bcl != nullptr && bcl->bt() == bt && bcl->phi() == this; } //------------------------------out_RegMask------------------------------------ @@ -3645,7 +3640,7 @@ const Type* CatchNode::Value(PhaseGVN* phase) const { Node* valid_length_test = call->in(AllocateNode::ValidLengthTest); const Type* valid_length_test_t = phase->type(valid_length_test); if (length_type == Type::TOP || klass_type == Type::TOP || valid_length_test_t == Type::TOP || - valid_length_test_t->is_int()->is_con(0)) { + valid_length_test_t->as_int()->is_con(0)) { f[CatchProjNode::fall_through_index] = Type::TOP; } } else if( call->req() > TypeFunc::Parms ) { @@ -3677,7 +3672,7 @@ bool CatchProjNode::cmp( const Node &n ) const { // If only 1 target is possible, choose it if it is the main control Node* CatchProjNode::Identity(PhaseGVN* phase) { // If my value is control and no other value is, then treat as ID - const TypeTuple *t = phase->type(in(0))->is_tuple(); + const TypeTuple* t = phase->type(in(0))->as_tuple(); if (t->field_at(_con) != Type::CONTROL) return this; // If we remove the last CatchProj and elide the Catch/CatchProj, then we // also remove any exception table entry. Thus we must know the call diff --git a/src/hotspot/share/opto/cfgnode.hpp b/src/hotspot/share/opto/cfgnode.hpp index cad9f87162c9..41b2e9b958c3 100644 --- a/src/hotspot/share/opto/cfgnode.hpp +++ b/src/hotspot/share/opto/cfgnode.hpp @@ -408,7 +408,7 @@ class PhiNode : public TypeNode { bool can_be_value_type() const { const Type* type = _type->make_oopptr(); - return Arguments::is_valhalla_enabled() && type != nullptr && type->isa_instptr() && type->is_instptr()->can_be_value_type(); + return Arguments::is_valhalla_enabled() && type != nullptr && type->is_instptr() && type->as_instptr()->can_be_value_type(); } Node* try_push_value_types_down(PhaseGVN* phase, bool can_reshape); diff --git a/src/hotspot/share/opto/chaitin.cpp b/src/hotspot/share/opto/chaitin.cpp index e86dc478620c..a4eb65c7c472 100644 --- a/src/hotspot/share/opto/chaitin.cpp +++ b/src/hotspot/share/opto/chaitin.cpp @@ -883,8 +883,8 @@ void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) { lrg.and_with(rm); uint ireg = n->ideal_reg(); - assert( !n->bottom_type()->isa_oop_ptr() || ireg == Op_RegP, - "oops must be in Op_RegP's" ); + assert(!n->bottom_type()->is_oopptr() || ireg == Op_RegP, + "oops must be in Op_RegP's"); // Check for vector live range (only if vector register is used). // On SPARC vector uses RegD which could be misaligned so it is not @@ -916,7 +916,7 @@ void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) { lrg.set_scalable_reg_slots(Matcher::scalable_predicate_reg_slots()); } } - assert(n_type->isa_vect() == nullptr || lrg._is_vector || + assert(!n_type->is_vect() || lrg._is_vector || ireg == Op_RegD || ireg == Op_RegL || ireg == Op_RegVectMask, "vector must be in vector registers"); @@ -979,7 +979,7 @@ void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) { // AMD64 1 1 1 1 1 14 15 // ----------------------------------------------------- lrg.set_reg_pressure(1); // normally one value per register - if( n_type->isa_oop_ptr() ) { + if (n_type->is_oopptr()) { lrg._is_oop = 1; } break; @@ -1127,7 +1127,7 @@ void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) { const RegMask &lrgmask_in = lrg_in.mask(); uint kreg = n->in(k)->ideal_reg(); bool is_vect = RegMask::is_vector(kreg); - assert(n->in(k)->bottom_type()->isa_vect() == nullptr || is_vect || + assert(!n->in(k)->bottom_type()->is_vect() || is_vect || kreg == Op_RegD || kreg == Op_RegL || kreg == Op_RegVectMask, "vector must be in vector registers"); if (lrgmask_in.is_bound(kreg)) @@ -1939,8 +1939,8 @@ Node* PhaseChaitin::find_base_for_derived(Node** derived_base_map, Node* derived // pointers derived from null! These are always along paths that // can't happen at run-time but the optimizer cannot deduce it so // we have to handle it gracefully. - assert(!derived->bottom_type()->isa_narrowoop() || - derived->bottom_type()->make_ptr()->is_ptr()->offset() == 0, "sanity"); + assert(!derived->bottom_type()->is_narrowoop() || + derived->bottom_type()->make_ptr()->as_ptr()->offset() == 0, "sanity"); const TypePtr *tj = derived->bottom_type()->isa_ptr(); // If its an OOP with a non-zero offset, then it is derived. if (tj == nullptr || tj->offset() == 0) { @@ -2108,10 +2108,10 @@ bool PhaseChaitin::stretch_base_pointer_live_ranges(ResourceArea *a) { // This works because we are still in SSA during this call. Node *derived = lrgs(neighbor)._def; const TypePtr *tj = derived->bottom_type()->isa_ptr(); - assert(!derived->bottom_type()->isa_narrowoop() || - derived->bottom_type()->make_ptr()->is_ptr()->offset() == 0, "sanity"); + assert(!derived->bottom_type()->is_narrowoop() || + derived->bottom_type()->make_ptr()->as_ptr()->offset() == 0, "sanity"); // If its an OOP with a non-zero offset, then it is derived. - if (tj && tj->offset() != 0 && tj->isa_oop_ptr()) { + if (tj && tj->offset() != 0 && tj->is_oopptr()) { Node *base = find_base_for_derived(derived_base_map, derived, maxlrg); assert(base->_idx < _lrg_map.size(), ""); // Add reaching DEFs of derived pointer and base pointer as a @@ -2637,20 +2637,20 @@ void PhaseChaitin::verify_base_ptrs(ResourceArea* a) const { worklist.push(check->in(m)); } } else if (check->is_Con()) { - if (is_derived && check->bottom_type()->is_ptr()->offset() != 0) { + if (is_derived && check->bottom_type()->as_ptr()->offset() != 0) { // Derived is null+non-zero offset, base must be null. - assert(check->bottom_type()->is_ptr()->ptr() == TypePtr::Null, "Bad derived pointer"); + assert(check->bottom_type()->as_ptr()->ptr() == TypePtr::Null, "Bad derived pointer"); } else { - assert(check->bottom_type()->is_ptr()->offset() == 0, "Bad base pointer"); + assert(check->bottom_type()->as_ptr()->offset() == 0, "Bad base pointer"); // Base either ConP(nullptr) or loadConP if (check->is_Mach()) { assert(check->as_Mach()->ideal_Opcode() == Op_ConP, "Bad base pointer"); } else { assert(check->Opcode() == Op_ConP && - check->bottom_type()->is_ptr()->ptr() == TypePtr::Null, "Bad base pointer"); + check->bottom_type()->as_ptr()->ptr() == TypePtr::Null, "Bad base pointer"); } } - } else if (check->bottom_type()->is_ptr()->offset() == 0) { + } else if (check->bottom_type()->as_ptr()->offset() == 0) { if (check->is_Proj() || (check->is_Mach() && (check->as_Mach()->ideal_Opcode() == Op_CreateEx || check->as_Mach()->ideal_Opcode() == Op_ThreadLocal || diff --git a/src/hotspot/share/opto/compile.cpp b/src/hotspot/share/opto/compile.cpp index 03de90df0fd9..994d900c734e 100644 --- a/src/hotspot/share/opto/compile.cpp +++ b/src/hotspot/share/opto/compile.cpp @@ -367,8 +367,7 @@ void Compile::remove_useless_late_inlines(GrowableArray* inlines } } -void Compile::remove_useless_late_inlines(GrowableArray* inlines, Node* dead) { - assert(dead != nullptr && dead->is_Call(), "sanity"); +void Compile::remove_useless_late_inlines(GrowableArray* inlines, CallNode* dead) { int found = 0; for (int i = 0; i < inlines->length(); i++) { if (inlines->at(i)->call_node() == dead) { @@ -428,15 +427,15 @@ void Compile::remove_useless_node(Node* dead) { if (dead->for_merge_stores_igvn()) { remove_from_merge_stores_igvn(dead); } - if (dead->is_Call()) { - remove_useless_late_inlines( &_late_inlines, dead); - remove_useless_late_inlines( &_string_late_inlines, dead); - remove_useless_late_inlines( &_boxing_late_inlines, dead); - remove_useless_late_inlines( &_vector_late_inlines, dead); - remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead); + if (CallNode* dead_call = dead->isa_Call(); dead_call != nullptr) { + remove_useless_late_inlines( &_late_inlines, dead_call); + remove_useless_late_inlines( &_string_late_inlines, dead_call); + remove_useless_late_inlines( &_boxing_late_inlines, dead_call); + remove_useless_late_inlines( &_vector_late_inlines, dead_call); + remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead_call); - if (dead->is_CallStaticJava()) { - remove_unstable_if_trap(dead->as_CallStaticJava(), false); + if (CallStaticJavaNode* dead_call_static = dead->isa_CallStaticJava(); dead_call_static != nullptr) { + remove_unstable_if_trap(dead_call_static, false); } } } @@ -1441,11 +1440,11 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { TypePtr::PTR ptr = tj->ptr(); // Known instance (scalarizable allocation) alias only with itself. - bool is_known_inst = tj->isa_oopptr() != nullptr && - tj->is_oopptr()->is_known_instance(); + bool is_known_inst = tj->is_oopptr() && + tj->as_oopptr()->is_known_instance(); // Process weird unsafe references. - if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) { + if (offset == Type::OffsetBot && (tj->is_instptr() /*|| tj->is_klassptr()*/)) { assert(InlineUnsafeOps || StressReflectiveCode || UseAcmpFastPath || UseHashcodeFastPath, "indeterminate pointers come only from unsafe ops"); assert(!is_known_inst, "scalarizable allocation should not have unsafe references"); tj = TypeOopPtr::BOTTOM; @@ -1599,12 +1598,12 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { TypePtr::MaybeFlat); } - if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) { + if (const TypeAryKlassPtr* tk_ary = tk->isa_aryklassptr(); tk_ary != nullptr && tk_ary->elem()->is_klassptr()) { ciKlass* k = ciObjArrayKlass::make(env()->Object_klass()); if (!k || !k->is_loaded()) { // Only fails for some -Xcomp runs tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), Type::Offset(offset), TypePtr::MaybeFlat); } else { - tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, Type::Offset(offset), tk->is_not_flat(), tk->is_not_null_free(), tk->is_flat(), tk->is_null_free(), tk->is_atomic(), tk->is_aryklassptr()->is_refined_type()); + tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk_ary->elem(), k, Type::Offset(offset), tk->is_not_flat(), tk->is_not_null_free(), tk->is_flat(), tk->is_null_free(), tk->is_atomic(), tk_ary->is_refined_type()); } } // Check for precise loads from the primary supertype array and force them @@ -1669,8 +1668,8 @@ void Compile::AliasType::Init(int i, const TypePtr* at) { BasicType Compile::AliasType::basic_type() const { if (element() != nullptr) { - const Type* element = adr_type()->is_aryptr()->elem(); - return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type(); + const Type* element = adr_type()->as_aryptr()->elem(); + return element->is_narrowoop() ? T_OBJECT : element->array_element_basic_type(); } if (field() != nullptr) { return field()->layout_type(); } else { @@ -1693,7 +1692,7 @@ void Compile::AliasType::print_on(outputStream* st) { adr_type()->dump_on(st); const TypeOopPtr* tjp = adr_type()->isa_oopptr(); if (field() != nullptr && tjp) { - if (tjp->is_instptr()->instance_klass() != field()->holder() || + if (tjp->as_instptr()->instance_klass() != field()->holder() || tjp->offset() != field()->offset_in_bytes()) { st->print(" != "); field()->print(); @@ -1767,7 +1766,7 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr // Try casting the type to the other exactness if possible if ((check_exact && finst->instance_klass()->is_loaded() && !finst->instance_klass()->is_abstract()) || (!check_exact && !finst->is_known_instance())) { - const TypePtr* xinst = finst->cast_to_exactness(check_exact)->is_ptr(); + const TypePtr* xinst = finst->cast_to_exactness(check_exact)->as_ptr(); assert(finst == flatten_alias_type(xinst), "exactness must not affect alias type: finst = %s; xinst = %s", Type::str(finst), Type::str(xinst)); } @@ -1792,23 +1791,23 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr _alias_types[idx]->Init(idx, flat); if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false); if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false); - if (flat->isa_instptr()) { + if (flat->is_instptr()) { if (flat->offset() == java_lang_Class::klass_offset() - && flat->is_instptr()->instance_klass() == env()->Class_klass()) + && flat->as_instptr()->instance_klass() == env()->Class_klass()) alias_type(idx)->set_rewritable(false); } ciField* field = nullptr; - if (flat->isa_aryptr()) { + if (flat->is_aryptr()) { #ifdef ASSERT const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE); // (T_BYTE has the weakest alignment and size restrictions...) assert(flat->offset() < header_size_min, "array body reference must be OffsetBot"); #endif - const Type* elemtype = flat->is_aryptr()->elem(); + const Type* elemtype = flat->as_aryptr()->elem(); if (flat->offset() == TypePtr::OffsetBot) { alias_type(idx)->set_element(elemtype); } - int field_offset = flat->is_aryptr()->field_offset().get(); + int field_offset = flat->as_aryptr()->field_offset().get(); if (flat->is_flat() && field_offset != Type::OffsetBot) { ciValueKlass* vk = elemtype->value_klass(); @@ -1816,7 +1815,7 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr field = vk->get_field_by_offset(field_offset, false); } } - if (flat->isa_klassptr()) { + if (flat->is_klassptr()) { if (UseCompactObjectHeaders) { if (flat->offset() == in_bytes(Klass::prototype_header_offset())) alias_type(idx)->set_rewritable(false); @@ -1833,7 +1832,7 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr alias_type(idx)->set_rewritable(false); } - if (flat->isa_instklassptr()) { + if (flat->is_instklassptr()) { if (flat->offset() == in_bytes(InstanceKlass::access_flags_offset())) { alias_type(idx)->set_rewritable(false); } @@ -1868,7 +1867,7 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr // Set field() and is_rewritable() attributes. if (field != nullptr) { alias_type(idx)->set_field(field); - if (flat->isa_aryptr()) { + if (flat->is_aryptr()) { // Fields of flat arrays are rewritable although they are declared final assert(flat->is_flat(), "must be a flat array"); alias_type(idx)->set_rewritable(true); @@ -2143,7 +2142,7 @@ void Compile::process_value_types(PhaseIterGVN &igvn, bool remove) { } if (ret != nullptr) { Node* ret_val = ret->in(TypeFunc::Parms); - if (igvn.type(ret_val)->isa_oopptr() && + if (igvn.type(ret_val)->is_oopptr() && return_val_keeps_allocations_alive(ret_val)) { igvn.replace_input_of(ret, TypeFunc::Parms, ValueTypeNode::tagged_klass(igvn.type(ret_val)->value_klass(), igvn)); assert(ret_val->outcnt() == 0, "should be dead now"); @@ -2240,13 +2239,13 @@ void Compile::process_value_types(PhaseIterGVN &igvn, bool remove) { } void Compile::add_flat_access(Node* n) { - assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name()); + assert(Node::is_exact(n) || Node::is_exact(n), "unexpected node %s", n == nullptr ? "nullptr" : n->Name()); assert(!_flat_access_nodes.contains(n), "duplicate insertion"); _flat_access_nodes.push(n); } void Compile::remove_flat_access(Node* n) { - assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name()); + assert(Node::is_exact(n) || Node::is_exact(n), "unexpected node %s", n == nullptr ? "nullptr" : n->Name()); _flat_access_nodes.remove_if_existing(n); } @@ -2265,9 +2264,9 @@ void Compile::process_flat_accesses(PhaseIterGVN& igvn) { // object. ciInstance* loaded_from = nullptr; if (FoldStableValues) { - const TypeOopPtr* base_type = igvn.type(loadn->base())->is_oopptr(); + const TypeOopPtr* base_type = igvn.type(loadn->base())->as_oopptr(); ciObject* oop = base_type->const_oop(); - int off = igvn.type(loadn->ptr())->isa_ptr()->offset(); + int off = igvn.type(loadn->ptr())->as_ptr()->offset(); if (oop != nullptr && oop->is_instance()) { ciInstance* holder = oop->as_instance(); @@ -2285,7 +2284,7 @@ void Compile::process_flat_accesses(PhaseIterGVN& igvn) { } else if (oop != nullptr && oop->is_array() && off != Type::OffsetBot) { ciArray* array = oop->as_array(); ciConstant elt = array->element_value_by_offset(off); - const TypeAryPtr* aryptr = base_type->is_aryptr(); + const TypeAryPtr* aryptr = base_type->as_aryptr(); if (aryptr->is_stable() && aryptr->is_atomic() && is_reference_type(elt.basic_type()) && elt.as_object()->is_instance()) { loaded_from = elt.as_object()->as_instance(); } @@ -2464,7 +2463,7 @@ void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) { ciArrayKlass* klass = klass_type->exact_klass()->as_array_klass(); assert(klass->is_flat_array_klass(), "must be a flat array"); ciValueKlass* elem_klass = klass->element_klass()->as_value_klass(); - const TypeAryPtr* oop_type = klass_type->as_exact_instance_type()->is_aryptr(); + const TypeAryPtr* oop_type = klass_type->as_exact_instance_type()->as_aryptr(); assert(oop_type->klass_is_exact(), "must be an exact klass"); Node* base = alloc->in(TypeFunc::Memory); @@ -2524,7 +2523,7 @@ void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) { Node* r = m->in(0); for (int j = start_alias; j < num_alias_types(); j++) { const TypePtr* adr_type = get_adr_type(j); - if (!adr_type->isa_aryptr() || !adr_type->is_flat()) { + if (!adr_type->is_aryptr() || !adr_type->is_flat()) { continue; } Node* phi = new PhiNode(r, Type::MEMORY, get_adr_type(j)); @@ -2554,7 +2553,7 @@ void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) { igvn.replace_input_of(m->in(0), TypeFunc::Control, top()); for (int j = start_alias; j < num_alias_types(); j++) { const TypePtr* adr_type = get_adr_type(j); - if (!adr_type->isa_aryptr() || !adr_type->is_flat()) { + if (!adr_type->is_aryptr() || !adr_type->is_flat()) { continue; } MemBarNode* mb = new MemBarCPUOrderNode(this, adr_type, adr_type, nullptr); @@ -2597,7 +2596,7 @@ void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) { igvn.rehash_node_delayed(current); for (int j = start_alias; j < num_alias_types(); j++) { const TypePtr* adr_type = get_adr_type(j); - if (!adr_type->isa_aryptr() || !adr_type->is_flat()) { + if (!adr_type->is_aryptr() || !adr_type->is_flat()) { continue; } current->set_memory_at(j, mm); @@ -3076,7 +3075,7 @@ void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) { if (r != nullptr) { for (uint i = r->req(); i < r->len(); ++i) { Node *n = r->in(i); - if (n != nullptr && n->is_SafePoint()) { + if (Node::is(n)) { r->rm_prec(i); if (n->outcnt() == 0) { igvn.remove_dead_node(n, PhaseIterGVN::NodeOrigin::Graph); @@ -3559,7 +3558,7 @@ static bool is_vector_bitwise_op(Node* n) { } static bool is_vector_bitwise_cone_root(Node* n) { - if (n->bottom_type()->isa_pvectmask() || !is_vector_bitwise_op(n)) { + if (n->bottom_type()->is_pvectmask() || !is_vector_bitwise_op(n)) { return false; } for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { @@ -3860,7 +3859,7 @@ void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &vi Unique_Node_List partition; Unique_Node_List inputs; if (compute_logic_cone(n, partition, inputs)) { - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); Node* pn = partition.at(partition.size() - 1); Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr; if (mask == nullptr || @@ -3880,7 +3879,7 @@ void Compile::optimize_logic_cones(PhaseIterGVN &igvn) { while (list.size() > 0) { Node* n = list.pop(); - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()); if (supported) { VectorSet visited(comp_arena()); @@ -4076,7 +4075,7 @@ void Compile::final_graph_reshaping_impl(Node* n, Final_Reshape_Counts& frc, Uni int alias_idx = get_alias_index(n->as_Mem()->in_adr_type()); assert( n->in(0) != nullptr || alias_idx != Compile::AliasIdxRaw || // oop will be recorded in oop map if load crosses safepoint - (n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() || + (n->is_Load() && (n->as_Load()->bottom_type()->is_oopptr() || LoadNode::is_immutable_value(n->in(MemNode::Address)))), "raw memory operations should have control edge"); } @@ -4283,12 +4282,12 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f // Some platforms can use the constant pool to load ConP. // Do this transformation here since IGVN will convert ConN back to ConP. const Type* t = addp->bottom_type(); - bool is_oop = t->isa_oopptr() != nullptr; - bool is_klass = t->isa_klassptr() != nullptr; + bool is_oop = t->is_oopptr(); + bool is_klass = t->is_klassptr(); if ((is_oop && UseCompressedOops && Matcher::const_oop_prefer_decode() ) || (is_klass && Matcher::const_klass_prefer_decode() && - t->isa_klassptr()->exact_klass()->is_in_encoding_range())) { + t->as_klassptr()->exact_klass()->is_in_encoding_range())) { Node* nn = nullptr; int op = is_oop ? Op_ConN : Op_ConNKlass; @@ -4316,12 +4315,12 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f // Otherwise we will run into the assertion above when visiting that guy. for (uint i = 0; i < n->outcnt(); ++i) { Node *out_i = n->raw_out(i); - if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) { + if (Node::is(out_i) && out_i->in(AddPNode::Base) == addp) { out_i->set_req(AddPNode::Base, nn); #ifdef ASSERT for (uint j = 0; j < out_i->outcnt(); ++j) { Node *out_j = out_i->raw_out(j); - assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp, + assert(!Node::is(out_j) || out_j->in(AddPNode::Base) != addp, "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx); } #endif @@ -4494,10 +4493,10 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f // Load [base_reg + offset], val_reg // NullCheck base_reg // - } else if (t->isa_oopptr()) { + } else if (t->is_oopptr()) { new_in2 = ConNode::make(t->make_narrowoop()); - } else if (t->isa_klassptr()) { - ciKlass* klass = t->is_klassptr()->exact_klass(); + } else if (t->is_klassptr()) { + ciKlass* klass = t->as_klassptr()->exact_klass(); if (klass->is_in_encoding_range()) { new_in2 = ConNode::make(t->make_narrowklass()); } @@ -4532,12 +4531,12 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f } else if (in1->Opcode() == Op_ConP) { const Type* t = in1->bottom_type(); if (t == TypePtr::NULL_PTR) { - assert(t->isa_oopptr(), "null klass?"); + assert(t->is_oopptr(), "null klass?"); n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this); - } else if (t->isa_oopptr()) { + } else if (t->is_oopptr()) { n->subsume_by(ConNode::make(t->make_narrowoop()), this); - } else if (t->isa_klassptr()) { - ciKlass* klass = t->is_klassptr()->exact_klass(); + } else if (t->is_klassptr()) { + ciKlass* klass = t->as_klassptr()->exact_klass(); if (klass->is_in_encoding_range()) { n->subsume_by(ConNode::make(t->make_narrowklass()), this); } else { @@ -4571,7 +4570,7 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f } case Op_Phi: - if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) { + if (n->as_Phi()->bottom_type()->is_narrowoop() || n->as_Phi()->bottom_type()->is_narrowklass()) { // The EncodeP optimization may create Phi with the same edges // for all paths. It is not handled well by Register Allocator. Node* unique_in = n->in(1); @@ -4781,7 +4780,7 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f } case Op_ConNKlass: { const TypePtr* tp = n->as_Type()->type()->make_ptr(); - ciKlass* klass = tp->is_klassptr()->exact_klass(); + ciKlass* klass = tp->as_klassptr()->exact_klass(); assert(klass->is_in_encoding_range(), "klass cannot be compressed"); break; } @@ -4992,7 +4991,7 @@ bool Compile::final_graph_reshaping() { record_method_not_compilable("malformed control flow"); return true; // Not all targets reachable! } - } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) { + } else if (n->is_PCTable() && n->in(0) && Node::is(n->in(0)->in(0))) { CallNode* call = n->in(0)->in(0)->as_Call(); if (call->entry_point() == OptoRuntime::new_array_Java() || call->entry_point() == OptoRuntime::new_array_nozero_Java()) { @@ -5409,20 +5408,20 @@ Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* su } const Type* superelem = superk; - if (superk->isa_aryklassptr()) { + if (const TypeAryKlassPtr* superk_ary = superk->isa_aryklassptr(); superk_ary != nullptr) { int ignored; - superelem = superk->is_aryklassptr()->base_element_type(ignored); + superelem = superk_ary->base_element_type(ignored); // Do not fold the subtype check to an array klass pointer comparison for null-able value type arrays // because null-free [LMyValue <: null-able [LMyValue but the klasses are different. Perform a full test. - if (!superk->is_aryklassptr()->is_null_free() && superk->is_aryklassptr()->elem()->isa_instklassptr() && - superk->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->is_value_klass()) { + if (!superk_ary->is_null_free() && superk_ary->elem()->is_instklassptr() && + superk_ary->elem()->as_instklassptr()->instance_klass()->is_value_klass()) { return SSC_full_test; } } - if (superelem->isa_instklassptr()) { - ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass(); + if (superelem->is_instklassptr()) { + ciInstanceKlass* ik = superelem->as_instklassptr()->instance_klass(); if (!ik->has_subklass()) { if (!ik->is_final()) { // Add a dependency if there is a chance of a later subclass. @@ -6018,7 +6017,7 @@ void Compile::sort_macro_nodes() { } } -void Compile::print_method(CompilerPhaseType compile_phase, int level, Node* n) { +void Compile::print_method(CompilerPhaseType compile_phase, int level, const Node* n) { if (failing_internal()) { return; } // failing_internal to not stress bailouts from printing code. EventCompilerPhase event(UNTIMED); if (event.should_commit()) { diff --git a/src/hotspot/share/opto/compile.hpp b/src/hotspot/share/opto/compile.hpp index 7f79b86b0d63..8ec53f3d7875 100644 --- a/src/hotspot/share/opto/compile.hpp +++ b/src/hotspot/share/opto/compile.hpp @@ -738,7 +738,7 @@ class Compile : public Phase { void begin_method(); void end_method(); - void print_method(CompilerPhaseType compile_phase, int level, Node* n = nullptr); + void print_method(CompilerPhaseType compile_phase, int level, const Node* n = nullptr); Stress& stress() { return _stress; } @@ -1176,7 +1176,7 @@ class Compile : public Phase { void remove_useless_nodes(GrowableArray& node_list, const Unique_Node_List& useful); void remove_useless_late_inlines(GrowableArray* inlines, const Unique_Node_List& useful); - void remove_useless_late_inlines(GrowableArray* inlines, Node* dead); + void remove_useless_late_inlines(GrowableArray* inlines, CallNode* dead); void remove_useless_coarsened_locks(const Unique_Node_List& useful); diff --git a/src/hotspot/share/opto/connode.cpp b/src/hotspot/share/opto/connode.cpp index 3538342b5d45..779b58a1d66b 100644 --- a/src/hotspot/share/opto/connode.cpp +++ b/src/hotspot/share/opto/connode.cpp @@ -43,21 +43,21 @@ uint ConNode::hash() const { //------------------------------make------------------------------------------- ConNode *ConNode::make(const Type *t) { - if (t->isa_half_float_constant()) { - return new ConHNode( t->is_half_float_constant() ); + if (t->is_half_float_constant()) { + return new ConHNode(t->as_half_float_constant()); } - switch( t->basic_type() ) { - case T_INT: return new ConINode( t->is_int() ); - case T_LONG: return new ConLNode( t->is_long() ); - case T_FLOAT: return new ConFNode( t->is_float_constant() ); - case T_DOUBLE: return new ConDNode( t->is_double_constant() ); - case T_VOID: return new ConNode ( Type::TOP ); - case T_OBJECT: return new ConPNode( t->is_ptr() ); - case T_ARRAY: return new ConPNode( t->is_aryptr() ); - case T_ADDRESS: return new ConPNode( t->is_ptr() ); - case T_NARROWOOP: return new ConNNode( t->is_narrowoop() ); - case T_NARROWKLASS: return new ConNKlassNode( t->is_narrowklass() ); - case T_METADATA: return new ConPNode( t->is_ptr() ); + switch (t->basic_type()) { + case T_INT: return new ConINode(t->as_int()); + case T_LONG: return new ConLNode(t->as_long()); + case T_FLOAT: return new ConFNode(t->as_float_constant()); + case T_DOUBLE: return new ConDNode(t->as_double_constant()); + case T_VOID: return new ConNode (Type::TOP); + case T_OBJECT: return new ConPNode(t->as_ptr()); + case T_ARRAY: return new ConPNode(t->as_aryptr()); + case T_ADDRESS: return new ConPNode(t->as_ptr()); + case T_NARROWOOP: return new ConNNode(t->as_narrowoop()); + case T_NARROWKLASS: return new ConNKlassNode(t->as_narrowklass()); + case T_METADATA: return new ConPNode(t->as_ptr()); // Expected cases: TypePtr::NULL_PTR, any is_rawptr() // Also seen: AnyPtr(TopPTR *+top); // %%%% Stop using TypePtr::NULL_PTR to represent nulls: use either TypeRawPtr::NULL_PTR diff --git a/src/hotspot/share/opto/convertnode.cpp b/src/hotspot/share/opto/convertnode.cpp index 94d7a5afc659..ec8e160e7a09 100644 --- a/src/hotspot/share/opto/convertnode.cpp +++ b/src/hotspot/share/opto/convertnode.cpp @@ -60,7 +60,7 @@ const Type* Conv2BNode::Value(PhaseGVN* phase) const { return TypeInt::BOOL; } if (t->base() != Type::Int) return TypeInt::BOOL; - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); if( ti->_hi < 0 || ti->_lo > 0 ) return TypeInt::ONE; return TypeInt::BOOL; } @@ -77,9 +77,9 @@ Node* Conv2BNode::Ideal(PhaseGVN* phase, bool can_reshape) { // Get type of comparison to make const Type* t = phase->type(in(1)); Node* cmp = nullptr; - if (t->isa_int()) { + if (t->is_int()) { cmp = phase->transform(new CmpINode(in(1), phase->intcon(0))); - } else if (t->isa_ptr()) { + } else if (t->is_ptr()) { cmp = phase->transform(new CmpPNode(in(1), phase->zerocon(BasicType::T_OBJECT))); } else { assert(false, "Unrecognized comparison for Conv2B: %s", NodeClassNames[in(1)->Opcode()]); @@ -156,7 +156,7 @@ const Type* ConvD2FNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::DOUBLE ) return Type::FLOAT; - const TypeD *td = t->is_double_constant(); + const TypeD* td = t->as_double_constant(); return TypeF::make( (float)td->getd() ); } @@ -188,7 +188,7 @@ const Type* ConvD2INode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::DOUBLE ) return TypeInt::INT; - const TypeD *td = t->is_double_constant(); + const TypeD* td = t->as_double_constant(); return TypeInt::make( SharedRuntime::d2i( td->getd() ) ); } @@ -205,7 +205,7 @@ const Type* ConvD2LNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::DOUBLE ) return TypeLong::LONG; - const TypeD *td = t->is_double_constant(); + const TypeD* td = t->as_double_constant(); return TypeLong::make( SharedRuntime::d2l( td->getd() ) ); } @@ -214,7 +214,7 @@ Node* ConvD2LNode::Identity(PhaseGVN* phase) { // Remove ConvD2L->ConvL2D->ConvD2L sequences. if( in(1) ->Opcode() == Op_ConvL2D && in(1)->in(1)->Opcode() == Op_ConvD2L ) - return in(1)->in(1); + return in(1)->in(1); return this; } @@ -224,7 +224,7 @@ const Type* ConvF2DNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::FLOAT ) return Type::DOUBLE; - const TypeF *tf = t->is_float_constant(); + const TypeF* tf = t->as_float_constant(); return TypeD::make( (double)tf->getf() ); } @@ -237,7 +237,7 @@ const Type* ConvF2HFNode::Value(PhaseGVN* phase) const { return TypeInt::SHORT; } - const TypeF *tf = t->is_float_constant(); + const TypeF* tf = t->as_float_constant(); return TypeInt::make( StubRoutines::f2hf(tf->getf()) ); } @@ -293,7 +293,7 @@ Node* ConvF2HFNode::Ideal(PhaseGVN* phase, bool can_reshape) { if (conF != nullptr && varS != nullptr && - conF->bottom_type()->isa_float_constant() != nullptr && + conF->bottom_type()->is_float_constant() && Matcher::match_rule_supported(Float16NodeFactory::get_float16_binary_oper(binopF->Opcode())) && Matcher::match_rule_supported(Op_ReinterpretS2HF) && Matcher::match_rule_supported(Op_ReinterpretHF2S) && @@ -338,7 +338,7 @@ const Type* ConvF2INode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::FLOAT ) return TypeInt::INT; - const TypeF *tf = t->is_float_constant(); + const TypeF* tf = t->as_float_constant(); return TypeInt::make( SharedRuntime::f2i( tf->getf() ) ); } @@ -357,7 +357,7 @@ const Type* ConvF2LNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::FLOAT ) return TypeLong::LONG; - const TypeF *tf = t->is_float_constant(); + const TypeF* tf = t->as_float_constant(); return TypeLong::make( SharedRuntime::f2l( tf->getf() ) ); } @@ -379,7 +379,7 @@ const Type* ConvHF2FNode::Value(PhaseGVN* phase) const { return Type::FLOAT; } - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); if (ti->is_con()) { return TypeF::make( StubRoutines::hf2f(ti->get_con()) ); } @@ -391,7 +391,7 @@ const Type* ConvHF2FNode::Value(PhaseGVN* phase) const { const Type* ConvI2DNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); if( ti->is_con() ) return TypeD::make( (double)ti->get_con() ); return Type::DOUBLE; } @@ -401,7 +401,7 @@ const Type* ConvI2DNode::Value(PhaseGVN* phase) const { const Type* ConvI2FNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); if( ti->is_con() ) return TypeF::make( (float)ti->get_con() ); return Type::FLOAT; } @@ -422,14 +422,14 @@ const Type* ConvI2LNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) { return Type::TOP; } - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); const Type* tl = TypeLong::make(ti->_lo, ti->_hi, ti->_widen); // Join my declared type against my incoming type. tl = tl->filter(_type); - if (!tl->isa_long()) { + if (!tl->is_long()) { return tl; } - const TypeLong* this_type = tl->is_long(); + const TypeLong* this_type = tl->as_long(); // Do NOT remove this node's type assertion until no more loop ops can happen. if (phase->C->post_loop_opts_phase()) { const TypeInt* in_type = phase->type(in(1))->isa_int(); @@ -741,8 +741,8 @@ bool Compile::push_thru_add(PhaseGVN* phase, Node* z, const TypeInteger* tz, con if (phase->type(y) == Type::TOP) { return false; } - const TypeInteger* tx = phase->type(x)->is_integer(in_bt); - const TypeInteger* ty = phase->type(y)->is_integer(in_bt); + const TypeInteger* tx = phase->type(x)->as_integer(in_bt); + const TypeInteger* ty = phase->type(y)->as_integer(in_bt); if (ranges_overlap(tx, ty, tz, z, true, in_bt) || ranges_overlap(tx, ty, tz, z, false, in_bt)) { @@ -756,7 +756,7 @@ bool Compile::push_thru_add(PhaseGVN* phase, Node* z, const TypeInteger* tz, con //------------------------------Ideal------------------------------------------ Node* ConvI2LNode::Ideal(PhaseGVN* phase, bool can_reshape) { - const TypeLong* this_type = this->type()->is_long(); + const TypeLong* this_type = this->type()->as_long(); if (can_reshape && !phase->C->post_loop_opts_phase()) { // makes sure we run ::Value to potentially remove type assertion after loop opts phase->C->record_for_post_loop_opts_igvn(this); @@ -798,8 +798,8 @@ Node* ConvI2LNode::Ideal(PhaseGVN* phase, bool can_reshape) { Node* x = z->in(1); Node* y = z->in(2); - Node* cx = find_or_make_convI2L(igvn, x, rx->is_long()); - Node* cy = find_or_make_convI2L(igvn, y, ry->is_long()); + Node* cx = find_or_make_convI2L(igvn, x, rx->as_long()); + Node* cy = find_or_make_convI2L(igvn, y, ry->as_long()); switch (op) { case Op_AddI: return new AddLNode(cx, cy); case Op_SubI: return new SubLNode(cx, cy); @@ -816,7 +816,7 @@ Node* ConvI2LNode::Ideal(PhaseGVN* phase, bool can_reshape) { const Type* ConvL2DNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeLong *tl = t->is_long(); + const TypeLong* tl = t->as_long(); if( tl->is_con() ) return TypeD::make( (double)tl->get_con() ); return Type::DOUBLE; } @@ -826,7 +826,7 @@ const Type* ConvL2DNode::Value(PhaseGVN* phase) const { const Type* ConvL2FNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeLong *tl = t->is_long(); + const TypeLong* tl = t->as_long(); if( tl->is_con() ) return TypeF::make( (float)tl->get_con() ); return Type::FLOAT; } @@ -843,7 +843,7 @@ Node* ConvL2INode::Identity(PhaseGVN* phase) { const Type* ConvL2INode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeLong *tl = t->is_long(); + const TypeLong* tl = t->as_long(); const TypeInt* ti = TypeInt::INT; if (tl->is_con()) { // Easy case. @@ -913,8 +913,8 @@ const Type* RoundDoubleModeNode::Value(PhaseGVN* phase) const { const Type* ReinterpretS2HFNode::Value(PhaseGVN* phase) const { const Type* type = phase->type(in(1)); // Convert short constant value to a Half Float constant value - if ((type->isa_int() && type->is_int()->is_con())) { - jshort hfval = type->is_int()->get_con(); + if (type->is_int() && type->as_int()->is_con()) { + jshort hfval = type->as_int()->get_con(); return TypeH::make(hfval); } return Type::HALF_FLOAT; @@ -922,7 +922,7 @@ const Type* ReinterpretS2HFNode::Value(PhaseGVN* phase) const { Node* ReinterpretS2HFNode::Identity(PhaseGVN* phase) { if (in(1)->Opcode() == Op_ReinterpretHF2S) { - assert(in(1)->in(1)->bottom_type()->isa_half_float(), ""); + assert(in(1)->in(1)->bottom_type()->is_half_float(), ""); return in(1)->in(1); } return this; @@ -931,8 +931,8 @@ Node* ReinterpretS2HFNode::Identity(PhaseGVN* phase) { const Type* ReinterpretHF2SNode::Value(PhaseGVN* phase) const { const Type* type = phase->type(in(1)); // Convert Half float constant value to short constant value. - if (type->isa_half_float_constant()) { - jshort hfval = type->is_half_float_constant()->_f; + if (type->is_half_float_constant()) { + jshort hfval = type->as_half_float_constant()->_f; return TypeInt::make(hfval); } return TypeInt::SHORT; diff --git a/src/hotspot/share/opto/countbitsnode.cpp b/src/hotspot/share/opto/countbitsnode.cpp index 1601b33ea2b6..670b50b6bf60 100644 --- a/src/hotspot/share/opto/countbitsnode.cpp +++ b/src/hotspot/share/opto/countbitsnode.cpp @@ -69,7 +69,7 @@ const Type* CountLeadingZerosINode::Value(PhaseGVN* phase) const { // // A more detailed proof using Z3 can be found at: // https://github.com/openjdk/jdk/pull/25928#discussion_r2256750507 - const TypeInt* ti = t->is_int(); + const TypeInt* ti = t->as_int(); return TypeInt::make(count_leading_zeros_int(~ti->_bits._zeros), count_leading_zeros_int(ti->_bits._ones), ti->_widen); @@ -84,7 +84,7 @@ const Type* CountLeadingZerosLNode::Value(PhaseGVN* phase) const { // The proof of correctness is same as the above comments // in `CountLeadingZerosINode::Value`. - const TypeLong* tl = t->is_long(); + const TypeLong* tl = t->as_long(); return TypeInt::make(count_leading_zeros_long(~tl->_bits._zeros), count_leading_zeros_long(tl->_bits._ones), tl->_widen); @@ -113,7 +113,7 @@ const Type* CountTrailingZerosINode::Value(PhaseGVN* phase) const { // // A more detailed proof using Z3 can be found at: // https://github.com/openjdk/jdk/pull/25928#discussion_r2256750507 - const TypeInt* ti = t->is_int(); + const TypeInt* ti = t->as_int(); return TypeInt::make(count_trailing_zeros_int(~ti->_bits._zeros), count_trailing_zeros_int(ti->_bits._ones), ti->_widen); @@ -128,7 +128,7 @@ const Type* CountTrailingZerosLNode::Value(PhaseGVN* phase) const { // The proof of correctness is same as the above comments // in `CountTrailingZerosINode::Value`. - const TypeLong* tl = t->is_long(); + const TypeLong* tl = t->as_long(); return TypeInt::make(count_trailing_zeros_long(~tl->_bits._zeros), count_trailing_zeros_long(tl->_bits._ones), tl->_widen); @@ -158,7 +158,7 @@ const Type* PopCountINode::Value(PhaseGVN* phase) const { if (t == Type::TOP) { return Type::TOP; } - const TypeInt* tint = t->is_int(); + const TypeInt* tint = t->as_int(); KnownBits bits = tint->_bits; return TypeInt::make(population_count(bits._ones), population_count(~bits._zeros), tint->_widen); @@ -169,7 +169,7 @@ const Type* PopCountLNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) { return Type::TOP; } - const TypeLong* tlong = t->is_long(); + const TypeLong* tlong = t->as_long(); KnownBits bits = tlong->_bits; return TypeInt::make(population_count(bits._ones), population_count(~bits._zeros), tlong->_widen); } diff --git a/src/hotspot/share/opto/divnode.cpp b/src/hotspot/share/opto/divnode.cpp index 1c2a4c97eb67..b5efeb227ed3 100644 --- a/src/hotspot/share/opto/divnode.cpp +++ b/src/hotspot/share/opto/divnode.cpp @@ -659,8 +659,8 @@ const Type* DivINode::Value(PhaseGVN* phase) const { return TypeInt::ONE; } - const TypeInt* i1 = t1->is_int(); - const TypeInt* i2 = t2->is_int(); + const TypeInt* i1 = t1->as_int(); + const TypeInt* i2 = t2->as_int(); return compute_signed_div_type(i1, i2); } @@ -726,8 +726,8 @@ const Type* DivLNode::Value(PhaseGVN* phase) const { return TypeLong::ONE; } - const TypeLong* i1 = t1->is_long(); - const TypeLong* i2 = t2->is_long(); + const TypeLong* i1 = t1->as_long(); + const TypeLong* i2 = t2->as_long(); return compute_signed_div_type(i1, i2); } @@ -1105,7 +1105,7 @@ Node *ModINode::Ideal(PhaseGVN *phase, bool can_reshape) { // Get the modulus const Type *t = phase->type( in(2) ); if( t == Type::TOP ) return nullptr; - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); // Check for useless control input // Check for excluding mod-zero case @@ -1241,8 +1241,8 @@ static const Type* mod_value(const PhaseGVN* phase, const Node* in1, const Node* return TypeInteger::zero(bt); } - const TypeInteger* i1 = t1->is_integer(bt); - const TypeInteger* i2 = t2->is_integer(bt); + const TypeInteger* i1 = t1->as_integer(bt); + const TypeInteger* i2 = t2->as_integer(bt); if (i1->is_con() && i2->is_con()) { // We must be modulo'ing 2 int constants. // Special case: min_jlong % '-1' is UB, and e.g., x86 triggers a division error. @@ -1404,7 +1404,7 @@ Node *ModLNode::Ideal(PhaseGVN *phase, bool can_reshape) { // Get the modulus const Type *t = phase->type( in(2) ); if( t == Type::TOP ) return nullptr; - const TypeLong *tl = t->is_long(); + const TypeLong* tl = t->as_long(); // Check for useless control input // Check for excluding mod-zero case @@ -1614,7 +1614,7 @@ const Type* ModFloatingNode::Value(PhaseGVN* phase) const { } const Type* constant_result = get_result_if_constant(dividend_type, divisor_type); if (constant_result != nullptr) { - const TypeTuple* tt = t->is_tuple(); + const TypeTuple* tt = t->as_tuple(); uint cnt = tt->cnt(); uint param_cnt = cnt - TypeFunc::Parms; const Type** fields = TypeTuple::fields(param_cnt); diff --git a/src/hotspot/share/opto/doCall.cpp b/src/hotspot/share/opto/doCall.cpp index a0adad57c8eb..c75bd65ba757 100644 --- a/src/hotspot/share/opto/doCall.cpp +++ b/src/hotspot/share/opto/doCall.cpp @@ -948,7 +948,7 @@ void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) { if (!default_handler) { bcis.append(-1); - const Type* extype = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr(); + const Type* extype = TypeOopPtr::make_from_klass(env()->Throwable_klass())->as_instptr(); extype = extype->join(TypeInstPtr::NOTNULL); extypes.append(extype); } @@ -971,7 +971,7 @@ void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) { set_control(ctrl); // Create exception oop - const TypeInstPtr* extype = extypes.at(i)->is_instptr(); + const TypeInstPtr* extype = extypes.at(i)->as_instptr(); Node* ex_oop = _gvn.transform(new CreateExNode(extypes.at(i), ctrl, i_o)); // Handle unloaded exception classes. @@ -1037,7 +1037,7 @@ void Parse::catch_inline_exceptions(SafePointNode* ex_map) { const TypeInstPtr* ex_type = _gvn.type(ex_node)->isa_instptr(); NOT_PRODUCT(if (ex_type==nullptr) tty->print_cr("*** Exception not InstPtr")); if (ex_type == nullptr) - ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr(); + ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->as_instptr(); // determine potential exception handlers ciExceptionHandlerStream handlers(method(), bci(), @@ -1127,7 +1127,7 @@ void Parse::catch_inline_exceptions(SafePointNode* ex_map) { Node* not_subtype_ctrl = gen_subtype_check(ex_klass_node, con); if (!stopped()) { PreserveJVMState pjvms(this); - const TypeInstPtr* tinst = TypeOopPtr::make_from_klass_unique(klass)->cast_to_ptr_type(TypePtr::NotNull)->is_instptr(); + const TypeInstPtr* tinst = TypeOopPtr::make_from_klass_unique(klass)->cast_to_ptr_type(TypePtr::NotNull)->as_instptr(); assert(klass->has_subklass() || tinst->klass_is_exact(), "lost exactness"); Node* ex_oop = _gvn.transform(new CheckCastPPNode(control(), ex_node, tinst)); if (PrintOpto && WizardMode) { @@ -1255,18 +1255,18 @@ ciMethod* Compile::optimize_inlining(ciMethod* caller, ciInstanceKlass* klass, c ciInstanceKlass* actual_receiver = klass; // Array methods are all inherited from Object, and are monomorphic. // finalize() call on array is not allowed. - if (receiver_type->isa_aryptr() && + if (receiver_type->is_aryptr() && callee->holder() == env()->Object_klass() && callee->name() != ciSymbols::finalize_method_name()) { return callee; } // All other interesting cases are instance klasses. - if (!receiver_type->isa_instptr()) { + if (!receiver_type->is_instptr()) { return nullptr; } - ciInstanceKlass* receiver_klass = receiver_type->is_instptr()->instance_klass(); + ciInstanceKlass* receiver_klass = receiver_type->as_instptr()->instance_klass(); if (receiver_klass->is_loaded() && receiver_klass->is_initialized() && !receiver_klass->is_interface() && (receiver_klass == actual_receiver || receiver_klass->is_subtype_of(actual_receiver))) { // ikl is a same or better type than the original actual_receiver, diff --git a/src/hotspot/share/opto/escape.cpp b/src/hotspot/share/opto/escape.cpp index 611275b3a8ac..7049b9a2c4fd 100644 --- a/src/hotspot/share/opto/escape.cpp +++ b/src/hotspot/share/opto/escape.cpp @@ -172,7 +172,7 @@ bool ConnectionGraph::compute_escape() { Node* n = ideal_nodes.at(next); if (n->is_Mem() && !n->in(MemNode::Address)->is_AddP() && - _igvn->type(n->in(MemNode::Address))->isa_oopptr()) { + _igvn->type(n->in(MemNode::Address))->is_oopptr()) { // EA expects on-heap memory addresses to be represented by an AddP. An AddP with a zero // offset can be optimized to its oop base, so recreate it. Node* addp = AddPNode::make_with_base(n->in(MemNode::Address), n->in(MemNode::Address), _igvn->MakeConX(0)); @@ -601,7 +601,7 @@ bool ConnectionGraph::can_reduce_check_users(Node* n, uint nesting) const { if (!use_use->is_Load() || !use_use->as_Load()->can_split_through_phi_base(_igvn)) { NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. AddP user isn't a [splittable] Load(): %s", n->_idx, _invocation, use_use->Name());) return false; - } else if (load_type->isa_narrowklass() || load_type->isa_klassptr()) { + } else if (load_type->is_narrowklass() || load_type->is_klassptr()) { NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. [Narrow] Klass Load: %s", n->_idx, _invocation, use_use->Name());) return false; } @@ -611,7 +611,7 @@ bool ConnectionGraph::can_reduce_check_users(Node* n, uint nesting) const { return false; } else if (use->is_CastPP()) { const Type* cast_t = _igvn->type(use); - if (cast_t == nullptr || cast_t->make_ptr()->isa_instptr() == nullptr) { + if (cast_t == nullptr || !cast_t->make_ptr()->is_instptr()) { #ifndef PRODUCT if (TraceReduceAllocationMerges) { tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP is not to an instance.", n->_idx, _invocation); @@ -683,14 +683,14 @@ bool ConnectionGraph::can_reduce_phi(PhiNode* ophi) const { // If there was an error attempting to reduce allocation merges for this // method we might have disabled the compilation and be retrying with RAM // disabled. - if (!_compile->do_reduce_allocation_merges() || ophi->region() == nullptr || ophi->region()->Opcode() != Op_Region) { + if (!_compile->do_reduce_allocation_merges() || !Node::is_exact(ophi->region())) { return false; } const Type* phi_t = _igvn->type(ophi); if (phi_t == nullptr || phi_t->make_ptr() == nullptr || - phi_t->make_ptr()->isa_aryptr() != nullptr) { + phi_t->make_ptr()->is_aryptr()) { return false; } @@ -809,9 +809,9 @@ Node* ConnectionGraph::split_castpp_load_through_phi(Node* curr_addp, Node* curr // The data_phi merging the loads needs to be nullable if // we are loading pointers. if (load_type->make_ptr() != nullptr) { - if (load_type->isa_narrowoop()) { + if (load_type->is_narrowoop()) { load_type = load_type->meet(TypeNarrowOop::NULL_PTR); - } else if (load_type->isa_ptr()) { + } else if (load_type->is_ptr()) { load_type = load_type->meet(TypePtr::NULL_PTR); } else { assert(false, "Unexpected load ptr type."); @@ -1089,7 +1089,7 @@ void ConnectionGraph::updates_after_load_split(Node* data_phi, Node* previous_lo assert(data_phi != previous_load, "Output of split_through_phi is same as input."); assert(data_phi->is_Phi(), "Output of split_through_phi isn't a Phi."); - if (data_phi == nullptr || !data_phi->is_Phi()) { + if (!Node::is(data_phi)) { // Make this a retry? return ; } @@ -1555,7 +1555,7 @@ void ConnectionGraph::verify_ram_nodes(Compile* C, Node* root) { if (sfpt->is_SafePoint()) { int merge_idx = merge->merge_pointer_idx(sfpt->as_SafePoint()->jvms()); - if (sfpt->in(merge_idx) != nullptr && sfpt->in(merge_idx)->is_SafePointScalarMerge()) { + if (Node::is(sfpt->in(merge_idx))) { assert(false, "SafePointScalarMerge nodes can't be nested."); C->record_failure(C2Compiler::retry_no_reduce_allocation_merges()); } @@ -1623,7 +1623,7 @@ bool ConnectionGraph::has_arg_escape(CallJavaNode* call) { const TypeTuple* d = call->tf()->domain_sig(); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); - if (at->isa_oopptr() != nullptr) { + if (at->is_oopptr()) { return true; } } @@ -1643,7 +1643,7 @@ void ConnectionGraph::add_objload_to_connection_graph(Node* n, Unique_Node_List< Node* adr = n->in(MemNode::Address); #ifdef ASSERT if (!adr->is_AddP()) { - assert(_igvn->type(adr)->isa_rawptr(), "sanity"); + assert(_igvn->type(adr)->is_rawptr(), "sanity"); } else { assert((ptnode_adr(adr->_idx) == nullptr || ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity"); @@ -1660,7 +1660,7 @@ void ConnectionGraph::add_proj(Node* n, Unique_Node_List* delayed_worklist } else if (n->in(0)->is_LoadFlat()) { // Treat LoadFlat outputs similar to a call return value add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist); - } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() && n->bottom_type()->isa_ptr()) { + } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() && n->bottom_type()->is_ptr()) { CallNode* call = n->in(0)->as_Call(); assert(call->tf()->returns_value_type_as_fields(), ""); if (n->as_Proj()->_con == TypeFunc::Parms || !returns_an_argument(call) || has_incompatible_argument_return(call)) { @@ -1714,7 +1714,7 @@ void ConnectionGraph::add_node_to_connection_graph(Node* n, Unique_Node_Listfast_outs(imax); i < imax && !returns_oop; i++) { ProjNode* pn = n->fast_out(i)->as_Proj(); - if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->isa_ptr()) { + if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->is_ptr()) { returns_oop = true; } } @@ -1845,7 +1845,7 @@ void ConnectionGraph::add_node_to_connection_graph(Node* n, Unique_Node_Listreq(); i++) { - if (igvn->type(n->in(i))->isa_oopptr()) { + if (igvn->type(n->in(i))->is_oopptr()) { add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(i), delayed_worklist); } } @@ -1896,7 +1896,7 @@ void ConnectionGraph::add_node_to_connection_graph(Node* n, Unique_Node_Listin(i); if (in != nullptr) { const Type* at = _igvn->type(in); - if (!at->isa_ptr()) continue; + if (!at->is_ptr()) continue; add_local_var(n, PointsToNode::GlobalEscape); delayed_worklist->push(n); @@ -2028,7 +2028,7 @@ void ConnectionGraph::add_final_edges(Node *n) { // Returned oops always escape, including oop fields of returned scalarized value types. DEBUG_ONLY(bool has_oop = false;) for (uint i = TypeFunc::Parms; i < n->req(); i++) { - if (_igvn->type(n->in(i))->isa_oopptr()) { + if (_igvn->type(n->in(i))->is_oopptr()) { DEBUG_ONLY(has_oop = true;) add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(i), nullptr); } @@ -2070,9 +2070,9 @@ void ConnectionGraph::add_final_edges(Node *n) { for (uint i = 2; i < n->req(); i++) { Node* adr = n->in(i); const Type* at = _igvn->type(adr); - if (!adr->is_top() && at->isa_ptr()) { + if (!adr->is_top() && at->is_ptr()) { assert(at == Type::TOP || at == TypePtr::NULL_PTR || - at->isa_ptr() != nullptr, "expecting a pointer"); + at->is_ptr(), "expecting a pointer"); if (adr->is_AddP()) { adr = get_addp_base(adr); } @@ -2089,7 +2089,7 @@ void ConnectionGraph::add_final_edges(Node *n) { Node* in = n->in(i); if (in != nullptr) { const Type* at = _igvn->type(in); - if (!at->isa_ptr()) continue; + if (!at->is_ptr()) continue; if (in->is_AddP()) { in = get_addp_base(in); @@ -2122,7 +2122,7 @@ void ConnectionGraph::add_to_congraph_unsafe_access(Node* n, uint opcode, Unique if (adr_type == nullptr) { return; // skip dead nodes } - if (adr_type->isa_oopptr() + if (adr_type->is_oopptr() || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) && adr_type == TypeRawPtr::NOTNULL && is_captured_store_address(adr))) { @@ -2141,7 +2141,7 @@ void ConnectionGraph::add_to_congraph_unsafe_access(Node* n, uint opcode, Unique return; } // Stored value escapes in unsafe access. - if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) { + if ((opcode == Op_StoreP) && adr_type->is_rawptr()) { delayed_worklist->push(n); // Process unsafe access later. return; } @@ -2164,7 +2164,7 @@ bool ConnectionGraph::add_final_edges_unsafe_access(Node* n, uint opcode) { } #endif - if (adr_type->isa_oopptr() + if (adr_type->is_oopptr() || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) && adr_type == TypeRawPtr::NOTNULL && is_captured_store_address(adr))) { @@ -2177,7 +2177,7 @@ bool ConnectionGraph::add_final_edges_unsafe_access(Node* n, uint opcode) { assert(ptn != nullptr, "node should be registered"); add_edge(adr_ptn, ptn); return true; - } else if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) { + } else if ((opcode == Op_StoreP) && adr_type->is_rawptr()) { // Stored value escapes in unsafe access. Node* val = n->in(MemNode::ValueIn); PointsToNode* ptn = ptnode_adr(val->_idx); @@ -2334,7 +2334,7 @@ bool ConnectionGraph::returns_an_argument(const CallNode* call) { const TypeTuple* d = call->tf()->domain_sig(); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* t = d->field_at(i); - if (t->isa_ptr() != nullptr && + if (t->is_ptr() && call_analyzer->is_arg_returned(i - TypeFunc::Parms)) { return true; } @@ -2350,7 +2350,7 @@ bool ConnectionGraph::has_incompatible_argument_return(const CallNode* call) { int arg_num = 0; for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* t = d->field_at(i); - if (t->isa_ptr() != nullptr && + if (t->is_ptr() && call_analyzer->is_arg_returned(i - TypeFunc::Parms)) { const bool scalarized_arg = meth->is_scalarized_arg(arg_num); if (scalarized_arg && !compatible_return(call->as_CallJava(), i)) { @@ -2379,7 +2379,7 @@ void ConnectionGraph::add_call_node(CallNode* call) { bool scalar_replaceable = true; NOT_PRODUCT(const char* nsr_reason = ""); if (call->is_AllocateArray()) { - if (!kt->isa_aryklassptr()) { // StressReflectiveCode + if (!kt->is_aryklassptr()) { // StressReflectiveCode es = PointsToNode::GlobalEscape; } else { int length = call->in(AllocateNode::ALength)->find_int_con(-1); @@ -2394,10 +2394,10 @@ void ConnectionGraph::add_call_node(CallNode* call) { } } } else { // Allocate instance - if (!kt->isa_instklassptr()) { // StressReflectiveCode + if (!kt->is_instklassptr()) { // StressReflectiveCode es = PointsToNode::GlobalEscape; } else { - const TypeInstKlassPtr* ikt = kt->is_instklassptr(); + const TypeInstKlassPtr* ikt = kt->as_instklassptr(); ciInstanceKlass* ik = ikt->klass_is_exact() ? ikt->exact_klass()->as_instance_klass() : ikt->instance_klass(); if (ik->is_subclass_of(_compile->env()->Thread_klass()) || ik->is_subclass_of(_compile->env()->Reference_klass()) || @@ -2504,7 +2504,7 @@ void ConnectionGraph::add_call_node(CallNode* call) { // Check that the return type is compatible with the type of the argument being returned i.e. that there's no cast that // fails in the method bool ConnectionGraph::compatible_return(CallJavaNode* call, uint k) { - return call->tf()->domain_sig()->field_at(k)->is_instptr()->instance_klass() == call->tf()->range_sig()->field_at(TypeFunc::Parms)->is_instptr()->instance_klass(); + return call->tf()->domain_sig()->field_at(k)->as_instptr()->instance_klass() == call->tf()->range_sig()->field_at(TypeFunc::Parms)->as_instptr()->instance_klass(); } void ConnectionGraph::process_call_arguments(CallNode *call) { @@ -2539,7 +2539,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { continue; } const Type *aat = _igvn->type(arg); - if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) { + if (arg->is_top() || !at->is_ptr() || !aat->is_ptr()) { continue; } if (arg->is_AddP()) { @@ -2558,13 +2558,13 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { PointsToNode::EscapeState arg_esc = arg_ptn->escape_state(); if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) { assert(aat == Type::TOP || aat == TypePtr::NULL_PTR || - aat->isa_ptr() != nullptr, "expecting an Ptr"); - bool arg_has_oops = aat->isa_oopptr() && - (aat->isa_instptr() || - (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)) || - (aat->isa_aryptr() && aat->isa_aryptr()->elem() != nullptr && - aat->isa_aryptr()->is_flat() && - aat->isa_aryptr()->elem()->value_klass()->contains_oops())); + aat->is_ptr(), "expecting an Ptr"); + bool arg_has_oops = aat->is_oopptr() && + (aat->is_instptr() || + (aat->is_aryptr() && (aat->as_aryptr()->elem() == Type::BOTTOM || aat->as_aryptr()->elem()->make_oopptr() != nullptr)) || + (aat->is_aryptr() && aat->as_aryptr()->elem() != nullptr && + aat->as_aryptr()->is_flat() && + aat->as_aryptr()->elem()->value_klass()->contains_oops())); if (i == TypeFunc::Parms) { src_has_oops = arg_has_oops; } @@ -2708,12 +2708,12 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1) == nullptr || _igvn->type(call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1)) == at, "scalarized return and scalarized argument should match"); - if (at->isa_ptr() != nullptr && call_analyzer->is_arg_returned(jvms_slot) && ret_arg) { + if (at->is_ptr() && call_analyzer->is_arg_returned(jvms_slot) && ret_arg) { // The call returns arguments. if (scalarized_arg) { ProjNode* res_proj = call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1); if (res_proj != nullptr) { - assert(_igvn->type(res_proj)->isa_ptr(), "scalarized return and scalarized argument should match"); + assert(_igvn->type(res_proj)->is_ptr(), "scalarized return and scalarized argument should match"); if (res_proj->_con != TypeFunc::Parms) { // add an edge between the result projection for a field and the argument projection for the same argument field PointsToNode* proj_ptn = ptnode_adr(res_proj->_idx); @@ -2729,7 +2729,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { add_edge(call_ptn, arg_ptn); } } - if (at->isa_oopptr() != nullptr && + if (at->is_oopptr() && arg_ptn->escape_state() < PointsToNode::GlobalEscape) { if (scalarized_arg && !call_analyzer->is_arg_local(jvms_slot)) { // If the argument is a field of a scalarized value object, the @@ -2771,7 +2771,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { const TypeTuple* d = call->tf()->domain_cc(); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); - if (at->isa_oopptr() != nullptr) { + if (at->is_oopptr()) { Node* arg = call->in(i); if (arg->is_AddP()) { arg = get_addp_base(arg); @@ -3264,12 +3264,12 @@ int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* pha } else { // Check only oop fields. const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type(); - if (adr_type->isa_rawptr()) { + if (adr_type->is_rawptr()) { #ifdef ASSERT // Raw pointers are used for initializing stores so skip it // since it should be recorded already Node* base = get_addp_base(field->ideal_node()); - assert(adr_type->isa_rawptr() && is_captured_store_address(field->ideal_node()), "unexpected pointer type"); + assert(adr_type->is_rawptr() && is_captured_store_address(field->ideal_node()), "unexpected pointer type"); #endif continue; } @@ -3455,8 +3455,8 @@ void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj, Uniq assert(n->is_AddP(), "expect an address computation"); if (n->in(AddPNode::Base)->is_top() && n->in(AddPNode::Address)->Opcode() == Op_CheckCastPP) { - assert(n->in(AddPNode::Address)->bottom_type()->isa_rawptr(), "raw address so raw cast expected"); - assert(_igvn->type(n->in(AddPNode::Address)->in(1))->isa_oopptr(), "cast pattern at unsafe access expected"); + assert(n->in(AddPNode::Address)->bottom_type()->is_rawptr(), "raw address so raw cast expected"); + assert(_igvn->type(n->in(AddPNode::Address)->in(1))->is_oopptr(), "cast pattern at unsafe access expected"); set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used as base of mixed unsafe access")); return; } @@ -3934,21 +3934,21 @@ bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) { return true; } const Type* adr_type = n->as_AddP()->bottom_type(); - int field_offset = adr_type->isa_aryptr() ? adr_type->isa_aryptr()->field_offset().get() : Type::OffsetBot; + int field_offset = adr_type->is_aryptr() ? adr_type->as_aryptr()->field_offset().get() : Type::OffsetBot; BasicType bt = T_INT; if (offset == Type::OffsetBot && field_offset == Type::OffsetBot) { // Check only oop fields. - if (!adr_type->isa_aryptr() || - adr_type->isa_aryptr()->elem() == Type::BOTTOM || - adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) { + if (!adr_type->is_aryptr() || + adr_type->as_aryptr()->elem() == Type::BOTTOM || + adr_type->as_aryptr()->elem()->make_oopptr() != nullptr) { // OffsetBot is used to reference array's element. Ignore first AddP. if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) { bt = T_OBJECT; } } } else if (offset != oopDesc::klass_offset_in_bytes()) { - if (adr_type->isa_instptr()) { - ciField* field = _compile->alias_type(adr_type->is_ptr())->field(); + if (adr_type->is_instptr()) { + ciField* field = _compile->alias_type(adr_type->as_ptr())->field(); if (field != nullptr) { bt = field->layout_type(); } else { @@ -3958,14 +3958,14 @@ bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) { (*unsafe) = true; } } - } else if (adr_type->isa_aryptr()) { + } else if (adr_type->is_aryptr()) { if (offset == arrayOopDesc::length_offset_in_bytes()) { // Ignore array length load. } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) { // Ignore first AddP. } else { - const Type* elemtype = adr_type->is_aryptr()->elem(); - if (adr_type->is_aryptr()->is_flat() && field_offset != Type::OffsetBot) { + const Type* elemtype = adr_type->as_aryptr()->elem(); + if (adr_type->as_aryptr()->is_flat() && field_offset != Type::OffsetBot) { ciValueKlass* vk = elemtype->value_klass(); field_offset += vk->payload_offset(); ciField* field = vk->get_field_by_offset(field_offset, false); @@ -3979,7 +3979,7 @@ bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) { bt = elemtype->array_element_basic_type(); } } - } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) { + } else if (adr_type->is_rawptr() || adr_type->is_klassptr()) { // Allocation initialization, ThreadLocal field access, unsafe access if (has_oop_node_outs(n)) { bt = T_OBJECT; @@ -4150,7 +4150,7 @@ bool FieldNode::has_base(JavaObjectNode* jobj) const { bool ConnectionGraph::is_captured_store_address(Node* addp) { // Handle simple case first. - assert(_igvn->type(addp)->isa_oopptr() == nullptr, "should be raw access"); + assert(!_igvn->type(addp)->is_oopptr(), "should be raw access"); if (addp->in(AddPNode::Address)->is_Proj() && addp->in(AddPNode::Address)->in(0)->is_Allocate()) { return true; } else if (addp->in(AddPNode::Address)->is_Phi()) { @@ -4170,7 +4170,7 @@ bool ConnectionGraph::is_captured_store_address(Node* addp) { int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) { const Type *adr_type = phase->type(adr); - if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) { + if (adr->is_AddP() && !adr_type->is_oopptr() && is_captured_store_address(adr)) { // We are computing a raw address for a store captured by an Initialize // compute an appropriate address type. AddP cases #3 and #5 (see below). int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot); @@ -4179,7 +4179,7 @@ int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) { "offset must be a constant or it is initialization of array"); return offs; } - return adr_type->is_ptr()->flat_offset(); + return adr_type->as_ptr()->flat_offset(); } Node* ConnectionGraph::get_addp_base(Node *addp) { @@ -4275,8 +4275,8 @@ Node* ConnectionGraph::get_addp_base(Node *addp) { base = base->in(AddPNode::Address); } if (base->Opcode() == Op_CheckCastPP && - base->bottom_type()->isa_rawptr() && - _igvn->type(base->in(1))->isa_oopptr()) { + base->bottom_type()->is_rawptr() && + _igvn->type(base->in(1))->is_oopptr()) { base = base->in(1); // Case #9 } else { // Case #3, #6, and #10 @@ -4285,8 +4285,8 @@ Node* ConnectionGraph::get_addp_base(Node *addp) { assert(opcode == Op_ConP || opcode == Op_ThreadLocal || opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() || (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)|| - (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) || - (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) || + (uncast_base->is_Mem() && uncast_base->bottom_type()->is_rawptr()) || + (uncast_base->is_Mem() && uncast_base->bottom_type()->is_klassptr()) || is_captured_store_address(addp) || is_load_array_klass_related(uncast_base), "sanity"); } @@ -4363,13 +4363,13 @@ bool ConnectionGraph::split_AddP(Node *addp, Node *base) { assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation"); intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot); assert(offs != Type::OffsetBot, "offset must be a constant"); - if (base_t->isa_aryptr() != nullptr) { + if (base_t->is_aryptr()) { // In the case of a flat value type array, each field has its // own slice so we need to extract the field being accessed from // the address computation - t = base_t->isa_aryptr()->add_field_offset_and_offset(offs)->is_oopptr(); + t = base_t->as_aryptr()->add_field_offset_and_offset(offs)->as_oopptr(); } else { - t = base_t->add_offset(offs)->is_oopptr(); + t = base_t->add_offset(offs)->as_oopptr(); } } int inst_id = base_t->instance_id(); @@ -4397,12 +4397,12 @@ bool ConnectionGraph::split_AddP(Node *addp, Node *base) { return false; // bail out } const TypePtr* tinst = base_t->add_offset(t->offset()); - if (tinst->isa_aryptr() && t->isa_aryptr()) { + if (tinst->is_aryptr() && t->is_aryptr()) { // In the case of a flat value type array, each field has its // own slice so we need to keep track of the field being accessed. - tinst = tinst->is_aryptr()->with_field_offset(t->is_aryptr()->field_offset().get()); + tinst = tinst->as_aryptr()->with_field_offset(t->as_aryptr()->field_offset().get()); // Keep array properties (not flat/null-free) - tinst = tinst->is_aryptr()->update_properties(t->is_aryptr()); + tinst = tinst->as_aryptr()->update_properties(t->as_aryptr()); if (tinst == nullptr) { return false; // Skip dead path with inconsistent properties } @@ -4412,7 +4412,7 @@ bool ConnectionGraph::split_AddP(Node *addp, Node *base) { // for the instance type. Note: C++ will not remove it since the call // has side effect. int alias_idx = _compile->get_alias_index(tinst); - if (igvn->type(addp)->isa_oopptr()) { + if (igvn->type(addp)->is_oopptr()) { igvn->set_type(addp, tinst); } else { // Captured stores should remain raw memory stores @@ -4531,15 +4531,15 @@ PhiNode* ConnectionGraph::split_memory_phi(PhiNode* orig_phi, int alias_idx, Uni bool finished = false; while(!finished) { while (idx < phi->req()) { - Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, rec_depth + 1); - if (mem != nullptr && mem->is_Phi()) { - PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created); + Node* mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, rec_depth + 1); + if (PhiNode* mem_phi = Node::isa(mem); mem_phi != nullptr) { + PhiNode* newphi = create_split_phi(mem_phi, alias_idx, orig_phi_worklist, new_phi_created); if (new_phi_created) { - // found an phi for which we created a new split, push current one on worklist and begin + // found a phi for which we created a new split, push current one on worklist and begin // processing new one phi_list.push(phi); cur_input.push(idx); - phi = mem->as_Phi(); + phi = mem_phi; result = newphi; idx = 1; continue; @@ -4585,8 +4585,8 @@ Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, // means an array I have not precisely typed yet. Do not do any // alias stuff with it any time soon. if (toop->base() != Type::AnyPtr && - !(toop->isa_instptr() && - toop->is_instptr()->instance_klass()->is_java_lang_Object() && + !(toop->is_instptr() && + toop->as_instptr()->instance_klass()->is_java_lang_Object() && toop->offset() == Type::OffsetBot)) { mem = mmem->memory_at(alias_idx); // Update input if it is progress over what we have now @@ -4662,7 +4662,7 @@ void ConnectionGraph::move_inst_mem(Node* n, Unique_Node_List& orig_phi "Following memory nodes should have new memory input or be on the same memory slice"); } else if (use->is_Phi()) { // Phi nodes should be split and moved already. - tp = use->as_Phi()->in_adr_type()->isa_ptr(); + tp = use->as_Phi()->in_adr_type(); assert(tp != nullptr, "ptr type"); int idx = C->get_alias_index(tp); assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice"); @@ -4698,8 +4698,8 @@ bool ConnectionGraph::flat_access_aliases_with(Node* flat_access, const TypeOopP } if (ptn->is_JavaObject()) { Node* jobj_base = get_map(ptn->idx()); - if (jobj_base == nullptr || !_igvn->type(jobj_base)->is_oopptr()->same_instance_as(toop)) { - assert(!_igvn->type(base)->is_oopptr()->same_instance_as(toop), "should not alias"); + if (jobj_base == nullptr || !_igvn->type(jobj_base)->as_oopptr()->same_instance_as(toop)) { + assert(!_igvn->type(base)->as_oopptr()->same_instance_as(toop), "should not alias"); return false; } return true; @@ -4708,12 +4708,12 @@ bool ConnectionGraph::flat_access_aliases_with(Node* flat_access, const TypeOopP for (EdgeIterator i(ptn); i.has_next(); i.next()) { if (i.get()->is_JavaObject()) { Node* jobj_base = get_map(i.get()->idx()); - if (jobj_base != nullptr && _igvn->type(jobj_base)->is_oopptr()->same_instance_as(toop)) { + if (jobj_base != nullptr && _igvn->type(jobj_base)->as_oopptr()->same_instance_as(toop)) { return true; } } } - assert(!_igvn->type(base)->is_oopptr()->same_instance_as(toop), "should not alias"); + assert(!_igvn->type(base)->as_oopptr()->same_instance_as(toop), "should not alias"); return false; } @@ -4742,13 +4742,13 @@ Node* ConnectionGraph::find_inst_mem(Node* orig_mem, int alias_idx, Unique_Node_ if (at == Type::TOP) { break; // Dead } - assert (at->isa_ptr() != nullptr, "pointer type required."); - int idx = C->get_alias_index(at->is_ptr()); + assert(at->is_ptr(), "pointer type required."); + int idx = C->get_alias_index(at->as_ptr()); if (idx == alias_idx) { break; // Found } - if (!is_instance && (at->isa_oopptr() == nullptr || - !at->is_oopptr()->is_known_instance())) { + if (!is_instance && (!at->is_oopptr() || + !at->as_oopptr()->is_known_instance())) { break; // Do not skip store to general memory slice. } result = result->in(MemNode::Memory); @@ -4852,8 +4852,8 @@ Node* ConnectionGraph::find_inst_mem(Node* orig_mem, int alias_idx, Unique_Node_ } const Type *at = igvn->type(adr); if (at != Type::TOP) { - assert(at->isa_ptr() != nullptr, "pointer type required."); - int idx = C->get_alias_index(at->is_ptr()); + assert(at->is_ptr(), "pointer type required."); + int idx = C->get_alias_index(at->as_ptr()); if (idx == alias_idx) { // Assert in debug mode assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field"); @@ -4865,8 +4865,8 @@ Node* ConnectionGraph::find_inst_mem(Node* orig_mem, int alias_idx, Unique_Node_ Node* adr = result->in(3); // Memory edge corresponds to destination array const Type *at = igvn->type(adr); if (at != Type::TOP) { - assert(at->isa_ptr() != nullptr, "pointer type required."); - int idx = C->get_alias_index(at->is_ptr()); + assert(at->is_ptr(), "pointer type required."); + int idx = C->get_alias_index(at->as_ptr()); if (idx == alias_idx) { // Assert in debug mode assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field"); @@ -5165,17 +5165,17 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, // correct memory state otherwise. _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes())); _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes())); - if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) { + if (alloc->is_Allocate() && (t->is_instptr() || t->is_aryptr())) { // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type InitializeNode* init = alloc->as_Allocate()->initialization(); assert(init != nullptr, "can't find Initialization node for this Allocate node"); auto process_narrow_proj = [&](NarrowMemProjNode* proj) { const TypePtr* adr_type = proj->out_adr_type(); const TypePtr* new_adr_type = tinst->with_offset(adr_type->offset()); - if (adr_type->isa_aryptr()) { + if (adr_type->is_aryptr()) { // In the case of a flat value type array, each field has its own slice so we need a // NarrowMemProj for each field of the flat array elements - new_adr_type = new_adr_type->is_aryptr()->with_field_offset(adr_type->is_aryptr()->field_offset().get()); + new_adr_type = new_adr_type->as_aryptr()->with_field_offset(adr_type->as_aryptr()->field_offset().get()); } if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) { // Do NOT remove the next line: ensure a new alias index is allocated for the instance type. @@ -5288,20 +5288,20 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, const Type *tn_type = igvn->type(tn); const TypeOopPtr *tn_t; - if (tn_type->isa_narrowoop()) { + if (tn_type->is_narrowoop()) { tn_t = tn_type->make_ptr()->isa_oopptr(); } else { tn_t = tn_type->isa_oopptr(); } if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) { - if (tn_t->isa_aryptr()) { + if (tn_t->is_aryptr()) { // Keep array properties (not flat/null-free) - tinst = tinst->is_aryptr()->update_properties(tn_t->is_aryptr()); + tinst = tinst->as_aryptr()->update_properties(tn_t->as_aryptr()); if (tinst == nullptr) { continue; // Skip dead path with inconsistent properties } } - if (tn_type->isa_narrowoop()) { + if (tn_type->is_narrowoop()) { tn_type = tinst->make_narrowoop(); } else { tn_type = tinst; @@ -5461,7 +5461,7 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, n->Opcode() == Op_EncodeISOArray) { // get the memory projection n = n->find_out_with(Op_SCMemProj); - assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required"); + assert(Node::is_exact(n), "memory projection required"); } else if (n->is_CallLeaf() && n->as_CallLeaf()->_name != nullptr && strcmp(n->as_CallLeaf()->_name, "store_unknown_value") == 0) { n = n->as_CallLeaf()->proj_out(TypeFunc::Memory); @@ -5479,8 +5479,8 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, if (addr_t == Type::TOP) { continue; } - assert (addr_t->isa_ptr() != nullptr, "pointer type required."); - int alias_idx = _compile->get_alias_index(addr_t->is_ptr()); + assert(addr_t->is_ptr(), "pointer type required."); + int alias_idx = _compile->get_alias_index(addr_t->as_ptr()); assert ((uint)alias_idx < new_index_end, "wrong alias index"); Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis); if (_compile->failing()) { @@ -5496,7 +5496,7 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, } else if (n->is_LoadStore()) { // get the memory projection n = n->find_out_with(Op_SCMemProj); - assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required"); + assert(Node::is_exact(n), "memory projection required"); } } // push user on appropriate worklist @@ -5569,8 +5569,8 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, while (mem->is_Mem()) { const Type* at = igvn->type(mem->in(MemNode::Address)); if (at != Type::TOP) { - assert (at->isa_ptr() != nullptr, "pointer type required."); - uint idx = (uint)_compile->get_alias_index(at->is_ptr()); + assert(at->is_ptr(), "pointer type required."); + uint idx = (uint)_compile->get_alias_index(at->as_ptr()); if (idx == i) { if (cur == nullptr) { cur = mem; @@ -5601,7 +5601,7 @@ void ConnectionGraph::split_unique_types(GrowableArray& alloc_worklist, } // Find the rest of instances values for (uint ni = new_index_start; ni < new_index_end; ni++) { - const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr(); + const TypeOopPtr* tinst = _compile->get_adr_type(ni)->as_oopptr(); Node* result = step_through_mergemem(nmm, ni, tinst); if (result == nmm->base_memory()) { // Didn't find instance memory, search through general slice recursively. diff --git a/src/hotspot/share/opto/gcm.cpp b/src/hotspot/share/opto/gcm.cpp index 3d97d66d63eb..59cc2a0cdb86 100644 --- a/src/hotspot/share/opto/gcm.cpp +++ b/src/hotspot/share/opto/gcm.cpp @@ -1453,7 +1453,7 @@ Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { // Do not hoist (to cover latency) instructions which target a // single register. Hoisting stretches the live range of the // single register and may force spilling. - MachNode* mach = self->is_Mach() ? self->as_Mach() : nullptr; + MachNode* mach = self->isa_Mach(); if (mach != nullptr && mach->out_RegMask().is_bound1() && !mach->out_RegMask().is_empty()) { in_latency = true; } @@ -1588,7 +1588,7 @@ void PhaseCFG::schedule_late(VectorSet& visited, Node_Stack& stack) { } #endif - MachNode* mach = self->is_Mach() ? self->as_Mach() : nullptr; + MachNode* mach = self->isa_Mach(); if (mach) { switch (mach->ideal_Opcode()) { case Op_CreateEx: @@ -1674,7 +1674,7 @@ void PhaseCFG::schedule_late(VectorSet& visited, Node_Stack& stack) { // Place temps in the block of their use. This isn't a // requirement for correctness but it reduces useless // interference between temps and other nodes. - if (mach != nullptr && mach->is_MachTemp()) { + if (Node::is(mach)) { map_node_to_block(self, LCA); LCA->add_inst(self); continue; diff --git a/src/hotspot/share/opto/generateOptoStub.cpp b/src/hotspot/share/opto/generateOptoStub.cpp index 8a420bc1d855..122b530615a5 100644 --- a/src/hotspot/share/opto/generateOptoStub.cpp +++ b/src/hotspot/share/opto/generateOptoStub.cpp @@ -115,7 +115,7 @@ void GraphKit::gen_stub(address C_function, // extra argument. Not all calls need it, but it is cheap to add here. for (uint pcnt = cnt; pcnt < parm_cnt; pcnt++, cnt++) { const Type *f = jdomain->field_at(pcnt); - if (CCallingConventionRequiresIntsAsLongs && f->isa_int()) { + if (CCallingConventionRequiresIntsAsLongs && f->is_int()) { fields[cnt++] = TypeLong::LONG; fields[cnt] = Type::HALF; // Must add an additional half for a long. } else { @@ -138,13 +138,13 @@ void GraphKit::gen_stub(address C_function, // Make a private copy of jrange->fields(); const Type **rfields = TypeTuple::fields(jrange->cnt() - TypeFunc::Parms); // Fixup oop returns - int retval_ptr = retval->isa_oop_ptr(); + int retval_ptr = retval->is_oopptr(); if (retval_ptr) { assert( pass_tls, "Oop must be returned thru TLS" ); // Fancy-jumps return address; others return void rfields[TypeFunc::Parms] = is_fancy_jump ? TypeRawPtr::BOTTOM : Type::TOP; - } else if (retval->isa_int()) { // Returning any integer subtype? + } else if (retval->is_int()) { // Returning any integer subtype? // "Fatten" byte, char & short return types to 'int' to show that // the native C code can return values with junk high order bits. // We'll sign-extend it below later. @@ -179,7 +179,7 @@ void GraphKit::gen_stub(address C_function, call->set_req(TypeFunc::ReturnAdr, top()); for (; i < parm_cnt; i++) { // Regular input arguments. const Type *f = jdomain->field_at(i); - if (CCallingConventionRequiresIntsAsLongs && f->isa_int()) { + if (CCallingConventionRequiresIntsAsLongs && f->is_int()) { call->init_req(cnt++, _gvn.transform(new ConvI2LNode(map()->in(i)))); call->init_req(cnt++, top()); } else { diff --git a/src/hotspot/share/opto/graphKit.cpp b/src/hotspot/share/opto/graphKit.cpp index f4dbf16428b6..c532adae0dfc 100644 --- a/src/hotspot/share/opto/graphKit.cpp +++ b/src/hotspot/share/opto/graphKit.cpp @@ -184,7 +184,7 @@ static bool is_hidden_merge(Node* reg) { reg = reg->in(0); if (reg == nullptr) return false; } - return reg->is_Region() && reg->in(0) != nullptr && reg->in(0)->is_Root(); + return reg->is_Region() && Node::is(reg->in(0)); } void GraphKit::verify_map() const { @@ -302,7 +302,7 @@ void GraphKit::add_exception_state(SafePointNode* ex_map) { // No action needed. return; } - assert(ex_type->isa_instptr(), "exception must be an instance"); + assert(ex_type->is_instptr(), "exception must be an instance"); for (SafePointNode* e2 = _exceptions; e2 != nullptr; e2 = e2->next_exception()) { const Type* ex_type2 = _gvn.type(saved_ex_oop(e2)); // We check sp also because call bytecodes can generate exceptions @@ -1275,8 +1275,8 @@ Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) { // problem. if (offset->is_Con()) { const Type* t = offset->bottom_type(); - bool is_zero_int = t->isa_int() && t->is_int()->get_con() == 0; - bool is_zero_long = t->isa_long() && t->is_long()->get_con() == 0; + bool is_zero_int = t->is_int() && t->as_int()->get_con() == 0; + bool is_zero_long = t->is_long() && t->as_long()->get_con() == 0; assert(!is_zero_int && !is_zero_long, "Unexpected zero offset - should have matched MakeConX(0)"); } @@ -1330,7 +1330,7 @@ Node* GraphKit::load_array_length(Node* array) { Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes()); alen = _gvn.transform( new LoadRangeNode(nullptr, immutable_memory(), r_adr, TypeInt::POS)); } else { - alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false); + alen = array_ideal_length(alloc, _gvn.type(array)->as_oopptr(), false); } return alen; } @@ -1722,19 +1722,24 @@ Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, return ld; } -Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt, +Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt, MemNode::MemOrd mo) { + return store_to_memory(ctl, adr, val, bt, mo, false, false, false, false, false, 0); +} + +Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt, MemNode::MemOrd mo, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, + bool store_special, int barrier_data) { int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr()); assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" ); const TypePtr* adr_type = nullptr; DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx)); Node *mem = memory(adr_idx); - Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access); + Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access, store_special); if (unaligned) { st->as_Store()->set_unaligned_access(); } @@ -1755,6 +1760,16 @@ Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt, return st; } +Node* GraphKit::access_store_at(Node* obj, + Node* adr, + const TypePtr* adr_type, + Node* val, + const Type* val_type, + BasicType bt, + DecoratorSet decorators) { + return access_store_at(obj, adr, adr_type, val, val_type, bt, decorators, true, nullptr); +} + Node* GraphKit::access_store_at(Node* obj, Node* adr, const TypePtr* adr_type, @@ -1832,7 +1847,7 @@ Node* GraphKit::access_load(Node* adr, // actual address to load val at } SavedState old_state(this); - C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr()); + C2AccessValuePtr addr(adr, adr->bottom_type()->as_ptr()); C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr); Node* load; if (access.is_raw()) { @@ -1929,7 +1944,7 @@ void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) { //-------------------------array_element_address------------------------- Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt, const TypeInt* sizetype, Node* ctrl) { - const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr(); + const TypeAryPtr* arytype = _gvn.type(ary)->as_aryptr(); uint shift; uint header; if (arytype->is_flat() && arytype->klass_is_exact()) { @@ -1989,7 +2004,7 @@ Node* GraphKit::cast_to_flat_array(Node* array, ciObjArrayKlass* array_klass, bo } assert(array_klass->element_klass()->is_value_klass(), "Must be"); - const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr(); + const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->as_aryptr(); if (exact) { assert(arytype->klass_is_exact(), "inconsistency"); assert(arytype->is_flat(), "inconsistency"); @@ -2543,8 +2558,7 @@ Node* GraphKit::uncommon_trap(int trap_request, // Make sure any guarding test views this path as very unlikely Node *i0 = control()->in(0); - if (i0 != nullptr && i0->is_If()) { // Found a guarding if test? - IfNode *iff = i0->as_If(); + if (IfNode* iff = Node::isa(i0); iff != nullptr) { // Found a guarding if test? float f = iff->_prob; // Get prob if (control()->Opcode() == Op_IfTrue) { if (f > PROB_UNLIKELY_MAG(4)) @@ -2599,9 +2613,9 @@ Node* GraphKit::just_allocated_object(Node* current_control) { // Object:: is invoked after allocation, most of invoke nodes // will be reduced, but a region node is kept in parse time, we check // the pattern and skip the region node if it degraded to a copy. - if (ctrl != nullptr && ctrl->is_Region() && ctrl->req() == 2 && - ctrl->as_Region()->is_copy()) { - ctrl = ctrl->as_Region()->is_copy(); + if (RegionNode* region = Node::isa(ctrl); + region != nullptr && ctrl->req() == 2 && region->is_copy()) { + ctrl = region->is_copy(); } if (C->recent_alloc_ctl() == ctrl) { return C->recent_alloc_obj(); @@ -2635,7 +2649,7 @@ Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, Prof assert(ptr_kind != ProfileAlwaysNull, "impossible here"); const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL; // record the new speculative type's depth - speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr(); + speculative = xtype->cast_to_ptr_type(ptr->ptr())->as_ptr(); speculative = speculative->with_inline_depth(jvms()->depth()); } else if (current_type->would_improve_ptr(ptr_kind)) { // Profiling report that null was never seen so we can change the @@ -2646,7 +2660,7 @@ Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, Prof assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement"); const TypePtr* ptr = TypePtr::NOTNULL; if (speculative != nullptr) { - speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr(); + speculative = speculative->cast_to_ptr_type(ptr->ptr())->as_ptr(); } else { speculative = ptr; } @@ -2758,7 +2772,7 @@ void GraphKit::record_profiled_parameters_for_speculation() { return; } for (int i = 0, j = 0; i < method()->arg_size() ; i++) { - if (_gvn.type(local(i))->isa_oopptr()) { + if (_gvn.type(local(i))->is_oopptr()) { ProfilePtrKind ptr_kind = ProfileMaybeNull; ciKlass* better_type = nullptr; if (method()->parameter_profiled_type(j, better_type, ptr_kind)) { @@ -2903,7 +2917,7 @@ Node* GraphKit::make_runtime_call(int flags, } else if (flags & RC_NO_FP) { call = new CallLeafNoFPNode(call_type, call_addr, call_name, out_adr_type, in_adr_type); } else if (flags & RC_VECTOR){ - uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte; + uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->as_vect()->length_in_bytes() * BitsPerByte; call = new CallLeafVectorNode(call_type, call_addr, call_name, out_adr_type, in_adr_type, num_bits); } else if (flags & RC_PURE) { assert(out_adr_type == nullptr, "pure call does not touch memory"); @@ -3078,12 +3092,12 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No return C->top(); } - const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->is_klassptr(); + const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->as_klassptr(); // For a direct pointer comparison, we need the refined array klass pointer Node* vm_superklass = superklass; - if (klass_ptr_type->isa_aryklassptr() && klass_ptr_type->klass_is_exact()) { - assert(!klass_ptr_type->is_aryklassptr()->is_refined_type(), "Unexpected refined array klass pointer"); - vm_superklass = gvn.makecon(klass_ptr_type->is_aryklassptr()->cast_to_refined_array_klass_ptr()); + if (klass_ptr_type->is_aryklassptr() && klass_ptr_type->klass_is_exact()) { + assert(!klass_ptr_type->as_aryklassptr()->is_refined_type(), "Unexpected refined array klass pointer"); + vm_superklass = gvn.makecon(klass_ptr_type->as_aryklassptr()->cast_to_refined_array_klass_ptr()); } // Fast check for identical types, perhaps identical constants. @@ -3093,8 +3107,8 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No return C->top(); // false path is dead; no test needed. if (gvn.type(superklass)->singleton()) { - const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr(); - const TypeKlassPtr* subk = gvn.type(subklass)->is_klassptr(); + const TypeKlassPtr* superk = gvn.type(superklass)->as_klassptr(); + const TypeKlassPtr* subk = gvn.type(subklass)->as_klassptr(); // In the common case of an exact superklass, try to fold up the // test before generating code. You may ask, why not just generate @@ -3141,7 +3155,7 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No // First load the super-klass's check-offset Node* p1 = gvn.transform(AddPNode::make_off_heap(superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset())))); Node* m = C->immutable_memory(); - Node* chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered)); + Node* chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->as_ptr(), TypeInt::INT, MemNode::unordered)); int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset()); const TypeInt* chk_off_t = chk_off->Value(&gvn)->isa_int(); int chk_off_con = (chk_off_t != nullptr && chk_off_t->is_con()) ? chk_off_t->get_con() : cacheoff_con; @@ -3168,9 +3182,9 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No // - it's a cache so, worse case, not reading the latest value // wouldn't cause incorrect execution if (might_be_cache && mem != nullptr) { - kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem; + kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->as_ptr())) : mem; } - Node* nkls = gvn.transform(LoadKlassNode::make(gvn, kmem, p2, gvn.type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL)); + Node* nkls = gvn.transform(LoadKlassNode::make(gvn, kmem, p2, gvn.type(p2)->as_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL)); // Compile speed common case: ARE a subtype and we canNOT fail if (superklass == nkls) { @@ -3193,7 +3207,7 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No total_prob += prob; } if (total_prob * 100. >= TypeProfileSubTypeCheckCommonThreshold) { - const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr(); + const TypeKlassPtr* superk = gvn.type(superklass)->as_klassptr(); for (int i = 0; profile.has_receiver(i); ++i) { ciKlass* klass = profile.receiver(i); const TypeKlassPtr* klass_t = TypeKlassPtr::make(klass); @@ -3201,9 +3215,9 @@ Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, No if (result != Compile::SSC_always_true && result != Compile::SSC_always_false) { continue; } - if (klass_t->isa_aryklassptr()) { + if (klass_t->is_aryklassptr()) { // For a direct pointer comparison, we need the refined array klass pointer - klass_t = klass_t->is_aryklassptr()->cast_to_refined_array_klass_ptr(); + klass_t = klass_t->as_aryklassptr()->cast_to_refined_array_klass_ptr(); } float prob = profile.receiver_prob(i); ConNode* klass_node = gvn.makecon(klass_t); @@ -3306,7 +3320,7 @@ Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) { MergeMemNode* mem = merged_memory(); Node* ctrl = control(); Node* subklass = obj_or_subklass; - if (!sub_t->isa_klassptr()) { + if (!sub_t->is_klassptr()) { subklass = load_object_klass(obj_or_subklass); } @@ -3339,15 +3353,15 @@ Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass, return fail; } const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces); - if (tklass->isa_aryklassptr()) { + if (tklass->is_aryklassptr()) { // For a direct pointer comparison, we need the refined array klass pointer - tklass = tklass->is_aryklassptr()->cast_to_refined_array_klass_ptr(); + tklass = tklass->as_aryklassptr()->cast_to_refined_array_klass_ptr(); } Node* recv_klass = load_object_klass(receiver); fail = type_check(recv_klass, tklass, prob); if (!stopped()) { - const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr(); + const TypeOopPtr* receiver_type = _gvn.type(receiver)->as_oopptr(); const TypeOopPtr* recv_xtype = tklass->as_exact_instance_type(); assert(recv_xtype->klass_is_exact(), ""); @@ -3442,7 +3456,7 @@ void GraphKit::guard_klass_is_initialized(Node* klass) { int init_state_off = in_bytes(InstanceKlass::init_state_offset()); Node* adr = basic_plus_adr(top(), klass, init_state_off); Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr, - adr->bottom_type()->is_ptr(), TypeInt::BYTE, + adr->bottom_type()->as_ptr(), TypeInt::BYTE, T_BYTE, MemNode::acquire); init_state = _gvn.transform(init_state); @@ -3463,7 +3477,7 @@ void GraphKit::guard_klass_being_initialized(Node* klass) { int init_state_off = in_bytes(InstanceKlass::init_state_offset()); Node* adr = off_heap_plus_addr(klass, init_state_off); Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr, - adr->bottom_type()->is_ptr(), TypeInt::BYTE, + adr->bottom_type()->as_ptr(), TypeInt::BYTE, T_BYTE, MemNode::acquire); init_state = _gvn.transform(init_state); @@ -3482,7 +3496,7 @@ void GraphKit::guard_init_thread(Node* klass) { Node* adr = off_heap_plus_addr(klass, init_thread_off); Node* init_thread = LoadNode::make(_gvn, nullptr, immutable_memory(), adr, - adr->bottom_type()->is_ptr(), TypePtr::NOTNULL, + adr->bottom_type()->as_ptr(), TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered); init_thread = _gvn.transform(init_thread); @@ -3683,7 +3697,7 @@ Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replac // Do we know the type check always succeed? bool known_statically = false; if (improved_klass_ptr_type->singleton()) { - const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type(); + const TypeKlassPtr* subk = _gvn.type(obj)->as_oopptr()->as_klass_type(); if (subk != nullptr && subk->is_loaded()) { int static_res = C->static_subtype_check(improved_klass_ptr_type, subk); known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false); @@ -3691,7 +3705,7 @@ Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replac } if (!known_statically) { - const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); + const TypeOopPtr* obj_type = _gvn.type(obj)->as_oopptr(); // We may not have profiling here or it may not help us. If we // have a speculative type use it to perform an exact cast. ciKlass* spec_obj_type = obj_type->speculative_type(); @@ -3752,7 +3766,7 @@ Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node** failure_contro assert(new_cast_failure_map == nullptr || failure_control != nullptr, "failure_control must be set when new_failure_map is used"); kill_dead_locals(); // Benefit all the uncommon traps - const TypeKlassPtr* klass_ptr_type = _gvn.type(superklass)->is_klassptr(); + const TypeKlassPtr* klass_ptr_type = _gvn.type(superklass)->as_klassptr(); const Type* obj_type = _gvn.type(obj); const TypeKlassPtr* improved_klass_ptr_type = klass_ptr_type->try_improve(); @@ -3768,8 +3782,8 @@ Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node** failure_contro // for example, in some objArray manipulations, such as a[i]=a[j].) if (improved_klass_ptr_type->singleton()) { const TypeKlassPtr* kptr = nullptr; - if (obj_type->isa_oop_ptr()) { - kptr = obj_type->is_oopptr()->as_klass_type(); + if (obj_type->is_oopptr()) { + kptr = obj_type->as_oopptr()->as_klass_type(); } else if (obj->is_ValueType()) { ciValueKlass* vk = obj_type->value_klass(); kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0)); @@ -3800,7 +3814,7 @@ Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node** failure_contro obj = null_check(obj); } // It needs a null check because a null will *pass* the cast check. - if (obj_type->isa_oopptr() != nullptr && !obj_type->is_oopptr()->maybe_null()) { + if (obj_type->is_oopptr() && !obj_type->as_oopptr()->maybe_null()) { bool is_aastore = (java_bc() == Bytecodes::_aastore); Deoptimization::DeoptReason reason = is_aastore ? Deoptimization::Reason_array_check : Deoptimization::Reason_class_check; @@ -3874,7 +3888,7 @@ Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node** failure_contro // (for example obtained during profiling) to the type of the superklass and then do a // dynamic check that the type of the object is what we expect. To work correctly // for checkcast and aastore the type of superklass should be exact. - const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); + const TypeOopPtr* obj_type = _gvn.type(obj)->as_oopptr(); // We may not have profiling here or it may not help us. If we have // a speculative type use it to perform an exact cast. ciKlass* spec_obj_type = obj_type->speculative_type(); @@ -3929,11 +3943,11 @@ Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node** failure_contro // Check if obj has been loaded from an array. Keep obj unchanged for final // map replacement below. Node* array_obj = obj->uncast(); - array_obj = array_obj->isa_DecodeN() ? array_obj->in(1) : array_obj; + array_obj = array_obj->is_DecodeN() ? array_obj->in(1) : array_obj; Node* array = nullptr; - if (array_obj->isa_Load()) { + if (array_obj->is_Load()) { Node* address = array_obj->in(MemNode::Address); - if (address->isa_AddP()) { + if (address->is_AddP()) { array = address->as_AddP()->in(AddPNode::Base); } } else if (array_obj->is_Phi()) { @@ -4103,7 +4117,7 @@ Node* GraphKit::value_array_null_guard(Node* ary, Node* val, int nargs) { record_for_igvn(region); if (_gvn.type(val) == TypePtr::NULL_PTR) { // Since we were just successfully storing null, the array can't be null free. - const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr(); + const TypeAryPtr* ary_t = _gvn.type(ary)->as_aryptr(); ary_t = ary_t->cast_to_not_null_free(); Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t)); replace_in_map(ary, cast); @@ -4293,7 +4307,7 @@ Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) { } const TypeAryKlassPtr* aryklass_t = klass_t->isa_aryklassptr(); - if (aryklass_t != nullptr && aryklass_t->elem()->isa_klassptr() != nullptr && aryklass_t->is_not_flat()) { + if (aryklass_t != nullptr && aryklass_t->elem()->is_klassptr() && aryklass_t->is_not_flat()) { // If we know that the array cannot be flat, then the layout_helper value is known constant_value = Klass::array_layout_helper(T_OBJECT); return nullptr; @@ -4366,7 +4380,7 @@ Node* GraphKit::set_output_for_allocation(AllocateNode* alloc, set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(mark_idx))), mark_idx); int klass_idx = C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())); set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(klass_idx))), klass_idx); - if (oop_type->isa_aryptr()) { + if (oop_type->is_aryptr()) { // Initially all flat array accesses share a single slice // but that changes after parsing. Prepare the memory graph so // it can optimize flat array accesses properly once they @@ -4379,8 +4393,8 @@ Node* GraphKit::set_output_for_allocation(AllocateNode* alloc, C->set_flat_accesses(); } hook_memory_on_init(*this, elemidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, alias_adr_type))); - } else if (oop_type->isa_instptr()) { - ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass(); + } else if (oop_type->is_instptr()) { + ciInstanceKlass* ik = oop_type->as_instptr()->instance_klass(); for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) { ciField* field = ik->nonstatic_field_at(i); if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize) @@ -4671,7 +4685,7 @@ Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable) initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn); } - const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr(); + const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->as_klassptr(); const TypeOopPtr* ary_type = ary_klass->as_exact_instance_type(); Node* raw_init_value = nullptr; @@ -4693,8 +4707,8 @@ Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable) } Node* valid_length_test = _gvn.intcon(1); - if (ary_type->isa_aryptr()) { - jint max = ary_type->is_aryptr()->max_array_length(); + if (ary_type->is_aryptr()) { + jint max = ary_type->as_aryptr()->max_array_length(); Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max))); valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le)); } @@ -4712,9 +4726,9 @@ Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable) // (This happens via a non-constant argument to inline_native_newArray.) // In any case, the value of klass_node provides the desired array type. const TypeInt* length_type = _gvn.find_int_type(length); - if (ary_type->isa_aryptr() && length_type != nullptr) { + if (ary_type->is_aryptr() && length_type != nullptr) { // Try to get a better type than POS for the size - ary_type = ary_type->is_aryptr()->cast_to_size(length_type); + ary_type = ary_type->as_aryptr()->cast_to_size(length_type); } Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception); @@ -4743,8 +4757,8 @@ AllocateNode* AllocateNode::Ideal_allocation(Node* ptr) { // to keep more precise type from last cast. if (ptr->is_Proj()) { Node* allo = ptr->in(0); - if (allo != nullptr && allo->is_Allocate()) { - return allo->as_Allocate(); + if (AllocateNode* allocate = isa(allo); allocate != nullptr) { + return allocate; } } // Report failure to match. @@ -5024,7 +5038,7 @@ void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* coun Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true); Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE), AndI(ch, intcon(0xff)), T_CHAR, MemNode::unordered, false, - false, true /* mismatched */); + false, true /* mismatched */, false, false, 0); IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN); head->init_req(2, IfTrue(iff)); @@ -5042,7 +5056,7 @@ Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) { } ciInstance* holder = nullptr; if (!field->is_static()) { - ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop(); + ciObject* const_oop = obj->bottom_type()->as_oopptr()->const_oop(); if (const_oop != nullptr && const_oop->is_instance()) { holder = const_oop->as_instance(); } @@ -5064,7 +5078,7 @@ Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) { Node* GraphKit::maybe_narrow_object_type(Node* obj, ciKlass* type, bool maybe_larval) { const Type* obj_type = obj->bottom_type(); const TypeOopPtr* sig_type = TypeOopPtr::make_from_klass(type); - if (obj_type->isa_oopptr() && sig_type->is_loaded() && !obj_type->higher_equal(sig_type)) { + if (obj_type->is_oopptr() && sig_type->is_loaded() && !obj_type->higher_equal(sig_type)) { const Type* narrow_obj_type = obj_type->filter_speculative(sig_type); // keep speculative part Node* casted_obj = gvn().transform(new CheckCastPPNode(control(), obj, narrow_obj_type)); obj = casted_obj; diff --git a/src/hotspot/share/opto/graphKit.hpp b/src/hotspot/share/opto/graphKit.hpp index 9e26adaf8526..0776932fed93 100644 --- a/src/hotspot/share/opto/graphKit.hpp +++ b/src/hotspot/share/opto/graphKit.hpp @@ -538,15 +538,15 @@ class GraphKit : public Phase { // Access unaliased memory Node* memory(uint alias_idx); Node* memory(const TypePtr *tp) { return memory(C->get_alias_index(tp)); } - Node* memory(Node* adr) { return memory(_gvn.type(adr)->is_ptr()); } + Node* memory(Node* adr) { return memory(_gvn.type(adr)->as_ptr()); } // Access immutable memory Node* immutable_memory() { return C->immutable_memory(); } // Set unaliased memory void set_memory(Node* c, uint alias_idx) { merged_memory()->set_memory_at(alias_idx, c); } - void set_memory(Node* c, const TypePtr *tp) { set_memory(c,C->get_alias_index(tp)); } - void set_memory(Node* c, Node* adr) { set_memory(c,_gvn.type(adr)->is_ptr()); } + void set_memory(Node* c, const TypePtr* tp) { set_memory(c, C->get_alias_index(tp)); } + void set_memory(Node* c, Node* adr) { set_memory(c, _gvn.type(adr)->as_ptr()); } // Get the entire memory state (probably a MergeMemNode), and reset it // (The resetting prevents somebody from using the dangling Node pointer.) @@ -587,11 +587,14 @@ class GraphKit : public Phase { // Return the new StoreXNode Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt, MemNode::MemOrd, - bool require_atomic_access = false, - bool unaligned = false, - bool mismatched = false, - bool unsafe = false, - int barrier_data = 0); + bool require_atomic_access, + bool unaligned, + bool mismatched, + bool unsafe, + bool store_special, + int barrier_data); + Node* store_to_memory(Node* ctl, Node* adr, Node* val, BasicType bt, + MemNode::MemOrd); // Perform decorated accesses @@ -602,8 +605,15 @@ class GraphKit : public Phase { const Type* val_type, BasicType bt, DecoratorSet decorators, - bool safe_for_replace = true, - const ValueTypeNode* vt = nullptr); + bool safe_for_replace, + const ValueTypeNode* vt); + Node* access_store_at(Node* obj, // containing obj + Node* adr, // actual address to store val at + const TypePtr* adr_type, + Node* val, + const Type* val_type, + BasicType bt, + DecoratorSet decorators); Node* access_load_at(Node* obj, // containing obj Node* adr, // actual address to load val at diff --git a/src/hotspot/share/opto/idealGraphPrinter.cpp b/src/hotspot/share/opto/idealGraphPrinter.cpp index 827c710669b5..75eb59118d36 100644 --- a/src/hotspot/share/opto/idealGraphPrinter.cpp +++ b/src/hotspot/share/opto/idealGraphPrinter.cpp @@ -700,12 +700,10 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { stringStream s2(buffer, sizeof(buffer) - 1); node->dump_spec(&s2); - if (t != nullptr && (t->isa_instptr() || t->isa_instklassptr())) { - const TypeInstPtr *toop = t->isa_instptr(); - const TypeInstKlassPtr *tkls = t->isa_instklassptr(); - if (toop) { + if (t != nullptr && (t->is_instptr() || t->is_instklassptr())) { + if (t->is_instptr()) { s2.print(" Oop:"); - } else if (tkls) { + } else { s2.print(" Klass:"); } t->dump_on(&s2); @@ -729,8 +727,8 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { print_prop(short_name, "F"); } else if ((node->is_Con() && node->is_Type()) || node->is_Proj()) { - if (t->base() == Type::Int && t->is_int()->is_con()) { - const TypeInt *typeInt = t->is_int(); + if (t->base() == Type::Int && t->as_int()->is_con()) { + const TypeInt* typeInt = t->as_int(); assert(typeInt->is_con(), "must be constant"); jint value = typeInt->get_con(); @@ -743,8 +741,8 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { } } else if (t == Type::TOP) { print_prop(short_name, "^"); - } else if (t->base() == Type::Long && t->is_long()->is_con()) { - const TypeLong *typeLong = t->is_long(); + } else if (t->base() == Type::Long && t->as_long()->is_con()) { + const TypeLong* typeLong = t->as_long(); assert(typeLong->is_con(), "must be constant"); jlong value = typeLong->get_con(); @@ -756,7 +754,7 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { print_prop(short_name, "L"); } } else if (t->base() == Type::KlassPtr || t->base() == Type::InstKlassPtr || t->base() == Type::AryKlassPtr) { - const TypeKlassPtr *typeKlass = t->is_klassptr(); + const TypeKlassPtr* typeKlass = t->as_klassptr(); print_prop(short_name, "CP"); } else if (t->base() == Type::Control) { print_prop(short_name, "C"); @@ -767,7 +765,7 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { } else if (t->base() == Type::Return_Address) { print_prop(short_name, "RA"); } else if (t->base() == Type::AnyPtr) { - if (t->is_ptr()->ptr() == TypePtr::Null) { + if (t->as_ptr()->ptr() == TypePtr::Null) { print_prop(short_name, "Null"); } else { print_prop(short_name, "P"); @@ -776,7 +774,7 @@ void IdealGraphPrinter::visit_node(Node* n, bool edges) { print_prop(short_name, "RP"); } else if (t->base() == Type::AryPtr) { print_prop(short_name, "AP"); - } else if (t->base() == Type::NarrowOop && t->is_narrowoop() == TypeNarrowOop::NULL_PTR) { + } else if (t->base() == Type::NarrowOop && t->as_narrowoop() == TypeNarrowOop::NULL_PTR) { print_prop(short_name, "Null"); } } @@ -933,7 +931,7 @@ ciField* IdealGraphPrinter::find_source_field_of_array_access(const Node* node, } do { - if (const TypePtr* in = node->in_adr_type(); in != nullptr && in->isa_aryptr()) { + if (const TypePtr* in = node->in_adr_type(); in != nullptr && in->is_aryptr()) { // Only process array accesses. Pattern match to find actual field source access. node = get_load_node(node); if (node != nullptr) { @@ -957,8 +955,8 @@ ciField* IdealGraphPrinter::find_source_field_of_array_access(const Node* node, Node* IdealGraphPrinter::get_load_node(const Node* node) { Node* load = nullptr; Node* addr = node->as_Mem()->in(MemNode::Address); - if (addr != nullptr && addr->is_AddP()) { - Node* base = addr->as_AddP()->base_node(); + if (AddPNode* addr_add = Node::isa(addr); addr_add != nullptr) { + Node* base = addr_add->base_node(); if (base != nullptr) { base = base->uncast(); if (base->is_Load()) { diff --git a/src/hotspot/share/opto/idealKit.cpp b/src/hotspot/share/opto/idealKit.cpp index 02d3aa0fda7e..1227503548e4 100644 --- a/src/hotspot/share/opto/idealKit.cpp +++ b/src/hotspot/share/opto/idealKit.cpp @@ -71,11 +71,11 @@ void IdealKit::if_then(Node* left, BoolTest::mask relop, Node* right, float prob, float cnt, bool push_new_state) { assert((state() & (BlockS|LoopS|IfThenS|ElseS)), "bad state for new If"); Node* bol; - if (left->bottom_type()->isa_ptr() == nullptr) { - if (left->bottom_type()->isa_int() != nullptr) { + if (!left->bottom_type()->is_ptr()) { + if (left->bottom_type()->is_int()) { bol = Bool(CmpI(left, right), relop); } else { - assert(left->bottom_type()->isa_long() != nullptr, "what else?"); + assert(left->bottom_type()->is_long(), "what else?"); bol = Bool(CmpL(left, right), relop); } } else { diff --git a/src/hotspot/share/opto/ifnode.cpp b/src/hotspot/share/opto/ifnode.cpp index a9a6cc0af191..23384471b4b8 100644 --- a/src/hotspot/share/opto/ifnode.cpp +++ b/src/hotspot/share/opto/ifnode.cpp @@ -128,8 +128,8 @@ static Node* split_if(IfNode *iff, PhaseIterGVN *igvn) { Node *cmp = b->in(1); if( !cmp->is_Cmp() ) return nullptr; i1 = cmp->in(1); - if( i1 == nullptr || !i1->is_Phi() ) return nullptr; - PhiNode *phi = i1->as_Phi(); + PhiNode* phi = Node::isa(i1); + if (phi == nullptr) return nullptr; Node *con2 = cmp->in(2); if( !con2->is_Con() ) return nullptr; // See that the merge point contains some constants @@ -526,11 +526,10 @@ IfProjNode* IfNode::range_check_trap_proj(int& flip_test, Node*& l, Node*& r) co return nullptr; } Node* b = in(1); - if (b == nullptr || !b->is_Bool()) return nullptr; - BoolNode* bn = b->as_Bool(); + BoolNode* bn = isa(b); + if (bn == nullptr) return nullptr; Node* cmp = bn->in(1); - if (cmp == nullptr) return nullptr; - if (cmp->Opcode() != Op_CmpU) return nullptr; + if (!is_exact(cmp)) return nullptr; l = cmp->in(1); r = cmp->in(2); @@ -677,7 +676,7 @@ Node* IfNode::up_one_dom(Node *curr, bool linear_only) { if( din4->is_Call() && // Handle a slow-path call on either arm (din4 = din4->in(0)) ) din4 = din4->in(0); - if (din3 != nullptr && din3 == din4 && din3->is_If()) // Regions not degraded to a copy + if (is(din3) && din3 == din4) // Regions not degraded to a copy return din3; // Skip around diamonds } @@ -698,14 +697,10 @@ const TypeInteger* IfNode::filtered_integer_type(PhaseGVN* gvn, Node* val, Node* assert(bt == T_INT || bt == T_LONG, "expected int or long"); const jlong min_value = bt == T_INT ? min_jint : min_jlong; const jlong max_value = bt == T_INT ? max_jint : max_jlong; - assert(if_proj && - (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection"); - if (if_proj->in(0) && if_proj->in(0)->is_If()) { - IfNode* iff = if_proj->in(0)->as_If(); - if (iff->in(1) && iff->in(1)->is_Bool()) { - BoolNode* bol = iff->in(1)->as_Bool(); - if (bol->in(1) && bol->in(1)->is_Cmp()) { - const CmpNode* cmp = bol->in(1)->as_Cmp(); + assert(is(if_proj), "expecting an if projection"); + if (IfNode* iff = isa(if_proj->in(0)); iff != nullptr) { + if (BoolNode* bol = isa(iff->in(1)); bol != nullptr) { + if (const CmpNode* cmp = isa(bol->in(1)); cmp != nullptr) { // Val is always the lhs of the comparison: val CmpI/CmpL cmp2 if (cmp->Opcode() == (bt == T_INT ? Op_CmpI : Op_CmpL) && cmp->in(1) == val) { // Only CmpI/CmpL allowed, assumed by signed logic below. @@ -781,7 +776,7 @@ const TypeInteger* IfNode::filtered_integer_type(PhaseGVN* gvn, Node* val, Node* const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node* val, Node* if_proj) { const TypeInteger* t = filtered_integer_type(gvn, val, if_proj, T_INT); - return t == nullptr ? nullptr : t->is_int(); + return t == nullptr ? nullptr : t->as_int(); } //------------------------------fold_compares---------------------------- @@ -824,24 +819,21 @@ const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node* val, Node* if_proj // Is the comparison for this If suitable for folding? bool IfNode::cmp_folds(PhaseIterGVN* igvn, bool fold_ne) { - return in(1) != nullptr && - in(1)->is_Bool() && - in(1)->in(1) != nullptr && - (in(1)->in(1)->Opcode() == Op_CmpI || in(1)->in(1)->Opcode() == Op_CmpL) && + BoolNode* in1_b = isa(in(1)); + return in1_b != nullptr && + (is_exact(in(1)->in(1)) || is_exact(in(1)->in(1))) && in(1)->in(1)->in(2) != nullptr && in(1)->in(1)->in(2) != igvn->C->top() && - (in(1)->as_Bool()->_test.is_less() || - in(1)->as_Bool()->_test.is_greater() || - (fold_ne && in(1)->as_Bool()->_test._test == BoolTest::ne)); + (in1_b->_test.is_less() || + in1_b->_test.is_greater() || + (fold_ne && in1_b->_test._test == BoolTest::ne)); } // Is a dominating control suitable for folding with this if? bool IfNode::is_ctrl_folds(Node* ctrl, PhaseIterGVN* igvn) { - return ctrl != nullptr && - ctrl->is_IfProj() && + return is(ctrl) && ctrl->outcnt() == 1 && // No side-effects - ctrl->in(0) != nullptr && - ctrl->in(0)->Opcode() == Op_If && + is_exact(ctrl->in(0)) && ctrl->in(0)->outcnt() == 2 && ctrl->in(0)->as_If()->cmp_folds(igvn, true) && // Must compare same value @@ -854,7 +846,7 @@ bool IfNode::is_ctrl_folds(Node* ctrl, PhaseIterGVN* igvn) { bool IfNode::has_shared_region(IfProjNode* proj, IfProjNode*& success, IfProjNode*& fail) const { IfProjNode* otherproj = proj->other_if_proj(); Node* otherproj_ctrl_use = otherproj->unique_ctrl_out_or_null(); - RegionNode* region = (otherproj_ctrl_use != nullptr && otherproj_ctrl_use->is_Region()) ? otherproj_ctrl_use->as_Region() : nullptr; + RegionNode* region = isa(otherproj_ctrl_use); success = nullptr; fail = nullptr; @@ -1561,7 +1553,7 @@ void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGV Node_Stack stack(2); assert(r->Opcode() == Op_LoadRange, "unexpected range check"); - const TypeInt* array_size = igvn->type(r)->is_int(); + const TypeInt* array_size = igvn->type(r)->as_int(); stack.push(l, 0); @@ -1574,7 +1566,7 @@ void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGV Node* use = n->raw_out(i); if (stack.size() == 1) { if (use->Opcode() == Op_ConvI2L) { - const TypeLong* bounds = use->as_Type()->type()->is_long(); + const TypeLong* bounds = use->as_Type()->type()->as_long(); if (bounds->_lo <= array_size->_lo && bounds->_hi >= array_size->_hi && (bounds->_lo != array_size->_lo || bounds->_hi != array_size->_hi)) { stack.set_index(i+1); @@ -1614,8 +1606,8 @@ void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGV } } } - } else if (use->in(0) == nullptr && (igvn->type(use)->isa_long() || - igvn->type(use)->isa_ptr())) { + } else if (use->in(0) == nullptr && (igvn->type(use)->is_long() || + igvn->type(use)->is_ptr())) { stack.set_index(i+1); stack.push(use, 0); break; @@ -1636,10 +1628,8 @@ bool IfNode::is_cmp_with_loadrange(IfProjNode* proj) const { if (other->Opcode() == Op_LoadRange && ((other->in(0) != nullptr && other->in(0) == proj) || (other->in(0) == nullptr && - other->in(2) != nullptr && - other->in(2)->is_AddP() && - other->in(2)->in(1) != nullptr && - other->in(2)->in(1)->Opcode() == Op_CastPP && + is(other->in(2)) && + is_exact(other->in(2)->in(1)) && other->in(2)->in(1)->in(0) == proj))) { return true; } @@ -1650,10 +1640,8 @@ bool IfNode::is_cmp_with_loadrange(IfProjNode* proj) const { bool IfNode::is_null_check(IfProjNode* proj, PhaseIterGVN* igvn) const { Node* other = in(1)->in(1)->in(2); if (other->in(MemNode::Address) != nullptr && - proj->in(0)->in(1) != nullptr && - proj->in(0)->in(1)->is_Bool() && - proj->in(0)->in(1)->in(1) != nullptr && - proj->in(0)->in(1)->in(1)->Opcode() == Op_CmpP && + is(proj->in(0)->in(1)) && + is_exact(proj->in(0)->in(1)->in(1)) && proj->in(0)->in(1)->in(1)->in(2) != nullptr && proj->in(0)->in(1)->in(1)->in(1) == other->in(MemNode::Address)->in(AddPNode::Address)->uncast() && igvn->type(proj->in(0)->in(1)->in(1)->in(2)) == TypePtr::NULL_PTR) { @@ -1670,7 +1658,7 @@ bool IfNode::is_flat_array_check(PhaseTransform* phase, Node** array) { return false; } Node* cmp = bol->in(1); - if (cmp->isa_FlatArrayCheck()) { + if (cmp->is_FlatArrayCheck()) { if (array != nullptr) { *array = cmp->in(FlatArrayCheckNode::ArrayOrKlass); } @@ -2061,8 +2049,7 @@ bool IfNode::has_same_non_constant_condition(const IfNode* other_if) const { return this_bool != nullptr && !this_bool->is_Con(); } - if (dom_bool == nullptr || !dom_bool->is_Bool() || - this_bool == nullptr || !this_bool->is_Bool()) { + if (!is(dom_bool) || !is(this_bool)) { return false; } Node* dom_cmp = dom_bool->in(1); @@ -2070,8 +2057,7 @@ bool IfNode::has_same_non_constant_condition(const IfNode* other_if) const { // If the comparison is a subtype check, then SubTypeCheck nodes may have profile data attached to them and may be // different nodes even-though they perform the same subtype check - if (dom_cmp == nullptr || !dom_cmp->is_SubTypeCheck() || - this_cmp == nullptr || !this_cmp->is_SubTypeCheck()) { + if (!is(dom_cmp) || !is(this_cmp)) { return false; } @@ -2263,7 +2249,7 @@ static int subsuming_bool_test_encode(Node* node) { // If the test is constant & we match, then we are the input Control Node* IfProjNode::Identity(PhaseGVN* phase) { // Can only optimize if cannot go the other way - const TypeTuple *t = phase->type(in(0))->is_tuple(); + const TypeTuple* t = phase->type(in(0))->as_tuple(); if (t == TypeTuple::IFNEITHER || (always_taken(t) && // During parsing (GVN) we don't remove dead code aggressively. // Cut off dead branch and let PhaseRemoveUseless take care of it. @@ -2279,7 +2265,7 @@ Node* IfProjNode::Identity(PhaseGVN* phase) { // CountedLoopEndNode may be eliminated by if subsuming, replace CountedLoopNode with LoopNode to // avoid mismatching between CountedLoopNode and CountedLoopEndNode in the following optimization. Node* head = unique_ctrl_out_or_null(); - if (head != nullptr && head->is_BaseCountedLoop() && head->in(LoopNode::LoopBackControl) == this) { + if (is(head) && head->in(LoopNode::LoopBackControl) == this) { Node* new_head = new LoopNode(head->in(LoopNode::EntryControl), this); phase->is_IterGVN()->register_new_node_with_optimizer(new_head); phase->is_IterGVN()->replace_node(head, new_head); diff --git a/src/hotspot/share/opto/intrinsicnode.cpp b/src/hotspot/share/opto/intrinsicnode.cpp index c0d8b9b0a536..4bca423da269 100644 --- a/src/hotspot/share/opto/intrinsicnode.cpp +++ b/src/hotspot/share/opto/intrinsicnode.cpp @@ -125,8 +125,8 @@ SignumFNode* SignumFNode::make(PhaseGVN& gvn, Node* in) { Node* CompressBitsNode::Ideal(PhaseGVN* phase, bool can_reshape) { Node* src = in(1); Node* mask = in(2); - if (bottom_type()->isa_int()) { - if (mask->Opcode() == Op_LShiftI && phase->type(mask->in(1))->isa_int() && phase->type(mask->in(1))->is_int()->is_con()) { + if (bottom_type()->is_int()) { + if (mask->Opcode() == Op_LShiftI && phase->type(mask->in(1))->is_int() && phase->type(mask->in(1))->as_int()->is_con()) { // compress(x, 1 << n) == (x >> n & 1) if (phase->type(mask->in(1))->higher_equal(TypeInt::ONE)) { Node* rshift = phase->transform(new RShiftINode(in(1), mask->in(2))); @@ -143,8 +143,8 @@ Node* CompressBitsNode::Ideal(PhaseGVN* phase, bool can_reshape) { return new AndINode(compr, src->in(1)); } } else { - assert(bottom_type()->isa_long(), ""); - if (mask->Opcode() == Op_LShiftL && phase->type(mask->in(1))->isa_long() && phase->type(mask->in(1))->is_long()->is_con()) { + assert(bottom_type()->is_long(), ""); + if (mask->Opcode() == Op_LShiftL && phase->type(mask->in(1))->is_long() && phase->type(mask->in(1))->as_long()->is_con()) { // compress(x, 1 << n) == (x >> n & 1) if (phase->type(mask->in(1))->higher_equal(TypeLong::ONE)) { Node* rshift = phase->transform(new RShiftLNode(in(1), mask->in(2))); @@ -183,8 +183,8 @@ Node* CompressBitsNode::Identity(PhaseGVN* phase) { Node* ExpandBitsNode::Ideal(PhaseGVN* phase, bool can_reshape) { Node* src = in(1); Node* mask = in(2); - if (bottom_type()->isa_int()) { - if (mask->Opcode() == Op_LShiftI && phase->type(mask->in(1))->isa_int() && phase->type(mask->in(1))->is_int()->is_con()) { + if (bottom_type()->is_int()) { + if (mask->Opcode() == Op_LShiftI && phase->type(mask->in(1))->is_int() && phase->type(mask->in(1))->as_int()->is_con()) { // expand(x, 1 << n) == (x & 1) << n if (phase->type(mask->in(1))->higher_equal(TypeInt::ONE)) { Node* andnode = phase->transform(new AndINode(in(1), phase->makecon(TypeInt::ONE))); @@ -200,8 +200,8 @@ Node* ExpandBitsNode::Ideal(PhaseGVN* phase, bool can_reshape) { return new AndINode(src->in(1), mask); } } else { - assert(bottom_type()->isa_long(), ""); - if (mask->Opcode() == Op_LShiftL && phase->type(mask->in(1))->isa_long() && phase->type(mask->in(1))->is_long()->is_con()) { + assert(bottom_type()->is_long(), ""); + if (mask->Opcode() == Op_LShiftL && phase->type(mask->in(1))->is_long() && phase->type(mask->in(1))->as_long()->is_con()) { // expand(x, 1 << n) == (x & 1) << n if (phase->type(mask->in(1))->higher_equal(TypeLong::ONE)) { Node* andnode = phase->transform(new AndLNode(in(1), phase->makecon(TypeLong::ONE))); @@ -314,10 +314,10 @@ const Type* CompressBitsNode::Value(PhaseGVN* phase) const { BasicType bt = bottom_type()->basic_type(); if (bt == T_INT) { - return RangeInference::infer_compress_bits(t1->is_int(), t2->is_int()); + return RangeInference::infer_compress_bits(t1->as_int(), t2->as_int()); } else { assert(bt == T_LONG, "unexpected BasicType %s", type2name(bt)); - return RangeInference::infer_compress_bits(t1->is_long(), t2->is_long()); + return RangeInference::infer_compress_bits(t1->as_long(), t2->as_long()); } } @@ -341,8 +341,8 @@ const Type* ExpandBitsNode::Value(PhaseGVN* phase) const { } BasicType bt = bottom_type()->basic_type(); - const TypeInteger* src_type = t1->is_integer(bt); - const TypeInteger* mask_type = t2->is_integer(bt); + const TypeInteger* src_type = t1->as_integer(bt); + const TypeInteger* mask_type = t2->as_integer(bt); int w = bt == T_INT ? 32 : 64; // Constant fold if both src and mask are constants. diff --git a/src/hotspot/share/opto/lcm.cpp b/src/hotspot/share/opto/lcm.cpp index 1de1c6ec0a03..c3bce2d98084 100644 --- a/src/hotspot/share/opto/lcm.cpp +++ b/src/hotspot/share/opto/lcm.cpp @@ -43,11 +43,11 @@ // i.e. will grab into the base of the heap if it represents null. static bool accesses_heap_base_zone(Node *val) { if (CompressedOops::base() != nullptr) { // Implies UseCompressedOops. - if (val && val->is_Mach()) { - if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) { + if (MachNode* val_mach = Node::isa(val); val_mach != nullptr) { + if (val_mach->ideal_Opcode() == Op_DecodeN) { // This assumes all Decodes with TypePtr::NotNull are matched to nodes that // decode null to point to the heap base (Decode_NN). - if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) { + if (val->bottom_type()->as_oopptr()->ptr() == TypePtr::NotNull) { return true; } } @@ -262,7 +262,7 @@ void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allo continue; // Not an memory op; skip it } if (val == base || - (val == index && val->bottom_type()->isa_narrowoop())) { + (val == index && val->bottom_type()->is_narrowoop())) { break; // Found it } else { continue; // Skip it @@ -293,7 +293,7 @@ void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allo if (base == nullptr || base == NodeSentinel) { // Narrow oop address doesn't have base, only index. // Give up if offset is beyond page size or if heap base is not protected. - if (val->bottom_type()->isa_narrowoop() && + if (val->bottom_type()->is_narrowoop() && (MacroAssembler::needs_explicit_null_check(offset) || !CompressedOops::use_implicit_null_checks())) continue; @@ -305,7 +305,7 @@ void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allo tptr = base->get_ptr_type(); } else { // only regular oops are expected here - tptr = base->bottom_type()->is_ptr(); + tptr = base->bottom_type()->as_ptr(); } // Give up if offset is not a compile-time constant. if (offset == Type::OffsetBot || tptr->offset() == Type::OffsetBot) @@ -465,7 +465,7 @@ void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allo // Move any MachTemp inputs to the end of the test block. for (uint i = 0; i < best->req(); i++) { Node* n = best->in(i); - if (n == nullptr || !n->is_MachTemp()) { + if (!Node::is(n)) { continue; } ensure_node_is_at_block_or_above(n, block); diff --git a/src/hotspot/share/opto/library_call.cpp b/src/hotspot/share/opto/library_call.cpp index 9853363238c5..fe9a52f722ed 100644 --- a/src/hotspot/share/opto/library_call.cpp +++ b/src/hotspot/share/opto/library_call.cpp @@ -1038,9 +1038,9 @@ Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_o Node* thread_obj_handle = (is_immutable - ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(), + ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->as_ptr(), TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered) - : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered)); + : make_load(nullptr, p, p->bottom_type()->as_ptr(), T_ADDRESS, MemNode::unordered)); thread_obj_handle = _gvn.transform(thread_obj_handle); DecoratorSet decorators = IN_NATIVE; @@ -1230,7 +1230,7 @@ bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) { } // length is now known positive, add a cast node to make this explicit - jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long(); + jlong upper_bound = _gvn.type(length)->as_integer(bt)->hi_as_long(); Node* casted_length = ConstraintCastNode::make_cast_for_basic_type( control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt), ConstraintCastNode::DependencyType::FloatingNarrowing, bt); @@ -1632,7 +1632,7 @@ bool LibraryCallKit::inline_string_toBytesU() { bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0); // If true, then check if src array address is aligned to HeapWordSize if (aligned) { - const TypeInt* toffset = gvn().type(offset)->is_int(); + const TypeInt* toffset = gvn().type(offset)->as_int(); aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0); } @@ -1711,8 +1711,8 @@ bool LibraryCallKit::inline_string_getCharsU() { Node* dst_start = array_element_address(dst, dst_begin, T_CHAR); // Check if array addresses are aligned to HeapWordSize - const TypeInt* tsrc = gvn().type(src_begin)->is_int(); - const TypeInt* tdst = gvn().type(dst_begin)->is_int(); + const TypeInt* tsrc = gvn().type(src_begin)->as_int(); + const TypeInt* tdst = gvn().type(dst_begin)->as_int(); bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) && tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0); @@ -2162,7 +2162,7 @@ LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) return Type::RawPtr; } else if (base_type->base() == Type::RawPtr) { return Type::RawPtr; - } else if (base_type->isa_oopptr()) { + } else if (base_type->is_oopptr()) { // Base is never null => always a heap address. if (!TypePtr::NULL_PTR->higher_equal(base_type)) { return Type::OopPtr; @@ -2365,10 +2365,10 @@ const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_ const TypeOopPtr* result = nullptr; // See if it is a narrow oop array. - if (adr_type->isa_aryptr()) { + if (adr_type->is_aryptr()) { if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) { - const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr(); - null_free = adr_type->is_aryptr()->is_null_free(); + const TypeOopPtr* elem_type = adr_type->as_aryptr()->elem()->make_oopptr(); + null_free = adr_type->as_aryptr()->is_null_free(); if (elem_type != nullptr && elem_type->is_loaded()) { // Sharpen the value type. result = elem_type; @@ -2382,7 +2382,7 @@ const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_ // Sharpen the value type. result = TypeOopPtr::make_from_klass(sharpened_klass); if (null_free) { - result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr(); + result = result->join_speculative(TypePtr::NOTNULL)->as_oopptr(); } } if (result != nullptr) { @@ -2579,8 +2579,8 @@ bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, c bool mismatched = false; BasicType bt = T_ILLEGAL; ciField* field = nullptr; - if (adr_type->isa_instptr()) { - const TypeInstPtr* instptr = adr_type->is_instptr(); + if (adr_type->is_instptr()) { + const TypeInstPtr* instptr = adr_type->as_instptr(); ciInstanceKlass* k = instptr->instance_klass(); int off = instptr->offset(); if (instptr->const_oop() != nullptr && @@ -2608,10 +2608,10 @@ bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, c if (bt != T_ILLEGAL) { assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access"); - if (bt == T_BYTE && adr_type->isa_aryptr()) { + if (bt == T_BYTE && adr_type->is_aryptr()) { // Alias type doesn't differentiate between byte[] and boolean[]). // Use address type to get the element type. - bt = adr_type->is_aryptr()->elem()->array_element_basic_type(); + bt = adr_type->as_aryptr()->elem()->array_element_basic_type(); } if (is_reference_type(bt, true)) { // accessing an array field with getReference is not a mismatch @@ -2622,7 +2622,7 @@ bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, c return false; } mismatched = (bt != type); - } else if (alias_type->adr_type()->isa_oopptr()) { + } else if (alias_type->adr_type()->is_oopptr()) { mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched } @@ -2763,14 +2763,14 @@ bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) { Node* ptr; bool immutable_memory = false; DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED; - if (base_type->isa_instptr()) { + if (base_type->is_instptr()) { const TypeLong* offset_type = _gvn.type(offset)->isa_long(); if (offset_type == nullptr || !offset_type->is_con()) { // Offset into a non-array should be a constant decorators |= C2_MISMATCHED; } else { int offset_con = checked_cast(offset_type->get_con()); - ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass(); + ciInstanceKlass* base_klass = base_type->as_instptr()->instance_klass(); ciField* field = base_klass->get_non_flat_field_by_offset(offset_con); if (field == nullptr) { assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8()); @@ -2793,11 +2793,11 @@ bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) { base = base->as_ValueType()->buffer(this, true); } ptr = basic_plus_adr(base, ConvL2X(offset)); - } else if (base_type->isa_aryptr()) { + } else if (base_type->is_aryptr()) { decorators |= IS_ARRAY; if (!layout.is_flat()) { - if (!base_type->is_aryptr()->is_not_flat()) { - const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat(); + if (!base_type->as_aryptr()->is_not_flat()) { + const TypeAryPtr* array_type = base_type->as_aryptr()->cast_to_not_flat(); // TODO 8388444 This should be a CheckCastPP, can we add a test? Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing)); replace_in_map(base, new_base); @@ -2825,7 +2825,7 @@ bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) { replace_in_map(base, new_base); base = new_base; ptr = basic_plus_adr(base, ConvL2X(offset)); - const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr(); + const TypeAryPtr* ptr_type = _gvn.type(ptr)->as_aryptr(); if (ptr_type->field_offset().get() != 0) { // TODO 8388444 This should be a CheckCastPP, can we add a test? ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing)); @@ -2856,7 +2856,7 @@ bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) { assert(value_type == TypePtr::NULL_PTR || value_type->value_klass() == value_klass, "value is of type %s while value klass is %s", value_type->value_klass()->name()->as_utf8(), value_klass->name()->as_utf8()); if (!layout.is_flat()) { - const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr(); + const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->as_ptr(); access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators); } else { bool atomic = layout.is_atomic_flat(); @@ -2872,7 +2872,7 @@ bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) { decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD); ValueTypeNode* result; if (!layout.is_flat()) { - const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr(); + const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->as_ptr(); Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators); result = ValueTypeNode::make_from_oop(this, oop, value_klass); } else { @@ -3046,7 +3046,7 @@ bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadSt Compile::AliasType* alias_type = C->alias_type(adr_type); BasicType bt = alias_type->basic_type(); if (bt != T_ILLEGAL) { - if (adr_type->isa_aryptr() && adr_type->is_flat()) { + if (adr_type->is_aryptr() && adr_type->is_flat()) { // mismatched access to a flat array element: // type=T_OBJECT doesn't make sense (and breaks Compile::adjust_flat_array_access_aliases()). // Some other type may need to be supported so this may need to be relaxed. @@ -3095,17 +3095,17 @@ bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadSt if (is_reference_type(type)) { decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF; - if (oldval != nullptr && oldval->is_ValueType()) { + if (ValueTypeNode* oldval_vt = Node::isa(oldval); oldval_vt != nullptr) { // Re-execute the unsafe access if allocation triggers deoptimization. PreserveReexecuteState preexecs(this); jvms()->set_should_reexecute(true); - oldval = oldval->as_ValueType()->buffer(this)->get_oop(); + oldval = oldval_vt->buffer(this)->get_oop(); } - if (newval != nullptr && newval->is_ValueType()) { + if (ValueTypeNode* newval_vt = Node::isa(newval); newval_vt != nullptr) { // Re-execute the unsafe access if allocation triggers deoptimization. PreserveReexecuteState preexecs(this); jvms()->set_should_reexecute(true); - newval = newval->as_ValueType()->buffer(this)->get_oop(); + newval = newval_vt->buffer(this)->get_oop(); } // Transformation of a value which could be null pointer (CastPP #null) @@ -3432,15 +3432,15 @@ bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, co Node* thread = ideal.thread(); Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset())); Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset()); - access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); - access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); + access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->as_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); + access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->as_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); insert_mem_bar(Op_MemBarStoreLoad); ideal.sync_kit(this); Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address())); Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/); Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset()); - const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr(); + const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->as_ptr(); Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/); Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable)); @@ -3476,8 +3476,8 @@ bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, cons Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset()); sync_kit(ideal); - access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); - access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); + access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->as_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); + access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->as_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED); ideal.sync_kit(this); } ideal.end_if(); @@ -3499,7 +3499,7 @@ bool LibraryCallKit::inline_native_notify_jvmti_sync() { Node* thread = ideal.thread(); Node* arg = argument(0); // argument for notification Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset())); - const TypePtr *addr_type = _gvn.type(addr)->isa_ptr(); + const TypePtr* addr_type = _gvn.type(addr)->as_ptr(); sync_kit(ideal); access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED); @@ -3741,7 +3741,7 @@ bool LibraryCallKit::inline_native_getEventWriter() { // Load the raw epoch value from the threadObj. Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset()); Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset, - _gvn.type(threadObj_epoch_offset)->isa_ptr(), + _gvn.type(threadObj_epoch_offset)->as_ptr(), TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD); @@ -3761,7 +3761,7 @@ bool LibraryCallKit::inline_native_getEventWriter() { // Load the raw epoch value from the vthread. Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset()); - Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(), + Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->as_ptr(), TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD); @@ -3998,7 +3998,7 @@ void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) { // False branch, is carrierThread. Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread)); // Store release - Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true); + Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true, false, false, false, false, 0); set_all_memory(input_memory_state); @@ -4008,7 +4008,7 @@ void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) { // Load the raw epoch value from the vthread. Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset()); - Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR, + Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->as_ptr(), TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD); // Mask off the excluded information from the epoch. @@ -4019,7 +4019,7 @@ void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) { // Store the vthread tid to the jfr thread local. Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR)); - Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true); + Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true, false, false, false, false, 0); // Branch is_excluded to conditionalize updating the epoch . Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask)); @@ -4041,7 +4041,7 @@ void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) { // Store the vthread epoch to the jfr thread local. Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR)); - Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true); + Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true, false, false, false, false, 0); RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT); record_for_igvn(excluded_rgn); @@ -4064,10 +4064,10 @@ void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) { // Store the vthread exclusion state to the jfr thread local. Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR)); - store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true); + store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true, false, false, false, false, 0); // Store release - Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true); + Node* vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true, false, false, false, false, 0); RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT); record_for_igvn(thread_compare_rgn); @@ -4113,7 +4113,7 @@ bool LibraryCallKit::inline_native_try_update_epoch() { const int jfr_epoch_field_offset = field->offset_in_bytes(); Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset); - const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr(); + const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->as_ptr(); const int alias_idx = C->get_alias_index(adr_type); BasicType bt = field->layout_type(); const Type * oop_epoch_field_type = Type::get_const_basic_type(bt); @@ -4226,14 +4226,14 @@ bool LibraryCallKit::inline_native_setCurrentThread() { Node* thread = _gvn.transform(new ThreadLocalNode()); Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset())); Node* thread_obj_handle - = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered); - const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr(); + = make_load(nullptr, p, p->bottom_type()->as_ptr(), T_OBJECT, MemNode::unordered); + const TypePtr* adr_type = _gvn.type(thread_obj_handle)->as_ptr(); access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED); // Change the _monitor_owner_id of the JavaThread Node* tid = load_field_from_object(arr, "tid", "J"); Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset())); - store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true); + store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true, false, false, false, false, 0); JFR_ONLY(extend_setCurrentThread(thread, arr);) return true; @@ -4257,9 +4257,9 @@ Node* LibraryCallKit::scopedValueCache_helper() { // We cannot use immutable_memory() because we might flip onto a // different carrier thread, at which point we'll need to use that // carrier thread's cache. - // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(), + // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->as_ptr(), // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)); - return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered); + return make_load(nullptr, p, p->bottom_type()->as_ptr(), T_ADDRESS, MemNode::unordered); } //------------------------inline_native_scopedValueCache------------------ @@ -4277,7 +4277,7 @@ bool LibraryCallKit::inline_native_setScopedValueCache() { Node* cache_obj_handle = scopedValueCache_helper(); const Type* objects_type = scopedValueCache_type(); - const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr(); + const TypePtr* adr_type = _gvn.type(cache_obj_handle)->as_ptr(); access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED); return true; @@ -4911,7 +4911,7 @@ bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) { } } Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val); - const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr(); + const TypeAryPtr* arytype = gvn().type(obj)->as_aryptr(); assert(arytype->is_null_free() == null_free, "inconsistency"); assert(arytype->is_not_null_free() == !null_free, "inconsistency"); set_result(obj); @@ -4971,7 +4971,7 @@ bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) { Node* array_klass = load_object_klass(array); int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset()); Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset); - Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr())); + Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->as_klassptr())); int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset()); Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset); Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered); @@ -5233,8 +5233,8 @@ bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) { klass_node = null_check(klass_node); - const TypeAryPtr* src_t = _gvn.type(original)->is_aryptr(); - const TypeKlassPtr* dest_klass_t = _gvn.type(klass_node)->is_klassptr(); + const TypeAryPtr* src_t = _gvn.type(original)->as_aryptr(); + const TypeKlassPtr* dest_klass_t = _gvn.type(klass_node)->as_klassptr(); Node* bailout_ctrl; if (should_bail_out_on_non_ref_arrays(src_t, dest_klass_t)) { @@ -5309,12 +5309,12 @@ bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) { // check can be optimized if we know something on the type of // the input array from type speculation. if (_gvn.type(klass_node)->singleton()) { - const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr(); - const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr(); + const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->as_klassptr(); + const TypeKlassPtr* superk = _gvn.type(klass_node)->as_klassptr(); int test = C->static_subtype_check(superk, subk); if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) { - const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr(); + const TypeOopPtr* t_original = _gvn.type(original)->as_oopptr(); if (t_original->speculative_type() != nullptr) { original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true); } @@ -5396,7 +5396,7 @@ bool LibraryCallKit::should_bail_out_on_non_ref_arrays(const TypeAryPtr* src_typ // We could have abstract flat value class arrays whose layout we don't know. Bail out. const bool can_src_be_abstract_flat_value_class_array = src_maybe_flat && !src_type->elem()->is_valueklassptr(); const bool can_dest_be_abstract_flat_value_class_array = dest_maybe_flat && - !dest_ary_klass_type->elem()->is_instklassptr()->instance_klass()->is_value_klass(); + !dest_ary_klass_type->elem()->as_instklassptr()->instance_klass()->is_value_klass(); if (can_src_be_abstract_flat_value_class_array || can_dest_be_abstract_flat_value_class_array) { return true; } @@ -5411,7 +5411,7 @@ bool LibraryCallKit::should_bail_out_on_non_ref_arrays(const TypeAryPtr* src_typ } const bool can_src_be_flat_with_oops = src_maybe_flat && src_type->elem()->value_klass()->contains_oops(); - const bool can_dest_be_flat_with_oops = dest_maybe_flat && dest_ary_klass_type->elem()->is_instklassptr()->instance_klass()->as_value_klass()->contains_oops(); + const bool can_dest_be_flat_with_oops = dest_maybe_flat && dest_ary_klass_type->elem()->as_instklassptr()->instance_klass()->as_value_klass()->contains_oops(); if (can_src_be_flat_with_oops || can_dest_be_flat_with_oops) { return true; } @@ -5778,7 +5778,7 @@ IfNode* LibraryCallKit::hashcode_fast_path_if_from_identity_hash_code_call(Phase if (!node->is_Con()) return false; TypeNode* con = node->as_Type(); assert(con->type()->is_intptr_t(), ""); - return con->type()->is_intptr_t()->is_con(in_bytes(n)); + return con->type()->as_intptr_t()->is_con(in_bytes(n)); }; assert(call->in(TypeFunc::Control) != nullptr, ""); @@ -5790,9 +5790,7 @@ IfNode* LibraryCallKit::hashcode_fast_path_if_from_identity_hash_code_call(Phase IfProjNode* if_proj = region->in(i)->as_IfProj(); if (if_proj->_con != 1) continue; - assert(if_proj->in(0) != nullptr, ""); - assert(if_proj->in(0)->is_If(), ""); - IfNode* iff = if_proj->in(0)->as_If(); + IfNode* iff = Node::as(if_proj->in(0)); assert(iff->in(1) != nullptr, ""); if (!iff->in(1)->is_Bool()) continue; @@ -5810,8 +5808,7 @@ IfNode* LibraryCallKit::hashcode_fast_path_if_from_identity_hash_code_call(Phase LoadNode* load_offset = cmp_i->in(1)->as_Load(); if (!cmp_i->in(2)->is_ConI()) continue; ConINode* zero_i = cmp_i->in(2)->as_ConI(); - assert(zero_i->type()->is_int() != nullptr, ""); - if (!zero_i->type()->is_int()->is_con(0)) continue; + if (!zero_i->type()->as_int()->is_con(0)) continue; assert(load_offset->in(2) != nullptr, ""); if (!load_offset->in(2)->is_AddP()) continue; @@ -5833,7 +5830,7 @@ IfNode* LibraryCallKit::hashcode_fast_path_if_from_identity_hash_code_call(Phase assert(members_addr_add->in(AddPNode::Address) != nullptr, ""); assert(members_addr_add->in(AddPNode::Offset) != nullptr, ""); if (!members_addr_add->in(AddPNode::Base)->is_top()) continue; - if (!phase->type(members_addr_add->in(AddPNode::Address))->isa_instklassptr()) continue; + if (!phase->type(members_addr_add->in(AddPNode::Address))->is_instklassptr()) continue; if (!is_con_offset(members_addr_add->in(AddPNode::Offset), ValueKlass::adr_members_offset())) continue; return iff; @@ -5996,7 +5993,7 @@ bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) { C->set_has_split_ifs(true); // Has chance for split-if optimization result = phi; - assert(result->bottom_type()->isa_long(), "must be"); + assert(result->bottom_type()->is_long(), "must be"); break; } @@ -6037,7 +6034,7 @@ bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) { C->set_has_split_ifs(true); // Has chance for split-if optimization result = phi; - assert(result->bottom_type()->isa_int(), "must be"); + assert(result->bottom_type()->is_int(), "must be"); break; } @@ -6133,9 +6130,9 @@ bool LibraryCallKit::inline_unsafe_copyMemory() { // Adjust memory effects of the runtime call based on input values. if (!has_wide_mem(_gvn, src_addr, src_base) && !has_wide_mem(_gvn, dst_addr, dst_base)) { - dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory + dst_type = _gvn.type(dst_addr)->as_ptr(); // narrow out memory - const TypePtr* src_type = _gvn.type(src_addr)->is_ptr(); + const TypePtr* src_type = _gvn.type(src_addr)->as_ptr(); if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) { flags |= RC_NARROW_MEM; // narrow in memory } @@ -6187,7 +6184,7 @@ bool LibraryCallKit::inline_unsafe_setMemory() { // Adjust memory effects of the runtime call based on input values. if (!has_wide_mem(_gvn, dst_addr, dst_base)) { - dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory + dst_type = _gvn.type(dst_addr)->as_ptr(); // narrow out memory flags |= RC_NARROW_MEM; // narrow in memory } @@ -6221,7 +6218,7 @@ void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, b // Object.clone() invocation), initialize the array within the allocation. // This is needed because some GCs (e.g. ZGC) might fall back in this case // to a runtime clone call that assumes fully initialized source arrays. - (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) { + (!is_array || obj->get_ptr_type()->is_aryptr())) { // We will be completely responsible for initializing this object - // mark Initialize node as complete. alloc = AllocateNode::Ideal_allocation(alloc_obj); @@ -6285,7 +6282,7 @@ bool LibraryCallKit::inline_native_clone(bool is_virtual) { obj = null_check_receiver(); if (stopped()) return true; - const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); + const TypeOopPtr* obj_type = _gvn.type(obj)->as_oopptr(); if (obj_type->is_valueklassptr()) { // If the object to clone is a value type, we can simply return it (i.e. a nop) since value types have // no identity. But we first need to check whether the value class is actually implementing the Cloneable @@ -6325,8 +6322,8 @@ bool LibraryCallKit::inline_native_clone(bool is_virtual) { ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass(); if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem && !spec_ik->has_injected_fields()) { - if (!obj_type->isa_instptr() || - obj_type->is_instptr()->instance_klass()->has_subklass()) { + if (!obj_type->is_instptr() || + obj_type->as_instptr()->instance_klass()->has_subklass()) { obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false); } } @@ -6552,7 +6549,7 @@ SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocati sfpt->init_req(i, alloc->in(i)); } int adjustment = 1; - const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr(); + const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->as_aryklassptr(); if (ary_klass_ptr->is_null_free()) { // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which // also requires the componentType and initVal on stack for re-execution. @@ -6569,7 +6566,7 @@ SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocati // Re-create and push the initVal. Node* init_val = alloc->in(AllocateNode::InitValue); if (init_val == nullptr) { - init_val = ValueTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_value_klass()); + init_val = ValueTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->as_instklassptr()->instance_klass()->as_value_klass()); } else if (UseCompressedOops) { init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr())); } @@ -6661,9 +6658,9 @@ void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, No // Update memory as done in GraphKit::set_output_for_allocation() const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength)); - const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_exact_instance_type(); - if (ary_type->isa_aryptr() && length_type != nullptr) { - ary_type = ary_type->is_aryptr()->cast_to_size(length_type); + const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->as_klassptr()->as_exact_instance_type(); + if (ary_type->is_aryptr() && length_type != nullptr) { + ary_type = ary_type->as_aryptr()->cast_to_size(length_type); } const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot); int elemidx = C->get_alias_index(telemref); @@ -7002,8 +6999,8 @@ bool LibraryCallKit::inline_arraycopy() { } if (has_src && has_dest && can_emit_guards) { - BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type(); - BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type(); + BasicType src_elem = top_src->elem()->array_element_basic_type(); + BasicType dest_elem = top_dest->elem()->array_element_basic_type(); if (is_reference_type(src_elem, true)) src_elem = T_OBJECT; if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT; @@ -7105,16 +7102,16 @@ bool LibraryCallKit::inline_arraycopy() { } if (Arguments::is_valhalla_enabled()) { - // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays. + // TODO 8251971: Add speculative layout checks for src and dest array to enable more optimization opportunities. // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted Node* src_klass = load_object_klass(src); Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset())); Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, - _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT, + _gvn.type(adr_prop_src)->as_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset())); Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, - _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT, + _gvn.type(adr_prop_dest)->as_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted(); @@ -7128,7 +7125,7 @@ bool LibraryCallKit::inline_arraycopy() { Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne)); generate_fair_guard(tst, slow_region); - // TODO 8251971 This is too strong + // TODO 8397038: This is too strong if (UseArrayFlattening) { generate_fair_guard(flat_array_test(src), slow_region); generate_fair_guard(flat_array_test(dest), slow_region); @@ -7685,7 +7682,7 @@ bool LibraryCallKit::inline_vectorizedMismatch() { BasicType elem_bt = T_ILLEGAL; - const TypeInt* scale_t = _gvn.type(scale)->is_int(); + const TypeInt* scale_t = _gvn.type(scale)->as_int(); if (scale_t->is_con()) { switch (scale_t->get_con()) { case 0: elem_bt = T_BYTE; break; @@ -7721,8 +7718,8 @@ bool LibraryCallKit::inline_vectorizedMismatch() { if (!stopped()) { Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin))); - const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr(); - const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr(); + const TypePtr* obja_adr_t = _gvn.type(obja_adr)->as_ptr(); + const TypePtr* objb_adr_t = _gvn.type(objb_adr)->as_ptr(); Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t)); Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t)); @@ -7784,7 +7781,7 @@ bool LibraryCallKit::inline_vectorizedHashCode() { return false; // failed input validation } - const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int(); + const TypeInt* basic_type_t = _gvn.type(basic_type)->as_int(); if (!basic_type_t->is_con()) { return false; // Only intrinsify if mode argument is constant } @@ -8180,7 +8177,7 @@ bool LibraryCallKit::inline_reference_clear0(bool is_phantom) { DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE; decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF); Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset()); - const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr(); + const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->as_ptr(); const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass()); Node* referent = access_load_at(reference_obj, @@ -10309,7 +10306,7 @@ Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciFi set_control(null_ctl); return nullptr; } - assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, ""); + assert(not_null_box->bottom_type()->as_instptr()->maybe_null() == false, ""); const TypePtr* adr_type = C->alias_type(field)->adr_type(); Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes()); return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP); @@ -10324,7 +10321,7 @@ Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciFiel Node* box = new_instance(klass_node); Node* value_field = basic_plus_adr(box, field->offset_in_bytes()); - const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr(); + const TypePtr* value_adr_type = value_field->bottom_type()->as_ptr(); Node* field_store = _gvn.transform(access_store_at(box, value_field, diff --git a/src/hotspot/share/opto/loopPredicate.cpp b/src/hotspot/share/opto/loopPredicate.cpp index 537e2ef97053..b7a5789f6446 100644 --- a/src/hotspot/share/opto/loopPredicate.cpp +++ b/src/hotspot/share/opto/loopPredicate.cpp @@ -620,7 +620,7 @@ BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl, const int scale, Node* offset predString->print("- %d) ", stride); } // Check if (limit - stride) may overflow - const TypeInt* limit_type = _igvn.type(limit)->isa_int(); + const TypeInt* limit_type = _igvn.type(limit)->as_int(); jint limit_lo = limit_type->_lo; jint limit_hi = limit_type->_hi; if ((stride > 0 && (java_subtract(limit_lo, stride) < limit_lo)) || @@ -687,7 +687,7 @@ BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl, const int scale, Node* offset } } // Check if (max_idx_expr + offset) may overflow - const TypeInt* offset_type = _igvn.type(offset)->isa_int(); + const TypeInt* offset_type = _igvn.type(offset)->as_int(); jint lo = java_add(idx_type->_lo, offset_type->_lo); jint hi = java_add(idx_type->_hi, offset_type->_hi); if (overflow || (lo > hi) || @@ -763,7 +763,7 @@ bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree* loop if (head->is_CountedLoop()) { CountedLoopNode* cl = head->as_CountedLoop(); if (cl->phi() != nullptr) { - const TypeInt* t = _igvn.type(cl->phi())->is_int(); + const TypeInt* t = _igvn.type(cl->phi())->as_int(); float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS((float)cl->stride_con()); if (worst_case_trip_cnt < loop_trip_cnt) { loop_trip_cnt = worst_case_trip_cnt; @@ -1034,7 +1034,7 @@ bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree* loop, const IfP Node* idx = cmp->in(1); assert(!invar.is_invariant(idx), "index is variant"); Node* range = cmp->in(2); - assert(range->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(range)->is_int()->_lo >= 0, "must be"); + assert(range->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(range)->as_int()->_lo >= 0, "must be"); assert(invar.is_invariant(range), "range must be invariant"); int scale = 1; Node* offset = zero; diff --git a/src/hotspot/share/opto/loopTransform.cpp b/src/hotspot/share/opto/loopTransform.cpp index b1180e93ceab..31a183a91f5b 100644 --- a/src/hotspot/share/opto/loopTransform.cpp +++ b/src/hotspot/share/opto/loopTransform.cpp @@ -54,8 +54,7 @@ //------------------------------is_loop_exit----------------------------------- // Given an IfNode, return the loop-exiting projection or null if both // arms remain in the loop. -Node *IdealLoopTree::is_loop_exit(Node *iff) const { - assert(iff->is_If(), "not an If: %s", iff->Name()); +Node* IdealLoopTree::is_loop_exit(const IfNode* iff) const { assert(is_member(_phase->get_loop(iff)), "not related"); if (iff->outcnt() != 2) { @@ -84,8 +83,8 @@ IfFalseNode* IdealLoopTree::unique_loop_exit_proj_or_null() { assert(_phase->is_dominator(head(), tail()), "sanity"); for (Node* ctrl = tail(); ctrl != head(); ctrl = ctrl->in(0)) { assert(is_member(_phase->get_loop(ctrl)), "sanity"); - if (ctrl->is_If()) { - if (!is_loop_exit(ctrl->as_If())) { + if (IfNode* iff = ctrl->isa_If(); iff != nullptr) { + if (!is_loop_exit(iff)) { continue; // local branch } else if (ctrl != loop_end) { return nullptr; // multiple loop exits @@ -178,8 +177,8 @@ void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase, BasicType loop_bt) Node* limit_n = cl->limit(); if (init_n != nullptr && limit_n != nullptr) { jlong stride_con = cl->stride_con(); - const TypeInteger* init_type = phase->_igvn.type(init_n)->is_integer(loop_bt); - const TypeInteger* limit_type = phase->_igvn.type(limit_n)->is_integer(loop_bt); + const TypeInteger* init_type = phase->_igvn.type(init_n)->as_integer(loop_bt); + const TypeInteger* limit_type = phase->_igvn.type(limit_n)->as_integer(loop_bt); // compute trip count // It used to be computed as: @@ -215,8 +214,8 @@ void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase, BasicType loop_bt) #ifdef ASSERT if (loop_bt == T_INT) { // Use longs to avoid integer overflow. - jlong init_con = (stride_con > 0) ? init_type->is_int()->_lo : init_type->is_int()->_hi; - jlong limit_con = (stride_con > 0) ? limit_type->is_int()->_hi : limit_type->is_int()->_lo; + jlong init_con = (stride_con > 0) ? init_type->as_int()->_lo : init_type->as_int()->_hi; + jlong limit_con = (stride_con > 0) ? limit_type->as_int()->_hi : limit_type->as_int()->_lo; int stride_m = stride_con - (stride_con > 0 ? 1 : -1); jlong trip_count = (limit_con - init_con + stride_m) / stride_con; // The loop body is always executed at least once even if init >= limit (for stride_con > 0) or @@ -247,7 +246,7 @@ float IdealLoopTree::compute_profile_trip_cnt_helper(Node* n) { IfNode *iff = n->as_If(); if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) { Node *exit = is_loop_exit(iff); - if (exit) { + if (exit != nullptr) { float exit_prob = iff->_prob; if (exit->Opcode() == Op_IfFalse) { exit_prob = 1.0 - exit_prob; @@ -288,22 +287,22 @@ void IdealLoopTree::compute_profile_trip_cnt(PhaseIdealLoop *phase) { float trip_cnt = (float)max_jint; // default is big Node* back = head->in(LoopNode::LoopBackControl); + IfNode* back_if = nullptr; while (back != head) { - if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) && - back->in(0) && - back->in(0)->is_If() && - back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN && - back->in(0)->as_If()->_prob != PROB_UNKNOWN && - (back->Opcode() == Op_IfTrue ? 1-back->in(0)->as_If()->_prob : back->in(0)->as_If()->_prob) > PROB_MIN) { - break; + if (back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) { + back_if = Node::isa(back->in(0)); + if (back_if != nullptr && + back_if->_fcnt != COUNT_UNKNOWN && + back_if->_prob != PROB_UNKNOWN && + (back->Opcode() == Op_IfTrue ? 1 - back_if->_prob : back_if->_prob) > PROB_MIN) { + break; + } } back = phase->idom(back); } if (back != head) { - assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) && - back->in(0), "if-projection exists"); - IfNode* back_if = back->in(0)->as_If(); - float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : (1 - back_if->_prob)); + assert(back_if != nullptr, "if-projection exists"); + float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : 1 - back_if->_prob); // Now compute a loop exit count float loop_exit_cnt = 0.0f; @@ -445,7 +444,7 @@ Node* IdealLoopTree::reassociate_add_sub_cmp(Node* n1, int inv1_idx, int inv2_id neg_inv2 = !neg_inv2; } - bool is_int = n2->bottom_type()->isa_int() != nullptr; + bool is_int = n2->bottom_type()->is_int(); Node* inv1_c = phase->get_ctrl(inv1); Node* n_inv1; if (neg_inv1) { @@ -640,7 +639,7 @@ uint IdealLoopTree::estimate_peeling(PhaseIdealLoop *phase) { test->Opcode() == Op_ParsePredicate, "Check this code when new subtype is added"); // Condition is not a member of this loop? - if (!is_member(phase->get_loop(ctrl)) && is_loop_exit(test)) { + if (!is_member(phase->get_loop(ctrl)) && is_loop_exit(test->as_If())) { return estimate; // Found reason to peel! } } @@ -1283,7 +1282,7 @@ bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) { Node* phi = cl->phi(); if (phi != nullptr) { assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi."); - const TypeInt* iv_type = phase->_igvn.type(phi)->is_int(); + const TypeInt* iv_type = phase->_igvn.type(phi)->as_int(); int next_stride = stride_con * 2; // stride after this unroll if (next_stride > 0) { if (iv_type->_lo > max_jint - next_stride || // overflow @@ -1301,7 +1300,7 @@ bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) { // After unroll limit will be adjusted: new_limit = limit-stride. // Bailout if adjustment overflow. - const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int(); + const TypeInt* limit_type = phase->_igvn.type(limit_n)->as_int(); if ((stride_con > 0 && ((min_jint + stride_con) > limit_type->_hi)) || (stride_con < 0 && ((max_jint + stride_con) < limit_type->_lo))) return false; // overflow @@ -1338,7 +1337,7 @@ bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) { case Op_VectorCastF2X: case Op_PopCountVI: case Op_PopCountVL: { - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); body_size += Matcher::vector_op_pre_select_sz_estimate(n->Opcode(), vt->element_basic_type(), vt->length()); } break; case Op_StrComp: @@ -1521,7 +1520,7 @@ bool IdealLoopTree::policy_range_check(PhaseIdealLoop* phase, bool provisional, // Found a test like 'trip+off vs limit'. Test is an IfNode, has two (2) // projections. If BOTH are in the loop we need loop unswitching instead // of iteration splitting. - if (is_loop_exit(iff)) { + if (is_loop_exit(iff->as_If())) { // Found valid reason to split iterations (if there is room). // NOTE: Usually a gross overestimate. // Long range checks cause the loop to be transformed in a loop nest which only causes a fixed number of nodes @@ -1620,12 +1619,12 @@ void PhaseIdealLoop::cast_incr_before_loop(Node* incr, Node* ctrl, CountedLoopNo void PhaseIdealLoop::ensure_zero_trip_guard_proj(Node* node, bool is_main_loop) { assert(node->is_IfProj(), "must be the zero trip guard If node"); Node* zer_bol = node->in(0)->in(1); - assert(zer_bol != nullptr && zer_bol->is_Bool(), "must be Bool"); + assert(Node::is(zer_bol), "must be Bool"); Node* zer_cmp = zer_bol->in(1); - assert(zer_cmp != nullptr && zer_cmp->Opcode() == Op_CmpI, "must be CmpI"); + assert(Node::is_exact(zer_cmp), "must be CmpI"); // For the main loop, the opaque node is the second input to zer_cmp, for the post loop it's the first input node Node* zer_opaq = zer_cmp->in(is_main_loop ? 2 : 1); - assert(zer_opaq != nullptr && zer_opaq->Opcode() == Op_OpaqueZeroTripGuard, "must be OpaqueZeroTripGuard"); + assert(Node::is_exact(zer_opaq), "must be OpaqueZeroTripGuard"); } #endif @@ -1906,7 +1905,7 @@ void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree* loop, Node_Listis_Store(), "starting point should be a store node"); + assert(Node::is(store), "starting point should be a store node"); // Follow the memory uses until we get out of the loop. // Store nodes in the outer loop body were moved by PhaseIdealLoop::try_move_store_after_loop. // Because of the conditions in try_move_store_after_loop (no other usage in the loop body @@ -2296,7 +2295,7 @@ void PhaseIdealLoop::do_unroll(IdealLoopTree* loop, Node_List& old_new, bo assert(opaq != nullptr && opaq->in(1) == limit, "sanity"); // Verify that policy_unroll result is still valid. - const TypeInt* limit_type = _igvn.type(limit)->is_int(); + const TypeInt* limit_type = _igvn.type(limit)->as_int(); assert((stride_con > 0 && ((min_jint + stride_con) <= limit_type->_hi)) || (stride_con < 0 && ((max_jint + stride_con) >= limit_type->_lo)), "sanity"); @@ -2542,8 +2541,8 @@ Node* PhaseIdealLoop::adjust_limit(bool is_positive_stride, Node* scale, Node* o // holds true in the main-loop. Stride, scale, offset and limit are all loop // invariant. Further, stride and scale are constants (offset and limit often are). void PhaseIdealLoop::add_constraint(jlong stride_con, jlong scale_con, Node* offset, Node* low_limit, Node* upper_limit, Node* pre_ctrl, Node** pre_limit, Node** main_limit) { - assert(_igvn.type(offset)->isa_long() != nullptr && _igvn.type(low_limit)->isa_long() != nullptr && - _igvn.type(upper_limit)->isa_long() != nullptr, "arguments should be long values"); + assert(_igvn.type(offset)->is_long() && _igvn.type(low_limit)->is_long() && + _igvn.type(upper_limit)->is_long(), "arguments should be long values"); // For a positive stride, we need to reduce the main-loop limit and // increase the pre-loop limit. This is reversed for a negative stride. @@ -2623,11 +2622,11 @@ void PhaseIdealLoop::add_constraint(jlong stride_con, jlong scale_con, Node* off // See grammar specification in PhaseIdealLoop::is_scaled_iv_plus_offset(). bool PhaseIdealLoop::is_iv(Node* exp, Node* iv, BasicType bt) { exp = exp->uncast(); - if (exp == iv && iv->bottom_type()->isa_integer(bt)) { + if (exp == iv && iv->bottom_type()->is_integer(bt)) { return true; } - if (bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L && exp->in(1)->uncast() == iv) { + if (bt == T_LONG && iv->bottom_type()->is_int() && exp->Opcode() == Op_ConvI2L && exp->in(1)->uncast() == iv) { return true; } return false; @@ -2660,7 +2659,7 @@ bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, BasicType bt, jlong* p_sc } return true; } - if (bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L) { + if (bt == T_LONG && iv->bottom_type()->is_int() && exp->Opcode() == Op_ConvI2L) { // Risk for short scaling: avoid long range-check transformations, because // the current implementation (transform_long_range_checks) does not protect // against overflow. @@ -3192,13 +3191,13 @@ void PhaseIdealLoop::do_range_check(IdealLoopTree* loop) { // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant. for (uint i = 0; i < loop->_body.size(); i++) { - Node *iff = loop->_body[i]; - if (iff->Opcode() == Op_If || - iff->Opcode() == Op_RangeCheck) { // Test? + if (IfNode* iff = Node::isa(loop->_body[i]); + iff != nullptr && + (iff->Opcode() == Op_If || iff->Opcode() == Op_RangeCheck)) { // Test? // Test is an IfNode, has 2 projections. If BOTH are in the loop // we need loop unswitching instead of iteration splitting. - Node *exit = loop->is_loop_exit(iff); - if (!exit) continue; + Node* exit = loop->is_loop_exit(iff); + if (exit == nullptr) continue; int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0; // Get boolean condition to test @@ -3382,8 +3381,7 @@ void PhaseIdealLoop::do_range_check(IdealLoopTree* loop) { Node* kill_con = intcon(1-flip); _igvn.replace_input_of(iff, 1, kill_con); // Find surviving projection - assert(iff->is_If(), ""); - ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip); + ProjNode* dp = iff->proj_out(1-flip); // Find loads off the surviving projection; remove their control edge for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) { Node* cd = dp->fast_out(i); // Control-dependent node @@ -3437,7 +3435,7 @@ void PhaseIdealLoop::do_range_check(IdealLoopTree* loop) { _igvn.replace_input_of(main_bol, 1, main_cmp); } assert(main_limit == cl->limit() || get_ctrl(main_limit) == new_limit_ctrl, "wrong control for added limit"); - const TypeInt* orig_limit_t = _igvn.type(orig_limit)->is_int(); + const TypeInt* orig_limit_t = _igvn.type(orig_limit)->as_int(); bool upward = cl->stride_con() > 0; // The new loop limit is <= (for an upward loop) >= (for a downward loop) than the orig limit. // The expression that computes the new limit may be too complicated and the computed type of the new limit @@ -3677,8 +3675,8 @@ bool IdealLoopTree::do_remove_empty_loop(PhaseIdealLoop *phase) { bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop(); if (needs_guard) { // Skip guard if values not overlap. - const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int(); - const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int(); + const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->as_int(); + const TypeInt* limit_t = phase->_igvn.type(cl->limit())->as_int(); int stride_con = cl->stride_con(); if (stride_con > 0) { needs_guard = (init_t->_hi >= limit_t->_lo); @@ -4188,7 +4186,7 @@ bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& st Node* value = n->in(MemNode::ValueIn); if (!lpt->is_invariant(value)) { msg = "variant store value"; - } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) { + } else if (!_igvn.type(n->in(MemNode::Address))->is_aryptr()) { msg = "not array address"; } store = n; @@ -4237,7 +4235,7 @@ bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& st // Make sure there is an appropriate fill routine BasicType t = msg == nullptr ? - store->out_adr_type()->isa_aryptr()->elem()->array_element_basic_type() : T_VOID; + store->out_adr_type()->as_aryptr()->elem()->array_element_basic_type() : T_VOID; const char* fill_name; if (msg == nullptr && StubRoutines::select_fill_function(t, false, fill_name) == nullptr) { @@ -4484,7 +4482,7 @@ bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) { #endif } - BasicType t = store->out_adr_type()->isa_aryptr()->elem()->array_element_basic_type(); + BasicType t = store->out_adr_type()->as_aryptr()->elem()->array_element_basic_type(); bool aligned = false; if (offset != nullptr && head->init_trip()->is_Con()) { int element_size = type2aelembytes(t); diff --git a/src/hotspot/share/opto/loopUnswitch.cpp b/src/hotspot/share/opto/loopUnswitch.cpp index 4f98b7b55a37..20015b376624 100644 --- a/src/hotspot/share/opto/loopUnswitch.cpp +++ b/src/hotspot/share/opto/loopUnswitch.cpp @@ -216,9 +216,9 @@ void PhaseIdealLoop::collect_flat_array_checks(const IdealLoopTree* loop, Node_L assert(flat_array_checks.size() == 0, "should be empty initially"); for (uint i = 0; i < loop->_body.size(); i++) { Node* next = loop->_body.at(i); - if (next->is_If() && next->as_If()->is_flat_array_check(&_igvn) && loop->is_invariant(next->in(1)) && - !loop->is_loop_exit(next)) { - flat_array_checks.push(next->as_If()); + if (IfNode* iff = next->isa_If(); iff != nullptr && iff->is_flat_array_check(&_igvn) && loop->is_invariant(next->in(1)) && + !loop->is_loop_exit(iff)) { + flat_array_checks.push(iff); } } } diff --git a/src/hotspot/share/opto/loopnode.cpp b/src/hotspot/share/opto/loopnode.cpp index 2869e1dde0f4..b1caf9596a09 100644 --- a/src/hotspot/share/opto/loopnode.cpp +++ b/src/hotspot/share/opto/loopnode.cpp @@ -83,7 +83,7 @@ bool LoopNode::is_valid_counted_loop(BasicType bt) const { le->true_proj_or_null() == l->in(LoopNode::LoopBackControl)) { Node* phi = l->phi(); IfFalseNode* exit = le->false_proj_or_null(); - if (exit != nullptr && phi != nullptr && phi->is_Phi() && + if (exit != nullptr && is(phi) && phi->in(LoopNode::LoopBackControl) == l->incr() && le->loopnode() == l && le->stride_is_con()) { return true; @@ -179,7 +179,7 @@ Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) { // that doesn't branch to an UNC, we stop. The code that process // expensive nodes will notice the loop and skip over it to try to // move the node further up. - if (ctl->is_CountedLoop() && ctl->in(1) != nullptr && ctl->in(1)->in(0) != nullptr && ctl->in(1)->in(0)->is_If()) { + if (ctl->is_CountedLoop() && ctl->in(1) != nullptr && Node::is(ctl->in(1)->in(0))) { if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern()) { break; } @@ -686,7 +686,7 @@ SafePointNode* PhaseIdealLoop::find_safepoint(Node* back_control, const Node* he // code that relies on mm. Clear that extra state here. if (mms.alias_idx() != Compile::AliasIdxBot && (loop != get_loop(ctrl_or_self(mms.memory())) || - (mms.adr_type()->isa_oop_ptr() && mms.adr_type()->is_known_instance()))) { + (mms.adr_type()->is_oopptr() && mms.adr_type()->is_known_instance()))) { mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory()); } } @@ -860,8 +860,8 @@ bool PhaseIdealLoop::create_loop_nest(IdealLoopTree* loop, Node_List& old_ // Take what we know about the number of iterations of the long counted loop into account when computing the limit of // the inner loop. Node* init = head->init_trip(); - const TypeInteger* lo = _igvn.type(init)->is_integer(bt); - const TypeInteger* hi = _igvn.type(limit)->is_integer(bt); + const TypeInteger* lo = _igvn.type(init)->as_integer(bt); + const TypeInteger* hi = _igvn.type(limit)->as_integer(bt); if (stride_con < 0) { swap(lo, hi); } @@ -1282,7 +1282,7 @@ bool PhaseIdealLoop::try_make_short_running_loop(IdealLoopTree* loop, jint strid // transformation happens by the time the counted loop is created (in a subsequent pass of loop opts), C2 knows // enough about the loop's limit that it doesn't try to add loop limit check predicates. const Predicates predicates(entry_control); - const TypeLong* new_limit_t = new_limit->Value(&_igvn)->is_long(); + const TypeLong* new_limit_t = new_limit->Value(&_igvn)->as_long(); new_limit = ConstraintCastNode::make_cast_for_basic_type(predicates.entry(), new_limit, TypeLong::make(0, new_limit_t->_hi, new_limit_t->_widen), ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, bt); @@ -3013,7 +3013,7 @@ bool CountedLoopConverter::stress_long_counted_loop() { } Node* in_clone = old_new[in->_idx]; if (in_clone == nullptr) { - assert(igvn->type(in)->isa_int(), ""); + assert(igvn->type(in)->is_int(), ""); in_clone = new ConvI2LNode(in); igvn->register_new_node_with_optimizer(in_clone); _phase->set_subtree_ctrl(in_clone, false); @@ -3100,7 +3100,7 @@ bool CountedLoopConverter::is_counted_loop() { // Check iv is not overflowing Node* init_trip = _structure.phi()->in(LoopNode::EntryControl); - const TypeInteger* init_t = igvn->type(init_trip)->is_integer(_iv_bt); + const TypeInteger* init_t = igvn->type(init_trip)->as_integer(_iv_bt); if (is_iv_overflowing(init_t, stride_con, _structure.iv_incr().phi_incr(), _structure.exit_test().mask())) { return false; } @@ -3298,7 +3298,7 @@ bool CountedLoopConverter::is_counted_loop() { // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii) // again and can skip the predicate. - const TypeInteger* limit_t = igvn->type(_structure.limit())->is_integer(_iv_bt); + const TypeInteger* limit_t = igvn->type(_structure.limit())->as_integer(_iv_bt); StrideOverflowState stride_overflow_state = check_stride_overflow(_structure.final_limit_correction(), limit_t, _iv_bt); Node* init_control = _head->in(LoopNode::EntryControl); @@ -3435,7 +3435,7 @@ bool CountedLoopConverter::is_iv_overflowing(const TypeInteger* init_t, jlong st bool CountedLoopConverter::LoopStructure::is_infinite_loop() const { PhaseIterGVN& igvn = _phase->igvn(); - const TypeInteger* limit_t = igvn.type(limit())->is_integer(_iv_bt); + const TypeInteger* limit_t = igvn.type(limit())->as_integer(_iv_bt); if (_truncated_increment.outer_trunc() != nullptr) { // When there is a truncation, we must be sure that after the truncation @@ -3455,7 +3455,7 @@ bool CountedLoopConverter::LoopStructure::is_infinite_loop() const { // If the array is longer then this is an endless loop // - No transformation can be done. - const TypeInteger* incr_t = igvn.type(_iv_incr.incr())->is_integer(_iv_bt); + const TypeInteger* incr_t = igvn.type(_iv_incr.incr())->as_integer(_iv_bt); if (limit_t->hi_as_long() > incr_t->hi_as_long()) { // if the limit can have a higher value than the increment (before the phi) return true; @@ -3722,7 +3722,7 @@ IdealLoopTree* CountedLoopConverter::convert() { outer_le->set_req(0, sfpt_clone); Node* polladdr = sfpt_clone->in(TypeFunc::Parms); - if (polladdr != nullptr && polladdr->is_Load()) { + if (Node::is(polladdr)) { // Polling load should be pinned outside inner loop. Node* new_polladdr = polladdr->clone(); new_polladdr->set_req(0, iffalse); @@ -3807,7 +3807,7 @@ bool CountedLoopConverter::has_dominating_loop_limit_check(Node* init_trip, Node IfTrueNode* if_true = new IfTrueNode(iff); Node* dominated_iff = _igvn.transform(iff); // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node). - const bool found_dominating_test = dominated_iff != nullptr && dominated_iff->is_ConI(); + const bool found_dominating_test = Node::is(dominated_iff); // Kill the If with its projections again in the next IGVN round by cutting it off from the graph. _igvn.replace_input_of(iff, 0, _phase->C->top()); @@ -3892,7 +3892,7 @@ void LoopNode::verify_strip_mined(int expect_skeleton) const { Node* inner_out = sfpt->in(0); CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd(); assert(cle == inner->loopexit_or_null(), "mismatch"); - bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0; + bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->as_int()->get_con() == 0; if (has_skeleton) { assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node"); assert(outer->outcnt() == 2, "only control nodes"); @@ -3970,7 +3970,7 @@ void CountedLoopNode::dump_spec(outputStream *st) const { //============================================================================= jlong BaseCountedLoopEndNode::stride_con() const { - return stride()->bottom_type()->is_integer(bt())->get_con_as_long(bt()); + return stride()->bottom_type()->as_integer(bt())->get_con_as_long(bt()); } @@ -3993,14 +3993,14 @@ const Type* LoopLimitNode::Value(PhaseGVN* phase) const { if (limit_t == Type::TOP) return Type::TOP; if (stride_t == Type::TOP) return Type::TOP; - int stride_con = stride_t->is_int()->get_con(); + int stride_con = stride_t->as_int()->get_con(); if (stride_con == 1) return bottom_type(); // Identity - if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) { + if (init_t->as_int()->is_con() && limit_t->as_int()->is_con()) { // Use jlongs to avoid integer overflow. - jlong init_con = init_t->is_int()->get_con(); - jlong limit_con = limit_t->is_int()->get_con(); + jlong init_con = init_t->as_int()->get_con(); + jlong limit_con = limit_t->as_int()->get_con(); int stride_m = stride_con - (stride_con > 0 ? 1 : -1); jlong trip_count = (limit_con - init_con + stride_m)/stride_con; jlong final_con = init_con + stride_con*trip_count; @@ -4032,7 +4032,7 @@ Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) { phase->type(in(Stride)) == Type::TOP) return nullptr; // Dead - int stride_con = phase->type(in(Stride))->is_int()->get_con(); + int stride_con = phase->type(in(Stride))->as_int()->get_con(); if (stride_con == 1) return nullptr; // Identity @@ -4043,8 +4043,8 @@ Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) { return nullptr; } - const TypeInt* init_t = phase->type(in(Init) )->is_int(); - const TypeInt* limit_t = phase->type(in(Limit))->is_int(); + const TypeInt* init_t = phase->type(in(Init) )->as_int(); + const TypeInt* limit_t = phase->type(in(Limit))->as_int(); jlong stride_p; jlong lim, ini; julong max; @@ -4108,7 +4108,7 @@ Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) { //------------------------------Identity--------------------------------------- // If stride == 1 return limit node. Node* LoopLimitNode::Identity(PhaseGVN* phase) { - int stride_con = phase->type(in(Stride))->is_int()->get_con(); + int stride_con = phase->type(in(Stride))->as_int()->get_con(); if (stride_con == 1 || stride_con == -1) return in(Limit); return this; @@ -4139,7 +4139,7 @@ void CountedLoopConverter::TruncatedIncrement::build(Node* expr) { n1->in(2)->is_Con()) { // Unsigned truncation. // Pattern: ((i+1) & mask) - jint mask = n1->in(2)->bottom_type()->is_int()->get_con(); + jint mask = n1->in(2)->bottom_type()->as_int()->get_con(); switch (mask) { case 0x7fff: // Unsigned 15-bit truncation. For historical reasons. t1 = n1; @@ -4149,11 +4149,10 @@ void CountedLoopConverter::TruncatedIncrement::build(Node* expr) { break; } } else if (n1op == Op_RShiftI && - n1->in(1) != nullptr && - n1->in(1)->Opcode() == Op_LShiftI && + Node::is_exact(n1->in(1)) && n1->in(2) == n1->in(1)->in(2) && n1->in(2)->is_Con()) { - jint shift = n1->in(2)->bottom_type()->is_int()->get_con(); + jint shift = n1->in(2)->bottom_type()->as_int()->get_con(); // %%% This check should match any shift in [1..31]. if (shift == 16 || shift == 8) { t1 = n1; @@ -4195,9 +4194,9 @@ IfNode* CountedLoopNode::find_multiversion_if_from_multiversion_fast_main_loop() } LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) { - if (is_strip_mined() && in(EntryControl) != nullptr && in(EntryControl)->is_OuterStripMinedLoop()) { + if (auto osmln = isa(in(EntryControl)); osmln != nullptr && is_strip_mined()) { verify_strip_mined(expect_skeleton); - return in(EntryControl)->as_Loop(); + return osmln; } return this; } @@ -4205,10 +4204,7 @@ LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) { OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const { assert(is_strip_mined(), "not a strip mined loop"); Node* c = in(EntryControl); - if (c == nullptr || c->is_top() || !c->is_OuterStripMinedLoop()) { - return nullptr; - } - return c->as_OuterStripMinedLoop(); + return isa(c); } IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const { @@ -4552,7 +4548,7 @@ void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) { return; } jlong short_scaled_iters = LoopStripMiningIterShortLoop * ABS(stride); - const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int(); + const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->as_int(); jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo; assert(iter_estimate > 0, "broken"); if (iter_estimate <= short_scaled_iters) { @@ -4797,7 +4793,7 @@ bool OuterStripMinedLoopEndNode::is_expanded(PhaseGVN *phase) const { IfTrueNode* backedge = true_proj_or_null(); if (backedge != nullptr) { Node* head = backedge->unique_ctrl_out_or_null(); - if (head != nullptr && head->is_OuterStripMinedLoop()) { + if (is(head)) { if (head->find_out_with(Op_Phi) != nullptr) { return true; } @@ -4830,7 +4826,7 @@ Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) { // } while ( i < 10) // const TypeInt* CountedLoopConverter::filtered_type(Node* n, Node* n_ctrl) { - assert(n && n->bottom_type()->is_int(), "must be int"); + assert(n != nullptr && n->bottom_type()->is_int(), "must be int"); const TypeInt* filtered_t = nullptr; if (!n->is_Phi()) { assert(n_ctrl != nullptr || n_ctrl == _phase->C->top(), "valid control"); @@ -4850,7 +4846,7 @@ const TypeInt* CountedLoopConverter::filtered_type(Node* n, Node* n_ctrl) { if (filtered_t == nullptr) { filtered_t = val_t; } else { - filtered_t = filtered_t->meet(val_t)->is_int(); + filtered_t = filtered_t->meet(val_t)->as_int(); } } else { // We found no constriant, so we have to assume that this path @@ -4863,9 +4859,9 @@ const TypeInt* CountedLoopConverter::filtered_type(Node* n, Node* n_ctrl) { // The filtered type may be worse than what we already know // about n, so take the intersection. - const TypeInt* n_t = _phase->igvn().type(n)->is_int(); + const TypeInt* n_t = _phase->igvn().type(n)->as_int(); if (filtered_t != nullptr) { - n_t = n_t->join(filtered_t)->is_int(); + n_t = n_t->join(filtered_t)->as_int(); } return n_t; } @@ -4877,7 +4873,7 @@ const TypeInt* CountedLoopConverter::filtered_type(Node* n, Node* n_ctrl) { // as if we returned TypeInt::INT. const TypeInt* CountedLoopConverter::filtered_type_from_dominators(Node* val, Node* use_ctrl) { if (val->is_Con()) { - return val->bottom_type()->is_int(); + return val->bottom_type()->as_int(); } uint if_limit = 10; // Max number of dominating if's visited const TypeInt* rtn_t = nullptr; @@ -4896,7 +4892,7 @@ const TypeInt* CountedLoopConverter::filtered_type_from_dominators(Node* val, No rtn_t = if_t; } else { const Type* join_t = rtn_t->join(if_t); - if (!join_t->isa_int()) { + if (!join_t->is_int()) { // We may have encountered multiple if conditions, that have no // overlap, and produce an empty/top type. Returning nullptr // is conservative, it means we do not constrain the type, which @@ -4904,7 +4900,7 @@ const TypeInt* CountedLoopConverter::filtered_type_from_dominators(Node* val, No assert(join_t->empty(), "top"); return nullptr; } - rtn_t = join_t->is_int(); + rtn_t = join_t->as_int(); } } } @@ -4926,7 +4922,7 @@ const TypeInt* CountedLoopConverter::filtered_type_from_dominators(Node* val, No // Dump special per-node info #ifndef PRODUCT void CountedLoopEndNode::dump_spec(outputStream *st) const { - if( in(TestValue) != nullptr && in(TestValue)->is_Bool() ) { + if (is(in(TestValue))) { BoolTest bt( test_trip()); // Added this for g++. st->print("["); @@ -7643,19 +7639,19 @@ OpaqueZeroTripGuardNode* CountedLoopNode::is_canonical_loop_entry() { } Node* ctrl = skip_assertion_predicates_with_halt(); - if (ctrl == nullptr || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) { + if (!is(ctrl) && !is(ctrl)) { return nullptr; } Node* iffm = ctrl->in(0); - if (iffm == nullptr || iffm->Opcode() != Op_If) { + if (!is_exact(iffm)) { return nullptr; } Node* bolzm = iffm->in(1); - if (bolzm == nullptr || !bolzm->is_Bool()) { + if (!is(bolzm)) { return nullptr; } Node* cmpzm = bolzm->in(1); - if (cmpzm == nullptr || !cmpzm->is_Cmp()) { + if (!is(cmpzm)) { return nullptr; } @@ -7668,7 +7664,7 @@ OpaqueZeroTripGuardNode* CountedLoopNode::is_canonical_loop_entry() { bool found_opaque = false; for (uint i = 1; i < cmpzm->req(); i++) { Node* opnd = cmpzm->in(i); - if (opnd && opnd->is_Opaque1()) { + if (is(opnd)) { found_opaque = true; break; } @@ -8166,7 +8162,7 @@ void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) { // which can inhibit range check elimination. if (least != early) { Node* ctrl_out = least->unique_ctrl_out_or_null(); - if (ctrl_out != nullptr && ctrl_out->is_Loop() && + if (Node::is(ctrl_out) && least == ctrl_out->in(LoopNode::EntryControl) && (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) { Node* least_dom = idom(least); @@ -8176,8 +8172,8 @@ void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) { } } // Don't extend live ranges of raw oops - if (least != early && n->is_ConstraintCast() && n->in(1)->bottom_type()->isa_rawptr() && - !n->bottom_type()->isa_rawptr()) { + if (least != early && n->is_ConstraintCast() && n->in(1)->bottom_type()->is_rawptr() && + !n->bottom_type()->is_rawptr()) { least = early; } diff --git a/src/hotspot/share/opto/loopnode.hpp b/src/hotspot/share/opto/loopnode.hpp index e392a90896c3..141473509292 100644 --- a/src/hotspot/share/opto/loopnode.hpp +++ b/src/hotspot/share/opto/loopnode.hpp @@ -434,10 +434,7 @@ class BaseCountedLoopEndNode : public IfNode { PhiNode* phi() const { Node* tmp = incr(); if (tmp && tmp->req() == 3) { - Node* phi = tmp->in(1); - if (phi->is_Phi()) { - return phi->as_Phi(); - } + return isa(tmp->in(1)); } return nullptr; } @@ -450,14 +447,14 @@ class BaseCountedLoopEndNode : public IfNode { if (iv_phi == nullptr) { return nullptr; } - Node* ln = iv_phi->in(0); - if (!ln->is_BaseCountedLoop() || ln->as_BaseCountedLoop()->loopexit_or_null() != this) { + BaseCountedLoopNode* ln = isa(iv_phi->in(0)); + if (ln == nullptr || ln->loopexit_or_null() != this) { return nullptr; } - if (ln->as_BaseCountedLoop()->bt() != bt()) { + if (ln->bt() != bt()) { return nullptr; } - return ln->as_BaseCountedLoop(); + return ln; } BoolTest::mask test_trip() const { return in(TestValue)->as_Bool()->_test._test; } @@ -722,7 +719,7 @@ class IdealLoopTree : public ResourceObj { void counted_loop( PhaseIdealLoop *phase ); // Check for Node being a loop-breaking test - Node *is_loop_exit(Node *iff) const; + Node* is_loop_exit(const IfNode *iff) const; // Return unique loop-exit projection or null if the loop has multiple exits. IfFalseNode* unique_loop_exit_proj_or_null(); @@ -1740,8 +1737,8 @@ class PhaseIdealLoop : public PhaseTransform { #endif // Returns nonzero constant stride if-node is a possible iv test (otherwise returns zero.) - int stride_of_possible_iv( Node* iff ); - bool is_possible_iv_test( Node* iff ) { return stride_of_possible_iv(iff) != 0; } + int stride_of_possible_iv(IfNode* iff); + bool is_possible_iv_test(IfNode* iff) { return stride_of_possible_iv(iff) != 0; } // Return the (unique) control output node that's in the loop (if it exists.) Node* stay_in_loop( Node* n, IdealLoopTree *loop); // Insert a signed compare loop exit cloned from an unsigned compare. diff --git a/src/hotspot/share/opto/loopopts.cpp b/src/hotspot/share/opto/loopopts.cpp index 3ec8e6f26e54..fdfce3523a69 100644 --- a/src/hotspot/share/opto/loopopts.cpp +++ b/src/hotspot/share/opto/loopopts.cpp @@ -1188,7 +1188,7 @@ Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) { return n; } - if (n->isa_FlatArrayCheck()) { + if (n->is_FlatArrayCheck()) { move_flat_array_check_out_of_loop(n); return n; } @@ -1886,8 +1886,8 @@ bool PhaseIdealLoop::safe_for_if_replacement(const Node* dom) const { // computation per usage to allow it to sink out of the loop. void PhaseIdealLoop::try_sink_out_of_loop(Node* n) { bool is_raw_to_oop_cast = n->is_ConstraintCast() && - n->in(1)->bottom_type()->isa_rawptr() && - !n->bottom_type()->isa_rawptr(); + n->in(1)->bottom_type()->is_rawptr() && + !n->bottom_type()->is_rawptr(); if (has_ctrl(n) && !n->is_Phi() && @@ -2322,7 +2322,7 @@ Node* PhaseIdealLoop::clone_iff(PhiNode* phi) { // "Nearly" because all Nodes have been cloned from the original in the loop, // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs // through the Phi recursively, and return a Bool. -CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) { +CmpNode* PhaseIdealLoop::clone_bool(PhiNode* phi) { uint i; // Convert this Phi into a Phi merging Bools for( i = 1; i < phi->req(); i++ ) { @@ -2337,22 +2337,29 @@ CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) { Node *sample_cmp = phi->in(1); // Make Phis to merge the Cmp's inputs. - PhiNode *phi1 = new PhiNode( phi->in(0), Type::TOP ); - PhiNode *phi2 = new PhiNode( phi->in(0), Type::TOP ); - for( uint j = 1; j < phi->req(); j++ ) { - Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP - Node *n1, *n2; - if( cmp_top->is_Cmp() ) { - n1 = cmp_top->in(1); - n2 = cmp_top->in(2); + // The Cmp could be a FlatArrayCheck node: input 1 is then memory and a memory Phi with the right address type + // needs to be created. + PhiNode* phi1 = nullptr; + PhiNode* phi2 = new PhiNode(phi->in(0), Type::TOP); + for (uint j = 1; j < phi->req(); j++) { + Node* cmp = phi->in(j); // Inputs are all Cmp + Node* n1, *n2; + assert(cmp->is_Cmp(), ""); + n1 = cmp->in(1); + n2 = cmp->in(2); + + if (phi1 == nullptr) { + phi1 = PhiNode::make(phi->in(0), n1); } else { - n1 = n2 = cmp_top; + phi1->set_req(j, n1); + phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); } - phi1->set_req( j, n1 ); - phi2->set_req( j, n2 ); - phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); + phi2->set_req(j, n2); + assert(phi1->bottom_type() != Type::MEMORY || cmp->is_FlatArrayCheck(), "only FlatArrayCheck has a memory input"); phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type())); + assert(phi2->bottom_type() != Type::MEMORY, "no memory input to a Cmp"); } + assert(phi1 != nullptr, ""); // See if these Phis have been made before. // Register with optimizer @@ -3028,14 +3035,13 @@ void PhaseIdealLoop::clone_loop_body(const Node_List& body, Node_Listis_If() || iff->in(1) == nullptr || !iff->in(1)->is_Bool()) { +int PhaseIdealLoop::stride_of_possible_iv(IfNode* iff) { + BoolNode* bl = Node::isa(iff->in(1)); + if (bl == nullptr) { return 0; } - BoolNode* bl = iff->in(1)->as_Bool(); Node* cmp = bl->in(1); - if (!cmp || (cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU)) { + if (!Node::is_exact(cmp) && !Node::is_exact(cmp)) { return 0; } // Must have an invariant operand @@ -3072,7 +3078,7 @@ int PhaseIdealLoop::stride_of_possible_iv(Node* iff) { } } if (add2 != nullptr) { - const TypeInt* add2t = _igvn.type(add2)->is_int(); + const TypeInt* add2t = _igvn.type(add2)->as_int(); if (add2t->is_con()) { return add2t->get_con(); } @@ -3380,7 +3386,7 @@ IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree* lo // -3 >=u -2 // is false. Node* limit = cmpu->in(2); - const TypeInt* type_limit = _igvn.type(limit)->is_int(); + const TypeInt* type_limit = _igvn.type(limit)->as_int(); if (type_limit->_lo < 0) { return nullptr; } @@ -3999,25 +4005,25 @@ bool PhaseIdealLoop::partial_peel(IdealLoopTree* loop, Node_List& old_new) IfNode *peel_if = nullptr; IfNode *peel_if_cmpu = nullptr; - Node *iff = loop->tail(); - while (iff != head) { - if (iff->is_If()) { - Node *ctrl = get_ctrl(iff->in(1)); + Node* next = loop->tail(); + while (next != head) { + if (IfNode* iff = next->isa_If(); iff != nullptr) { + Node *ctrl = get_ctrl(next->in(1)); if (ctrl->is_top()) return false; // Dead test on live IF. // If loop-varying exit-test, check for induction variable if (loop->is_member(get_loop(ctrl)) && loop->is_loop_exit(iff) && is_possible_iv_test(iff)) { - Node* cmp = iff->in(1)->in(1); + Node* cmp = next->in(1)->in(1); if (cmp->Opcode() == Op_CmpI) { - peel_if = iff->as_If(); + peel_if = iff; } else { assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU"); - peel_if_cmpu = iff->as_If(); + peel_if_cmpu = iff; } } } - iff = idom(iff); + next = idom(next); } // Prefer signed compare over unsigned compare. diff --git a/src/hotspot/share/opto/machnode.cpp b/src/hotspot/share/opto/machnode.cpp index e4fc97f33d36..c26e9518054b 100644 --- a/src/hotspot/share/opto/machnode.cpp +++ b/src/hotspot/share/opto/machnode.cpp @@ -296,8 +296,8 @@ const Node* MachNode::get_base_and_disp(intptr_t &offset, const TypePtr* &adr_ty // See if it adds up to a base + offset. if (index != nullptr) { const Type* t_index = index->bottom_type(); - if (t_index->isa_narrowoop() || t_index->isa_narrowklass()) { // EncodeN, LoadN, LoadConN, LoadNKlass, - // EncodeNKlass, LoadConNklass. + if (t_index->is_narrowoop() || t_index->is_narrowklass()) { // EncodeN, LoadN, LoadConN, LoadNKlass, + // EncodeNKlass, LoadConNklass. // Memory references through narrow oops have a // funny base so grab the type from the index: // [R12 + narrow_oop_reg<<3 + offset] @@ -327,8 +327,8 @@ const Node* MachNode::get_base_and_disp(intptr_t &offset, const TypePtr* &adr_ty if (t_disp != nullptr) { offset = Type::OffsetBot; const Type* t_base = base->bottom_type(); - if (t_base->isa_intptr_t()) { - const TypeX *t_offset = t_base->is_intptr_t(); + if (t_base->is_intptr_t()) { + const TypeX* t_offset = t_base->as_intptr_t(); if( t_offset->is_con() ) { offset = t_offset->get_con(); } @@ -428,9 +428,9 @@ const TypePtr* MachNode::compute_adr_type_from_inputs() const { } #ifdef ASSERT - if (base != nullptr && base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_VerifyVectorAlignment) { + if (auto base_mach = isa(base); base_mach != nullptr && base_mach->ideal_Opcode() == Op_VerifyVectorAlignment) { // For VerifyVectorAlignment we just pass the type through - return base->bottom_type()->is_ptr(); + return base->bottom_type()->as_ptr(); } #endif @@ -457,16 +457,16 @@ const TypePtr* MachNode::compute_adr_type_from_inputs() const { if (base == NodeSentinel) return TypePtr::BOTTOM; const Type* t = base->bottom_type(); - if (t->isa_narrowoop() && CompressedOops::shift() == 0) { + if (t->is_narrowoop() && CompressedOops::shift() == 0) { // 32-bit unscaled narrow oop can be the base of any address expression t = t->make_ptr(); } - if (t->isa_narrowklass() && CompressedKlassPointers::shift() == 0) { + if (t->is_narrowklass() && CompressedKlassPointers::shift() == 0) { // 32-bit unscaled narrow oop can be the base of any address expression t = t->make_ptr(); } - if (t->isa_intptr_t() && + if (t->is_intptr_t() && #if !defined(AARCH64) && !defined(RISCV) // AArch64 and RISC-V support the addressing mode: // [base, 0], in which [base] is converted from a long value @@ -490,7 +490,7 @@ const TypePtr* MachNode::compute_adr_type_from_inputs() const { } assert(tp->base() != Type::AnyPtr, "not a bare pointer"); - if (tp->isa_aryptr()) { + if (tp->is_aryptr()) { // In the case of a flat value type array, each field has its // own slice so we need to extract the field being accessed from // the address computation @@ -500,10 +500,10 @@ const TypePtr* MachNode::compute_adr_type_from_inputs() const { const MachOper* oper = memory_inputs(base, index); if (oper != (MachOper*)-1) { offset = oper->constant_disp(); - return tp->is_aryptr()->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot); + return tp->as_aryptr()->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot); } } - return tp->is_aryptr()->add_field_offset_and_offset(offset); + return tp->as_aryptr()->add_field_offset_and_offset(offset); } return tp->add_offset(offset); @@ -725,7 +725,7 @@ const Type *MachProjNode::bottom_type() const { // Try the normal mechanism first const Type *t = in(0)->bottom_type(); if( t->base() == Type::Tuple ) { - const TypeTuple *tt = t->is_tuple(); + const TypeTuple* tt = t->as_tuple(); if (_con < tt->cnt()) return tt->field_at(_con); } @@ -903,7 +903,7 @@ bool MachCallNode::return_value_is_used() const { bool MachCallNode::returns_pointer() const { const TypeTuple *r = tf()->range_sig(); return (r->cnt() > TypeFunc::Parms && - r->field_at(TypeFunc::Parms)->isa_ptr()); + r->field_at(TypeFunc::Parms)->is_ptr()); } bool MachCallNode::returns_scalarized() const { diff --git a/src/hotspot/share/opto/machnode.hpp b/src/hotspot/share/opto/machnode.hpp index 4414b8c8a9ae..8e1e1bbd3d0e 100644 --- a/src/hotspot/share/opto/machnode.hpp +++ b/src/hotspot/share/opto/machnode.hpp @@ -355,8 +355,8 @@ class MachNode : public Node { const Type* res = _opnds[0]->type(); // The type system around pointers is complex, do not rely on operand type then assert(res != nullptr, "must be not null"); - assert(is_MachTemp() || res->isa_ptr() == nullptr, "must not be a pointer"); - assert(is_MachTemp() || res->isa_narrowoop() == nullptr, "must not be a narrow oop"); + assert(is_MachTemp() || !res->is_ptr(), "must not be a pointer"); + assert(is_MachTemp() || !res->is_narrowoop(), "must not be a narrow oop"); return res; } @@ -479,9 +479,6 @@ class MachConstantBaseNode : public MachIdealNode { virtual uint ideal_reg() const { return Op_RegP; } virtual uint oper_input_base() const { return 1; } - virtual bool requires_postalloc_expand() const; - virtual void postalloc_expand(GrowableArray *nodes, PhaseRegAlloc *ra_); - virtual void emit(C2_MacroAssembler* masm, PhaseRegAlloc* ra_) const; virtual uint size(PhaseRegAlloc* ra_) const; diff --git a/src/hotspot/share/opto/macro.cpp b/src/hotspot/share/opto/macro.cpp index 3be18a8ace49..5d666b3ac2fa 100644 --- a/src/hotspot/share/opto/macro.cpp +++ b/src/hotspot/share/opto/macro.cpp @@ -129,7 +129,7 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me Node *orig_mem = mem; Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false); assert(alloc_mem != nullptr, "Allocation without a memory projection."); - const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr(); + const TypeOopPtr* tinst = phase->C->get_adr_type(alias_idx)->as_oopptr(); while (true) { if (mem == alloc_mem || mem == start_mem ) { return mem; // hit one of our sentinels @@ -172,9 +172,9 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me const TypePtr* atype = mem->as_Store()->out_adr_type(); int adr_idx = phase->C->get_alias_index(atype); if (adr_idx == alias_idx) { - assert(atype->isa_oopptr(), "address type must be oopptr"); + assert(atype->is_oopptr(), "address type must be oopptr"); int adr_offset = atype->flat_offset(); - uint adr_iid = atype->is_oopptr()->instance_id(); + uint adr_iid = atype->as_oopptr()->instance_id(); // Array elements references have the same alias_idx // but different offset and different instance_id. if (adr_offset == offset && adr_iid == alloc->_idx) { @@ -210,7 +210,7 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me mem->Opcode() == Op_StrCompressedCopy, "sanity"); adr = mem->in(3); // Destination array } - const TypePtr* atype = adr->bottom_type()->is_ptr(); + const TypePtr* atype = adr->bottom_type()->as_ptr(); int adr_idx = phase->C->get_alias_index(atype); if (adr_idx == alias_idx) { DEBUG_ONLY(mem->dump();) @@ -220,7 +220,7 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me mem = mem->in(MemNode::Memory); } else if (mem->Opcode() == Op_StrInflatedCopy) { Node* adr = mem->in(3); // Destination array - const TypePtr* atype = adr->bottom_type()->is_ptr(); + const TypePtr* atype = adr->bottom_type()->as_ptr(); int adr_idx = phase->C->get_alias_index(atype); if (adr_idx == alias_idx) { DEBUG_ONLY(mem->dump();) @@ -298,9 +298,9 @@ Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, if (ac->is_clonebasic()) { assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination"); adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(offset))); - adr_type = _igvn.type(base)->is_ptr(); - if (adr_type->isa_aryptr()) { - adr_type = adr_type->is_aryptr()->add_field_offset_and_offset(offset); + adr_type = _igvn.type(base)->as_ptr(); + if (adr_type->is_aryptr()) { + adr_type = adr_type->as_aryptr()->add_field_offset_and_offset(offset); } else { adr_type = adr_type->add_offset(offset); } @@ -313,18 +313,18 @@ Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, uint shift = exact_log2(type2aelembytes(bt)); Node* src_pos = ac->in(ArrayCopyNode::SrcPos); Node* dest_pos = ac->in(ArrayCopyNode::DestPos); - const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int(); - const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int(); + const TypeInt* src_pos_t = _igvn.type(src_pos)->as_int(); + const TypeInt* dest_pos_t = _igvn.type(dest_pos)->as_int(); - adr_type = _igvn.type(base)->is_aryptr(); + adr_type = _igvn.type(base)->as_aryptr(); if (((const TypeAryPtr*)adr_type)->is_flat()) { shift = ((const TypeAryPtr*)adr_type)->flat_log_elem_size(); } if (src_pos_t->is_con() && dest_pos_t->is_con()) { intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset; adr = _igvn.transform(AddPNode::make_with_base(base, base, _igvn.MakeConX(off))); - adr_type = _igvn.type(adr)->is_aryptr(); - assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type"); + adr_type = _igvn.type(adr)->as_aryptr(); + assert(adr_type == _igvn.type(base)->as_aryptr()->add_field_offset_and_offset(off), "incorrect address type"); if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) { // Don't emit a new load from src if src == dst but try to get the value from memory instead return value_from_mem(ac, ctl, ft, ftype, (const TypeAryPtr*)adr_type, alloc); @@ -346,7 +346,7 @@ Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, // In the case of a flat value type array, each field has its // own slice so we need to extract the field being accessed from // the address computation - adr_type = ((TypeAryPtr*)adr_type)->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr(); + adr_type = ((TypeAryPtr*)adr_type)->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->as_aryptr(); adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type)); } } @@ -366,7 +366,7 @@ Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, return make_arraycopy_load(ac, offset, ac->control(), ac->memory(), ft, ftype, alloc); } - if (ftype->isa_narrowoop()) { + if (ftype->is_narrowoop()) { // PhaseMacroExpand::scalar_replacement adds DecodeN nodes res = _igvn.transform(new EncodePNode(res, ftype)); } @@ -531,7 +531,7 @@ Node* PhaseMacroExpand::value_from_alloc(BasicType ft, const TypeOopPtr* adr_t, } if (ft == T_NARROWOOP) { - assert(init_value->bottom_type()->isa_ptr(), "must be a pointer"); + assert(init_value->bottom_type()->is_ptr(), "must be a pointer"); init_value = transform_later(new EncodePNode(init_value, init_value->bottom_type()->make_narrowoop())); } @@ -722,7 +722,7 @@ Node* PhaseMacroExpand::value_type_from_mem(ciValueKlass* vk, const TypeAryPtr* if (field_value == nullptr || force_scalarization_failure) { report_failure(field_offset_in_element, field_value != nullptr); return nullptr; - } else if (ft->isa_narrowoop()) { + } else if (ft->is_narrowoop()) { assert(UseCompressedOops, "unexpected narrow oop"); if (field_value->is_EncodeP()) { field_value = field_value->in(1); @@ -766,7 +766,7 @@ bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode } else if (!res_type->klass_is_exact()) { NOT_PRODUCT(fail_eliminate = "Not an exact type.";) can_eliminate = false; - } else if (res_type->isa_aryptr()) { + } else if (res_type->is_aryptr()) { int length = alloc->in(AllocateNode::ALength)->find_int_con(-1); if (length < 0) { NOT_PRODUCT(fail_eliminate = "Array's size is not constant";) @@ -781,7 +781,7 @@ bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode Node* use = res->fast_out(j); if (use->is_AddP()) { - const TypePtr* addp_type = igvn->type(use)->is_ptr(); + const TypePtr* addp_type = igvn->type(use)->as_ptr(); int offset = addp_type->offset(); if (offset == Type::OffsetTop || offset == Type::OffsetBot) { @@ -812,7 +812,7 @@ bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode use->in(ArrayCopyNode::Src)->get_ptr_type()->is_flat() && !use->in(ArrayCopyNode::Src) ->get_ptr_type() - ->isa_aryptr() + ->as_aryptr() ->elem() ->value_klass() ->is_naturally_atomic( @@ -1012,7 +1012,7 @@ void PhaseMacroExpand::undo_previous_scalarizations(Node_List& sa #endif void PhaseMacroExpand::process_field_value_at_safepoint(const Type* field_type, Node* field_val, SafePointNode* sfpt, Unique_Node_List* value_worklist) { - if (UseCompressedOops && field_type->isa_narrowoop()) { + if (UseCompressedOops && field_type->is_narrowoop()) { // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation // to be able scalar replace the allocation. if (field_val->is_EncodeP()) { @@ -1093,7 +1093,7 @@ bool PhaseMacroExpand::add_array_elems_to_safepoint(AllocateNode* alloc, const T // 'offset_minus_header' refers to the offset of the payload of 'iklass' inside 'base' minus the // payload offset of 'iklass'. If 'base' is of type 'iklass' then 'offset_minus_header' == 0. bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, AllocateNode* alloc, Node* base, int offset_minus_header, SafePointNode* sfpt, Unique_Node_List* value_worklist) { - const TypeInstPtr* base_type = _igvn.type(base)->is_instptr(); + const TypeInstPtr* base_type = _igvn.type(base)->as_instptr(); auto report_failure = [&](int offset, bool is_forced_failure) { #ifndef PRODUCT if (PrintEliminateAllocations) { @@ -1160,7 +1160,7 @@ bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, All field_type = Type::get_const_basic_type(basic_elem_type); } - const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->isa_instptr(); + const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->as_instptr(); Node* field_val = value_from_mem(sfpt, sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc); bool force_scalarization_failure = StressEliminateAllocations && (C->stress().random() % StressEliminateAllocationsMean == 0); @@ -1194,9 +1194,9 @@ SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_descriptio if (res != nullptr) { // Could be null when there are no users res_type = _igvn.type(res)->isa_oopptr(); - if (res_type->isa_instptr()) { + if (res_type->is_instptr()) { // find the fields of the class which will be needed for safepoint debug information - iklass = res_type->is_instptr()->instance_klass(); + iklass = res_type->as_instptr()->instance_klass(); nfields = iklass->nof_nonstatic_fields(); } else { // find the array's elements which will be needed for safepoint debug information @@ -1226,7 +1226,7 @@ SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_descriptio bool success; if (iklass == nullptr) { - success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist); + success = add_array_elems_to_safepoint(alloc, res_type->as_aryptr(), sfpt, value_worklist); } else { success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist); } @@ -1387,7 +1387,7 @@ void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool value_t _igvn.rehash_node_delayed(use); use->as_ValueType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT)); use->as_ValueType()->set_is_buffered(_igvn, false); - const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot); + const TypeOopPtr* toop = _igvn.type(use)->as_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot); _igvn.set_type(use, toop); use->as_ValueType()->set_type(toop); // Process users @@ -1505,12 +1505,12 @@ bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) { return false; } Node* klass = alloc->in(AllocateNode::KlassNode); - const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr(); + const TypeKlassPtr* tklass = _igvn.type(klass)->as_klassptr(); // Attempt to eliminate value type buffer allocations // regardless of usage and escape/replaceable status. - bool value_type_alloc = tklass->isa_instklassptr() && - tklass->is_instklassptr()->instance_klass()->is_value_klass(); + bool value_type_alloc = tklass->is_instklassptr() && + tklass->as_instklassptr()->instance_klass()->is_value_klass(); if (!alloc->_is_non_escaping && !value_type_alloc) { return false; } @@ -1518,8 +1518,8 @@ bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) { // regardless scalar replaceable status. Node* res = alloc->result_cast(); bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() && - tklass->isa_instklassptr() && - tklass->is_instklassptr()->instance_klass()->is_box_klass(); + tklass->is_instklassptr() && + tklass->as_instklassptr()->instance_klass()->is_box_klass(); if (!alloc->_is_scalar_replaceable && !boxing_alloc && !value_type_alloc) { return false; } @@ -1621,7 +1621,7 @@ bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode* call) { Node* PhaseMacroExpand::make_load_raw(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) { Node* adr = off_heap_plus_addr(base, offset); - const TypePtr* adr_type = adr->bottom_type()->is_ptr(); + const TypePtr* adr_type = adr->bottom_type()->as_ptr(); Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered); transform_later(value); return value; @@ -2196,8 +2196,8 @@ Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc, rawmem = make_store_raw(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT); // conservatively small header size: header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE); - if (_igvn.type(klass_node)->isa_aryklassptr()) { // we know the exact header size in most cases: - BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_exact_instance_type()->isa_aryptr()->elem()->array_element_basic_type(); + if (_igvn.type(klass_node)->is_aryklassptr()) { // we know the exact header size in most cases: + BasicType elem = _igvn.type(klass_node)->as_klassptr()->as_exact_instance_type()->as_aryptr()->elem()->array_element_basic_type(); if (is_reference_type(elem, true)) { elem = T_OBJECT; } @@ -2411,7 +2411,7 @@ void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) { const TypeFunc* slow_call_type; address slow_call_address; // Address of slow call if (init != nullptr && init->is_complete_with_arraycopy() && - ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) { + ary_klass_t && !ary_klass_t->elem()->is_klassptr()) { // Don't zero type array during slow allocation in VM since // it will be initialized later by arraycopy in compiled code. slow_call_address = OptoRuntime::new_array_nozero_Java(); @@ -2649,7 +2649,7 @@ bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) { if (alock->is_Lock()) { // Search for MemBarAcquireLock node and delete it also. MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar(); - assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, ""); + assert(Node::is_exact(membar), ""); Node* ctrlproj = membar->proj_out(TypeFunc::Control); Node* memproj = membar->proj_out(TypeFunc::Memory); _igvn.replace_node(ctrlproj, fallthroughproj); @@ -3028,7 +3028,7 @@ void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) { Node* ctrl = iff->in(0); Node* subklass = nullptr; - if (_igvn.type(obj_or_subklass)->isa_klassptr()) { + if (_igvn.type(obj_or_subklass)->is_klassptr()) { subklass = obj_or_subklass; } else { Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes()); @@ -3065,7 +3065,7 @@ void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) { // } void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) { assert(UseArrayFlattening, "Should not be called if flat arrays are not enabled"); - bool use_mark_word = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr; + bool use_mark_word = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->is_oopptr(); Unique_Node_List outputs; for (DUIterator_Fast imax, i = check->fast_outs(imax); i < imax; i++) { @@ -3090,7 +3090,7 @@ void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) { assert(t != nullptr, "Mixing array and klass inputs"); assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out"); Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes()); - Node* mark_load = _igvn.transform(LoadNode::make(_igvn, nullptr, mem, mark_adr, mark_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered)); + Node* mark_load = _igvn.transform(LoadNode::make(_igvn, nullptr, mem, mark_adr, mark_adr->bottom_type()->as_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered)); mark = _igvn.transform(new OrXNode(mark, mark_load)); } assert(!mark->is_Con(), "Should have been optimized out"); @@ -3122,17 +3122,17 @@ void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) { for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) { Node* array_or_klass = check->in(i); Node* klass = nullptr; - const TypePtr* t = _igvn.type(array_or_klass)->is_ptr(); + const TypePtr* t = _igvn.type(array_or_klass)->as_ptr(); assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out"); - if (t->isa_oopptr() != nullptr) { + if (t->is_oopptr()) { Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes()); klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT)); } else { - assert(t->isa_klassptr(), "Unexpected input type"); + assert(t->is_klassptr(), "Unexpected input type"); klass = array_or_klass; } Node* lh_addr = basic_plus_adr(top(), klass, in_bytes(Klass::layout_helper_offset())); - Node* lh_val = _igvn.transform(LoadNode::make(_igvn, nullptr, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); + Node* lh_val = _igvn.transform(LoadNode::make(_igvn, nullptr, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->as_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); lhs = _igvn.transform(new OrINode(lhs, lh_val)); } Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace))); diff --git a/src/hotspot/share/opto/macroArrayCopy.cpp b/src/hotspot/share/opto/macroArrayCopy.cpp index 72cc6bccc804..de46ee7102ee 100644 --- a/src/hotspot/share/opto/macroArrayCopy.cpp +++ b/src/hotspot/share/opto/macroArrayCopy.cpp @@ -60,7 +60,7 @@ void PhaseMacroExpand::insert_mem_bar(Node** ctrl, Node** mem, int opcode, int a Node* PhaseMacroExpand::array_element_address(Node* ary, Node* idx, BasicType elembt, bool raw_base) { uint shift = exact_log2(type2aelembytes(elembt)); const TypeAryPtr* array_type = _igvn.type(ary)->isa_aryptr(); - if (array_type != nullptr && array_type->is_aryptr()->is_flat()) { + if (array_type != nullptr && array_type->is_flat()) { // Use T_FLAT_ELEMENT to get proper alignment with COH when fetching the array element address. elembt = T_FLAT_ELEMENT; } @@ -875,13 +875,13 @@ Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* // insert a wide membar now that it's being expanded: a load that uses the input memory state of the ArrayCopy // could then become anti dependent on the membar when it was not anti dependent on the ArrayCopy leading to a // broken graph. - mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr()); + mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->as_ptr()); } insert_mem_bar(ctrl, &out_mem, Op_MemBarCPUOrder, mem_bar_alias_idx); } assert((*ctrl)->is_Proj(), "MemBar control projection"); - assert((*ctrl)->in(0)->isa_MemBar(), "MemBar node"); + assert((*ctrl)->in(0)->is_MemBar(), "MemBar node"); (*ctrl)->in(0)->isa_MemBar()->set_trailing_expanded_array_copy(); _igvn.replace_node(_callprojs->fallthrough_memproj, out_mem); @@ -891,7 +891,7 @@ Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* _igvn.replace_node(_callprojs->fallthrough_catchproj, *ctrl); #ifdef ASSERT - const TypeOopPtr* dest_t = _igvn.type(orig_dest)->is_oopptr(); + const TypeOopPtr* dest_t = _igvn.type(orig_dest)->as_oopptr(); if (dest_t->is_known_instance()) { ArrayCopyNode* ac = nullptr; assert(ArrayCopyNode::may_modify(dest_t, (*ctrl)->in(0)->as_MemBar(), &_igvn, ac), "dependency on arraycopy lost"); @@ -1020,7 +1020,7 @@ void PhaseMacroExpand::generate_clear_array(Node* ctrl, MergeMemNode* merge_mem, assert(raw_val == nullptr, "val may not be null"); mem = StoreNode::make(_igvn, ctrl, mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered); } else { - assert(_igvn.type(val)->isa_narrowoop(), "should be narrow oop"); + assert(_igvn.type(val)->is_narrowoop(), "should be narrow oop"); mem = new StoreNNode(ctrl, mem, p1, adr_type, val, MemNode::unordered); } mem = transform_later(mem); @@ -1072,8 +1072,8 @@ bool PhaseMacroExpand::generate_block_arraycopy(Node** ctrl, MergeMemNode** mem, ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) { Node* sptr = basic_plus_adr(src, src_off); Node* dptr = basic_plus_adr(dest, dest_off, raw_base); - const TypePtr* s_adr_type = _igvn.type(sptr)->is_ptr(); - assert(s_adr_type->isa_aryptr(), "impossible slice"); + const TypePtr* s_adr_type = _igvn.type(sptr)->as_ptr(); + assert(s_adr_type->is_aryptr(), "impossible slice"); uint s_alias_idx = C->get_alias_index(s_adr_type); uint d_alias_idx = C->get_alias_index(adr_type); bool is_mismatched = (basic_elem_type != T_INT); @@ -1193,7 +1193,7 @@ Node* PhaseMacroExpand::generate_checkcast_arraycopy(Node** ctrl, MergeMemNode** // super_check_offset, for the desired klass. int sco_offset = in_bytes(Klass::super_check_offset_offset()); Node* p3 = off_heap_plus_addr(dest_elem_klass, sco_offset); - Node* n3 = new LoadINode(nullptr, *mem /*memory(p3)*/, p3, _igvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered); + Node* n3 = new LoadINode(nullptr, *mem /*memory(p3)*/, p3, _igvn.type(p3)->as_ptr(), TypeInt::INT, MemNode::unordered); Node* check_offset = ConvI2X(transform_later(n3)); Node* check_value = dest_elem_klass; @@ -1302,7 +1302,7 @@ const TypePtr* PhaseMacroExpand::adjust_for_flat_array(const TypeAryPtr* top_des Node*& dest_length) { assert(UseArrayFlattening, "Should not be called if flat arrays are not enabled"); #ifdef ASSERT - assert(top_dest->elem()->make_ptr()->is_instptr()->is_valueklassptr(), "must be concrete value klass"); + assert(top_dest->elem()->make_ptr()->as_instptr()->is_valueklassptr(), "must be concrete value klass"); BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); bool needs_barriers = top_dest->elem()->value_klass()->contains_oops() && bs->array_copy_requires_gc_barriers(dest_length != nullptr, T_OBJECT, false, false, BarrierSetC2::Optimization); @@ -1400,14 +1400,14 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { // on all slices to prevent writes into the source from floating below the arraycopy. int mem_bar_alias_idx = Compile::AliasIdxBot; if (ac->_dest_type != TypeOopPtr::BOTTOM) { - mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr()); + mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->as_ptr()); } insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder, mem_bar_alias_idx); adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length); } else { - adr_type = dest_type->is_oopptr()->add_offset(Type::OffsetBot); + adr_type = dest_type->as_oopptr()->add_offset(Type::OffsetBot); if (ac->_dest_type != TypeOopPtr::BOTTOM) { - adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr(); + adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->as_ptr(); } } merge_mem = MergeMemNode::make(mem); @@ -1480,36 +1480,10 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { assert(!ac->is_arraycopy_validated() || (src_elem == dest_elem && dest_elem != T_VOID), "validated but different basic types"); - // (2) src and dest arrays must have elements of the same BasicType - // Figure out the size and type of the elements we will be copying. - // - // - // Go to the slow path but avoid the native method wrapper to JVM_ArrayCopy when: - // 1) The component types are not the same or void. - // 2) src and dest do not have the same flatness. - // 3) src or dest is a flat abstract value class array (we don't know the exact layout and cannot use the stub). - // 4) src or dest is a flat value class array with oop fields and requires to emit barriers (we don't have such a stub). - // TODO 8251971: This does not handle atomicity. We should probably match on layouts which makes this code easier - // and handles all cases. - BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); - bool go_to_slow_path = false; - if (src_elem != dest_elem || top_src->is_flat() != top_dest->is_flat() || dest_elem == T_VOID) { - // 1) and 2) - go_to_slow_path = true; - } else if ((top_src->is_flat() && !top_src->elem()->is_valueklassptr()) || - (top_dest->is_flat() && !top_dest->elem()->is_valueklassptr())) { - // 3) - go_to_slow_path = true; - } else if (top_dest->is_flat() && - bs->array_copy_requires_gc_barriers(alloc != nullptr, T_OBJECT, false, false, BarrierSetC2::Optimization) && - top_dest->elem()->value_klass()->contains_oops()) { - // 4) - assert(top_src->is_flat() && top_src->elem()->value_klass()->contains_oops(), "must match"); - go_to_slow_path = true; - } - - if (go_to_slow_path) { - // Avoid the native method wrapper to JVM_ArrayCopy. + // (2) src and dest array layouts need to be compatible. For flat arrays, we additionally check for GC-barrier + // requirements. + if (!ac->can_use_arraycopy_fast_path(top_src, top_dest)) { + // Go to the slow path but avoid the native method wrapper to JVM_ArrayCopy Node* mem = ac->in(TypeFunc::Memory); merge_mem = generate_slow_arraycopy(ac, &ctrl, mem, &io, TypePtr::BOTTOM, src, src_offset, dest, dest_offset, length, false); @@ -1532,7 +1506,8 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { // (6) length must not be negative. // (7) src_offset + length must not exceed length of src. // (8) dest_offset + length must not exceed length of dest. - // (9) each element of an oop array must be assignable + // (9) each element of an oop array must be assignable. + // (10) cannot copy a nullable source to a null-free destination. Node* mem = ac->in(TypeFunc::Memory); if (top_dest->is_flat()) { @@ -1540,7 +1515,7 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { // on all slices to prevent writes into the source from floating below the arraycopy. int mem_bar_alias_idx = Compile::AliasIdxBot; if (ac->_dest_type != TypeOopPtr::BOTTOM) { - mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr()); + mem_bar_alias_idx = C->get_alias_index(ac->_dest_type->add_offset(Type::OffsetBot)->as_ptr()); } insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder, mem_bar_alias_idx); } @@ -1589,14 +1564,9 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { // (9) each element of an oop array must be assignable // The generate_arraycopy subroutine checks this. - // TODO 8251971 This is too strong - // We need to be careful here because 'adjust_for_flat_array' will adjust offsets/length etc. which then does not work anymore for the slow call to SharedRuntime::slow_arraycopy_C. - assert(top_src->is_flat() == top_dest->is_flat(), "must have bailed out before"); - if (Arguments::is_valhalla_enabled() && !flat_and_same_nullness) { - if (UseArrayFlattening) { - generate_flat_array_guard(&ctrl, src, merge_mem, slow_region); - generate_flat_array_guard(&ctrl, dest, merge_mem, slow_region); - } + // (10) we cannot directly copy a nullable source to a null-free destination, this requires per-element null checks + bool needs_null_free_guard = !top_src->is_null_free() && !top_dest->is_not_null_free(); + if (Arguments::is_valhalla_enabled() && needs_null_free_guard) { generate_null_free_array_guard(&ctrl, dest, merge_mem, slow_region); } } @@ -1608,7 +1578,7 @@ void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) { if (flat_and_same_nullness) { adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length); } else if (ac->_dest_type != TypeOopPtr::BOTTOM) { - adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr(); + adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->as_ptr(); } else { adr_type = TypeAryPtr::get_array_body_type(dest_elem); } diff --git a/src/hotspot/share/opto/matcher.cpp b/src/hotspot/share/opto/matcher.cpp index 463ae32e134d..263ea03e34d8 100644 --- a/src/hotspot/share/opto/matcher.cpp +++ b/src/hotspot/share/opto/matcher.cpp @@ -398,7 +398,7 @@ void Matcher::match( ) { // in find_base_for_derived(). assert(_mach_null != nullptr || C->failure_is_artificial(), ""); // bailouts are handled below. - C->set_root(xroot->is_Root() ? xroot->as_Root() : nullptr); + C->set_root(xroot->isa_Root()); #ifdef ASSERT verify_new_nodes_only(xroot); @@ -1072,7 +1072,7 @@ Node *Matcher::xform( Node *n, int max_stack ) { if (C->failing()) return nullptr; if (m == nullptr) { Matcher::soft_match_failure(); return nullptr; } } else { // Nothing the matcher cares about - if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Multi()) { // Projections? + if (n->is_Proj() && Node::is(n->in(0))) { // Projections? if (n->in(0)->is_Initialize() && n->as_Proj()->_con == TypeFunc::Memory) { // Initialize may have multiple NarrowMem projections. They would all match to identical raw mem MachProjs. // We don't need multiple MachProjs. Create one if none already exist, otherwise use existing one. @@ -1239,8 +1239,8 @@ MachNode* Matcher::match_sfpt(SafePointNode* sfpt) { for (uint i = 0; i < static_java_call->req(); i++) { if (i == TypeFunc::Parms) { // Remove the trap request input edge. - assert(static_java_call->in(i)->bottom_type()->isa_int() && - static_java_call->in(i)->bottom_type()->is_int()->is_con(), "incorrect trap request input"); + assert(static_java_call->in(i)->bottom_type()->is_int() && + static_java_call->in(i)->bottom_type()->as_int()->is_con(), "incorrect trap request input"); } else { mn->add_req(static_java_call->in(i)); } @@ -1318,7 +1318,7 @@ MachNode* Matcher::match_sfpt(SafePointNode* sfpt) { OptoReg::Name out_arg_limit_per_call = begin_out_arg_area; // Calls to C may hammer extra stack slots above and beyond any arguments. // These are usually backing store for register arguments for varargs. - if( call != nullptr && call->is_CallRuntime() ) + if (Node::is(call)) out_arg_limit_per_call = OptoReg::add(out_arg_limit_per_call,C->varargs_C_out_slots_killed()); @@ -1381,7 +1381,7 @@ MachNode* Matcher::match_sfpt(SafePointNode* sfpt) { continue; // Avoid Halves } // Handle case where arguments are in vector registers. - if(call->in(TypeFunc::Parms + i)->bottom_type()->isa_vect()) { + if (call->in(TypeFunc::Parms + i)->bottom_type()->is_vect()) { OptoReg::Name reg_fst = OptoReg::as_OptoReg(first); OptoReg::Name reg_snd = OptoReg::as_OptoReg(second); assert (reg_fst <= reg_snd, "fst=%d snd=%d", reg_fst, reg_snd); @@ -1801,7 +1801,7 @@ MachNode *Matcher::ReduceInst( State *s, int rule, Node *&mem ) { m = leaf; } else { m = _mem_node; - assert(m != nullptr && m->is_Mem(), "expecting memory node"); + assert(Node::is(m), "expecting memory node"); } const TypePtr* mach_at = mach->in_adr_type(); // DecodeN node consumed by an address may have different type @@ -2495,11 +2495,13 @@ void Matcher::find_shared_post_visit(Node* n, uint opcode) { break; } case Op_StoreLSpecial: { - if (n->req() > (MemNode::ValueIn + 1) && n->in(MemNode::ValueIn + 1) != nullptr) { - Node* pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn + 1)); + if (!n->in(StoreLSpecialNode::OopOffset)->is_top()) { + Node* pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(StoreLSpecialNode::OopOffset)); n->set_req(MemNode::ValueIn, pair); - n->del_req(MemNode::ValueIn + 1); } + n->del_req(StoreLSpecialNode::SecondOop); + n->del_req(StoreLSpecialNode::FirstOop); + n->del_req(StoreLSpecialNode::OopOffset); break; } default: @@ -2561,7 +2563,7 @@ void Matcher::collect_null_checks( Node *proj, Node *orig_proj ) { _null_check_tests.push(proj); Node* val = cmp->in(1); #ifdef _LP64 - if (val->bottom_type()->isa_narrowoop() && + if (val->bottom_type()->is_narrowoop() && !Matcher::narrow_oop_use_complex_address()) { // // Look for DecodeN node which should be pinned to orig_proj. @@ -2657,19 +2659,19 @@ const RegMask* Matcher::regmask_for_ideal_register(uint ideal_reg, Node* ret) { Node* spill; switch (ideal_reg) { - case Op_RegN: spill = new LoadNNode(nullptr, mem, fp, atp, t->is_narrowoop(), mo); break; - case Op_RegI: spill = new LoadINode(nullptr, mem, fp, atp, t->is_int(), mo); break; - case Op_RegP: spill = new LoadPNode(nullptr, mem, fp, atp, t->is_ptr(), mo); break; + case Op_RegN: spill = new LoadNNode(nullptr, mem, fp, atp, t->as_narrowoop(), mo); break; + case Op_RegI: spill = new LoadINode(nullptr, mem, fp, atp, t->as_int(), mo); break; + case Op_RegP: spill = new LoadPNode(nullptr, mem, fp, atp, t->as_ptr(), mo); break; case Op_RegF: spill = new LoadFNode(nullptr, mem, fp, atp, t, mo); break; case Op_RegD: spill = new LoadDNode(nullptr, mem, fp, atp, t, mo); break; - case Op_RegL: spill = new LoadLNode(nullptr, mem, fp, atp, t->is_long(), mo); break; + case Op_RegL: spill = new LoadLNode(nullptr, mem, fp, atp, t->as_long(), mo); break; case Op_VecA: // fall-through case Op_VecS: // fall-through case Op_VecD: // fall-through case Op_VecX: // fall-through case Op_VecY: // fall-through - case Op_VecZ: spill = new LoadVectorNode(nullptr, mem, fp, atp, t->is_vect()); break; + case Op_VecZ: spill = new LoadVectorNode(nullptr, mem, fp, atp, t->as_vect()); break; case Op_RegVectMask: return Matcher::predicate_reg_mask(); default: ShouldNotReachHere(); @@ -2680,7 +2682,7 @@ const RegMask* Matcher::regmask_for_ideal_register(uint ideal_reg, Node* ret) { return nullptr; } // Handle generic vector operand case - if (Matcher::supports_generic_vector_operands && t->isa_vect()) { + if (Matcher::supports_generic_vector_operands && t->is_vect()) { specialize_mach_node(mspill); } return &mspill->out_RegMask(); @@ -2728,7 +2730,7 @@ MachOper* Matcher::specialize_vector_operand(MachNode* m, uint opnd_idx) { } } } - assert(def->bottom_type()->isa_vect(), "not a vector"); + assert(def->bottom_type()->is_vect(), "not a vector"); uint ideal_vreg = def->bottom_type()->ideal_reg(); return Matcher::pd_specialize_generic_vector_operand(m->_opnds[opnd_idx], ideal_vreg, false /*is_temp*/); } @@ -2772,36 +2774,36 @@ void Matcher::specialize_generic_vector_operands() { } uint Matcher::vector_length(const Node* n) { - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); return vt->length(); } uint Matcher::vector_length(const MachNode* use, const MachOper* opnd) { int def_idx = use->operand_index(opnd); Node* def = use->in(def_idx); - return def->bottom_type()->is_vect()->length(); + return def->bottom_type()->as_vect()->length(); } uint Matcher::vector_length_in_bytes(const Node* n) { - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); return vt->length_in_bytes(); } uint Matcher::vector_length_in_bytes(const MachNode* use, const MachOper* opnd) { uint def_idx = use->operand_index(opnd); Node* def = use->in(def_idx); - return def->bottom_type()->is_vect()->length_in_bytes(); + return def->bottom_type()->as_vect()->length_in_bytes(); } BasicType Matcher::vector_element_basic_type(const Node* n) { - const TypeVect* vt = n->bottom_type()->is_vect(); + const TypeVect* vt = n->bottom_type()->as_vect(); return vt->element_basic_type(); } BasicType Matcher::vector_element_basic_type(const MachNode* use, const MachOper* opnd) { int def_idx = use->operand_index(opnd); Node* def = use->in(def_idx); - return def->bottom_type()->is_vect()->element_basic_type(); + return def->bottom_type()->as_vect()->element_basic_type(); } bool Matcher::is_non_long_integral_vector(const Node* n) { @@ -2811,10 +2813,8 @@ bool Matcher::is_non_long_integral_vector(const Node* n) { } bool Matcher::is_encode_and_store_pattern(const Node* n, const Node* m) { - if (n == nullptr || - m == nullptr || - n->Opcode() != Op_StoreN || - !m->is_EncodeP() || + if (!Node::is_exact(n) || + !Node::is(m) || n->as_Store()->barrier_data() == 0) { return false; } @@ -2963,8 +2963,8 @@ bool Matcher::branches_to_uncommon_trap(const Node *n) { if (call && call->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) { const Type* trtype = call->in(TypeFunc::Parms)->bottom_type(); - if (trtype->isa_int() && trtype->is_int()->is_con()) { - jint tr_con = trtype->is_int()->get_con(); + if (trtype->is_int() && trtype->as_int()->is_con()) { + jint tr_con = trtype->as_int()->get_con(); Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con); Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con); assert((int)reason < (int)BitsPerInt, "recode bit map"); diff --git a/src/hotspot/share/opto/matcher.hpp b/src/hotspot/share/opto/matcher.hpp index fd91046588a3..dc0ecbbdecb1 100644 --- a/src/hotspot/share/opto/matcher.hpp +++ b/src/hotspot/share/opto/matcher.hpp @@ -330,6 +330,9 @@ class Matcher : public PhaseTransform { static bool vector_rearrange_requires_load_shuffle(BasicType elem_bt, int vlen); + // Determine whether the given node is a valid vector MLA/MLS candidate. + static bool is_multiply_accumulate_candidate(const Node* n); + // Identify if a vector mask operation prefers the input/output mask to be // saved with a predicate type or not. // - Return true if it prefers a predicate type (i.e. TypePVectMask). diff --git a/src/hotspot/share/opto/memnode.cpp b/src/hotspot/share/opto/memnode.cpp index 0f4259d3e5e2..b459ada75892 100644 --- a/src/hotspot/share/opto/memnode.cpp +++ b/src/hotspot/share/opto/memnode.cpp @@ -242,7 +242,7 @@ Node* MemNode::optimize_simple_memory_chain(Node* mchain, const TypeOopPtr* t_oo // After macro expansion, an allocation may become a call, changing the memory input to the // memory output of that call would be illegal. As a result, disallow this transformation after // macro expansion. - if (phase->is_IterGVN() && phase->C->allow_macro_nodes() && load != nullptr && load->is_Load() && !load->as_Load()->is_mismatched_access()) { + if (auto ld = isa(load); phase->is_IterGVN() && phase->C->allow_macro_nodes() && ld != nullptr && !ld->is_mismatched_access()) { is_strict_final_load = t_oop->is_ptr_to_strict_final_field(); #ifdef ASSERT if ((t_oop->is_valueklassptr() && t_oop->value_klass()->contains_field_offset(t_oop->offset())) || t_oop->is_ptr_to_boxed_value()) { @@ -309,8 +309,8 @@ Node* MemNode::optimize_simple_memory_chain(Node* mchain, const TypeOopPtr* t_oo result = proj_in->in(TypeFunc::Memory); } else if (is_strict_final_load) { Node* klass = alloc->in(AllocateNode::KlassNode); - const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr(); - if (tklass->klass_is_exact() && !tklass->exact_klass()->is_subclass_of(t_oop->is_instptr()->instance_klass())) { + const TypeKlassPtr* tklass = phase->type(klass)->as_klassptr(); + if (tklass->klass_is_exact() && !tklass->exact_klass()->is_subclass_of(t_oop->as_instptr()->instance_klass())) { // Allocation of an unrelated type, must be another object result = proj_in->in(TypeFunc::Memory); } else if (base_local != nullptr && (base_local->is_Parm() || base_local->in(0) != alloc)) { @@ -384,9 +384,9 @@ static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const T bool consistent = adr_check == nullptr || adr_check->empty() || phase->C->must_alias(adr_check, alias_idx ); // Sometimes dead array references collapse to a[-1], a[-2], or a[-3] - if( !consistent && adr_check != nullptr && !adr_check->empty() && - tp->isa_aryptr() && tp->offset() == Type::OffsetBot && - adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot && + if (!consistent && adr_check != nullptr && !adr_check->empty() && + tp->is_aryptr() && tp->offset() == Type::OffsetBot && + adr_check->is_aryptr() && adr_check->offset() != Type::OffsetBot && ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() || adr_check->offset() == oopDesc::klass_offset_in_bytes() || adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) { @@ -412,8 +412,8 @@ static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const T const TypeOopPtr *toop = tp->isa_oopptr(); if (tp->base() != Type::AnyPtr && !(toop && - toop->isa_instptr() && - toop->is_instptr()->instance_klass()->is_java_lang_Object() && + toop->is_instptr() && + toop->as_instptr()->instance_klass()->is_java_lang_Object() && toop->offset() == Type::OffsetBot)) { // IGVN _delay_transform may be set to true and if that is the case and mmem // is already a registered node then the validation inside transform will @@ -513,15 +513,15 @@ Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { // Weird access to null+offset, either is a dead unsafe access that cannot be proved to be so, or // should be folded later if (t_adr->base() == Type::AnyPtr) { - assert(t_adr->is_ptr()->ptr() == TypePtr::Null, "must be null"); + assert(t_adr->as_ptr()->ptr() == TypePtr::Null, "must be null"); return NodeSentinel; // caller will return null } // Do NOT remove or optimize the next lines: ensure a new alias index // is allocated for an oop pointer type before Escape Analysis. // Note: C++ will not remove it since the call has side effect. - if (t_adr->isa_oopptr()) { - int alias_idx = phase->C->get_alias_index(t_adr->is_ptr()); + if (t_adr->is_oopptr()) { + int alias_idx = phase->C->get_alias_index(t_adr->as_ptr()); } // Avoid independent memory operations @@ -537,7 +537,7 @@ Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { if (mem->is_MergeMem()) { MergeMemNode* mmem = mem->as_MergeMem(); - const TypePtr *tp = t_adr->is_ptr(); + const TypePtr* tp = t_adr->as_ptr(); mem = step_through_mergemem(phase, mmem, tp, in_adr_type(), tty); } @@ -683,7 +683,7 @@ bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1, // TypePtr::NULL_PTR, so we exclude that case. const Type* p1_type = p1->bottom_type(); const Type* p2_type = p2->bottom_type(); - if (p1_type != p2_type && p1_type->isa_oopptr() && p2_type->isa_oopptr() && + if (p1_type != p2_type && p1_type->is_oopptr() && p2_type->is_oopptr() && (!p1_type->maybe_null() || !p2_type->maybe_null()) && p1_type->join(p2_type)->empty()) { return true; @@ -731,7 +731,7 @@ Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem); jlong elemsize = type2aelembytes(ary_elem); - const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); + const TypeX* ld_offs_t = phase->type(ld_offs)->as_intptr_t(); const TypeInt* sizetype = ary_t->size(); if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) { @@ -742,32 +742,32 @@ Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node } // The load could be out-of-bounds. It must not be hoisted but must remain // dependent on the runtime range check. This is achieved by returning null. - } else if (mem->is_Proj() && mem->in(0) != nullptr && mem->in(0)->is_ArrayCopy()) { - ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy(); - - if (ac->is_arraycopy_validated() || - ac->is_copyof_validated() || - ac->is_copyofrange_validated()) { - Node* ld_addp = in(MemNode::Address); - if (ld_addp->is_AddP()) { - Node* ld_base = ld_addp->in(AddPNode::Address); - Node* ld_offs = ld_addp->in(AddPNode::Offset); - - Node* dest = ac->in(ArrayCopyNode::Dest); - - if (dest == ld_base) { - const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); - assert(!ld_offs_t->empty(), "dead reference should be checked already"); - // Take into account vector or unsafe access size - jlong ld_size_in_bytes = (jlong)memory_size(); - jlong offset_hi = ld_offs_t->_hi + ld_size_in_bytes - 1; - offset_hi = MIN2(offset_hi, (jlong)(TypeX::MAX->_hi)); // Take care for overflow in 32-bit VM - if (ac->modifies(ld_offs_t->_lo, (intptr_t)offset_hi, phase, can_see_stored_value)) { - return ac; - } - if (!can_see_stored_value) { - mem = ac->in(TypeFunc::Memory); - return ac; + } else if (mem->is_Proj()) { + if (ArrayCopyNode* ac = isa(mem->in(0)); ac != nullptr) { + if (ac->is_arraycopy_validated() || + ac->is_copyof_validated() || + ac->is_copyofrange_validated()) { + Node* ld_addp = in(MemNode::Address); + if (ld_addp->is_AddP()) { + Node* ld_base = ld_addp->in(AddPNode::Address); + Node* ld_offs = ld_addp->in(AddPNode::Offset); + + Node* dest = ac->in(ArrayCopyNode::Dest); + + if (dest == ld_base) { + const TypeX* ld_offs_t = phase->type(ld_offs)->as_intptr_t(); + assert(!ld_offs_t->empty(), "dead reference should be checked already"); + // Take into account vector or unsafe access size + jlong ld_size_in_bytes = (jlong)memory_size(); + jlong offset_hi = ld_offs_t->_hi + ld_size_in_bytes - 1; + offset_hi = MIN2(offset_hi, (jlong)(TypeX::MAX->_hi)); // Take care for overflow in 32-bit VM + if (ac->modifies(ld_offs_t->_lo, (intptr_t)offset_hi, phase, can_see_stored_value)) { + return ac; + } + if (!can_see_stored_value) { + mem = ac->in(TypeFunc::Memory); + return ac; + } } } } @@ -777,21 +777,13 @@ Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node } ArrayCopyNode* MemNode::find_array_copy_clone(Node* ld_alloc, Node* mem) const { - if (mem->is_Proj() && mem->in(0) != nullptr && (mem->in(0)->Opcode() == Op_MemBarStoreStore || - mem->in(0)->Opcode() == Op_MemBarCPUOrder)) { + if (mem->is_Proj() && (is_exact(mem->in(0)) || is_exact(mem->in(0)))) { if (ld_alloc != nullptr) { // Check if there is an array copy for a clone Node* mb = mem->in(0); ArrayCopyNode* ac = nullptr; - if (mb->in(0) != nullptr && mb->in(0)->is_Proj() && - mb->in(0)->in(0) != nullptr && mb->in(0)->in(0)->is_ArrayCopy()) { - ac = mb->in(0)->in(0)->as_ArrayCopy(); - } else { - Node* control_proj_ac = mb->in(0); - - if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) { - ac = control_proj_ac->in(0)->as_ArrayCopy(); - } + if (ProjNode* control_proj_ac = isa(mb->in(0)); control_proj_ac != nullptr) { + ac = isa(control_proj_ac->in(0)); } if (ac != nullptr && ac->is_clonebasic()) { @@ -876,7 +868,7 @@ const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_c // The type of the address must be contained in the adr_type, // disregarding "null"-ness. // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.) - const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr(); + const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->as_ptr(); assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(), "real address must not escape from expected memory type"); } @@ -1133,31 +1125,31 @@ bool LoadNode::is_immutable_value(Node* adr) { Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo, ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) { Compile* C = gvn.C; - assert(adr->is_top() || C->get_alias_index(gvn.type(adr)->is_ptr(), true) == C->get_alias_index(adr_type, true), "adr and adr_type must agree"); + assert(adr->is_top() || C->get_alias_index(gvn.type(adr)->as_ptr(), true) == C->get_alias_index(adr_type, true), "adr and adr_type must agree"); // sanity check the alias category against the created node type - assert(!(adr_type->isa_oopptr() && + assert(!(adr_type->is_oopptr() && adr_type->offset() == oopDesc::klass_offset_in_bytes()), "use LoadKlassNode instead"); - assert(!(adr_type->isa_aryptr() && + assert(!(adr_type->is_aryptr() && adr_type->offset() == arrayOopDesc::length_offset_in_bytes()), "use LoadRangeNode instead"); // Check control edge of raw loads assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw || // oop will be recorded in oop map if load crosses safepoint - rt->isa_oopptr() || is_immutable_value(adr), + rt->is_oopptr() || is_immutable_value(adr), "raw memory operations should have control edge"); LoadNode* load = nullptr; switch (bt) { - case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; - case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; - case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; - case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; - case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; - case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break; + case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; + case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; + case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; + case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; + case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; + case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->as_long(), mo, control_dependency, require_atomic_access); break; case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break; case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic_access); break; - case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); break; + case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->as_ptr(), mo, control_dependency); break; case T_ARRAY: case T_OBJECT: case T_NARROWOOP: @@ -1168,7 +1160,7 @@ Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypeP #endif { assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop"); - load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); + load = new LoadPNode(ctl, mem, adr, adr_type, rt->as_ptr(), mo, control_dependency); } break; default: @@ -1204,8 +1196,8 @@ static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) { bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile(); bool is_stable_ary = FoldStableValues && - (tp != nullptr) && (tp->isa_aryptr() != nullptr) && - tp->isa_aryptr()->is_stable(); + (tp != nullptr) && tp->is_aryptr() && + tp->as_aryptr()->is_stable(); return (eliminate_boxing && non_volatile) || is_stable_ary || tp->is_valueklassptr(); } @@ -1259,8 +1251,8 @@ Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const { addp->set_req(AddPNode::Base, src); addp->set_req(AddPNode::Address, src); - const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr(); - BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type(); + const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->as_aryptr(); + BasicType ary_elem = ary_t->elem()->array_element_basic_type(); if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT; uint shift = ary_t->is_flat() ? ary_t->flat_log_elem_size() : exact_log2(type2aelembytes(ary_elem)); @@ -1276,7 +1268,7 @@ Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const { } addp = phase->transform(addp); #ifdef ASSERT - const TypePtr* adr_type = phase->type(addp)->is_ptr(); + const TypePtr* adr_type = phase->type(addp)->as_ptr(); ld->_adr_type = adr_type; #endif ld->set_req(MemNode::Address, addp); @@ -1497,7 +1489,7 @@ Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const { } } else { // TODO: materialize all-zero vector constant - assert(!isa_Load() || as_Load()->type()->isa_vect(), ""); + assert(!is_Load() || as_Load()->type()->is_vect(), ""); } } @@ -1519,8 +1511,8 @@ Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const { (tp != nullptr) && tp->is_ptr_to_boxed_value()) { intptr_t ignore = 0; Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore); - if (base != nullptr && base->is_Proj() && - base->as_Proj()->_con == TypeFunc::Parms && + if (auto base_proj = isa(base); base_proj != nullptr && + base_proj->_con == TypeFunc::Parms && base->in(0)->is_CallStaticJava() && base->in(0)->as_CallStaticJava()->is_boxing_method()) { return base->in(0)->in(TypeFunc::Parms); @@ -1583,7 +1575,7 @@ Node* LoadNode::Identity(PhaseGVN* phase) { return this; } - if (phase->type(value)->isa_ptr() && phase->type(this)->isa_narrowoop()) { + if (phase->type(value)->is_ptr() && phase->type(this)->is_narrowoop()) { return this; } // (This works even when value is a Con, but LoadNode::Value @@ -1602,7 +1594,7 @@ Node* LoadNode::Identity(PhaseGVN* phase) { // instance's field to avoid infinite generation of phis in a loop. Node *region = mem->in(0); if (is_instance_field_load_with_local_phi(region)) { - const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr(); + const TypeOopPtr* addr_t = in(Address)->bottom_type()->as_oopptr(); int this_index = phase->C->get_alias_index(addr_t); int this_offset = addr_t->offset(); int this_iid = addr_t->instance_id(); @@ -1647,7 +1639,7 @@ Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) { return gvn.C->top(); } return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), - mem_t->is_ptr(), rt, bt, _mo, _control_dependency, + mem_t->as_ptr(), rt, bt, _mo, _control_dependency, false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); } @@ -1671,7 +1663,7 @@ Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) { return gvn.C->top(); } return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), - mem_t->is_ptr(), rt, bt, _mo, _control_dependency, + mem_t->as_ptr(), rt, bt, _mo, _control_dependency, false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); } @@ -1679,8 +1671,7 @@ Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) { BasicType bt = rt->basic_type(); assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt)); bool is_mismatched = is_mismatched_access(); - const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); - if (raw_type == nullptr) { + if (!gvn.type(in(MemNode::Memory))->is_rawptr()) { is_mismatched = true; // conservatively match all non-raw accesses as mismatched } const int op = Opcode(); @@ -1691,7 +1682,7 @@ Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) { return gvn.C->top(); } return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), - mem_t->is_ptr(), rt, bt, _mo, _control_dependency, + mem_t->as_ptr(), rt, bt, _mo, _control_dependency, require_atomic_access, is_unaligned_access(), is_mismatched); } @@ -1706,11 +1697,10 @@ Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Ty return gvn.C->top(); } StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), - mem_t->is_ptr(), val, bt, _mo, require_atomic_access); + mem_t->as_ptr(), val, bt, _mo, require_atomic_access); bool is_mismatched = is_mismatched_access(); - const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); - if (raw_type == nullptr) { + if (!gvn.type(in(MemNode::Memory))->is_rawptr()) { is_mismatched = true; // conservatively match all non-raw accesses as mismatched } if (is_mismatched) { @@ -1748,7 +1738,7 @@ Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) { } AddPNode* address = base->in(Address)->as_AddP(); Node* cache_base = address->in(AddPNode::Base); - if ((cache_base != nullptr) && cache_base->is_DecodeN()) { + if (is(cache_base)) { // Get ConP node which is static 'cache' field. cache_base = cache_base->in(1); } @@ -1913,7 +1903,7 @@ Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_ Compile* C = phase->C; intptr_t ignore = 0; Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); - bool base_is_phi = (base != nullptr) && base->is_Phi(); + bool base_is_phi = is(base); bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() && (base != nullptr) && (base == address->in(AddPNode::Base)) && phase->type(base)->higher_equal(TypePtr::NOTNULL); @@ -2033,7 +2023,7 @@ Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_ Node* the_clone = nullptr; Node* in = region->in(i); if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl && - in != nullptr && in->is_OuterStripMinedLoop()) { + is(in)) { // No node should go in the outer strip mined loop in = in->in(LoopNode::EntryControl); } @@ -2146,13 +2136,13 @@ Node* LoadNode::Ideal_load_common(PhaseGVN* phase, bool can_reshape) { Node* ctrl = in(MemNode::Control); Node* address = in(MemNode::Address); - bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) && - phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes()); + bool addr_mark = (phase->type(address)->is_oopptr() || phase->type(address)->is_narrowoop()) && + phase->type(address)->as_ptr()->offset() == oopDesc::mark_offset_in_bytes(); // Skip up past a SafePoint control. Cannot do this for Stores because // pointer stores & cardmarks must stay on the same side of a SafePoint. - if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint && - phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw && + if (is_exact(ctrl) && + phase->C->get_alias_index(phase->type(address)->as_ptr()) != Compile::AliasIdxRaw && !addr_mark && (depends_only_on_test() || has_unknown_control_dependency())) { ctrl = ctrl->in(0); @@ -2163,7 +2153,7 @@ Node* LoadNode::Ideal_load_common(PhaseGVN* phase, bool can_reshape) { intptr_t ignore = 0; Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); if (base != nullptr && - phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) { + phase->C->get_alias_index(phase->type(address)->as_ptr()) != Compile::AliasIdxRaw) { // Check for useless control edge in some common special cases if (in(MemNode::Control) != nullptr // TODO 8350865 Can we re-enable this? @@ -2212,7 +2202,7 @@ Node* LoadNode::Ideal_load_common(PhaseGVN* phase, bool can_reshape) { // Is there a dominating load that loads the same value? Leave // anything that is not a load of a field/array element (like // barriers etc.) alone - if (in(0) != nullptr && !in_adr_type()->isa_rawptr() && can_reshape) { + if (in(0) != nullptr && !in_adr_type()->is_rawptr() && can_reshape) { for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { Node* use = mem->fast_out(i); if (use != this && @@ -2280,10 +2270,10 @@ LoadNode::load_array_final_field(const TypeKlassPtr *tkls, tkls->offset() != in_bytes(Klass::prototype_header_offset()), "must not happen"); - if (tkls->isa_instklassptr() && tkls->offset() == in_bytes(InstanceKlass::access_flags_offset())) { + if (tkls->is_instklassptr() && tkls->offset() == in_bytes(InstanceKlass::access_flags_offset())) { // The field is InstanceKlass::_access_flags. Return its (constant) value. assert(Opcode() == Op_LoadUS, "must load an unsigned short from _access_flags"); - ciInstanceKlass* iklass = tkls->is_instklassptr()->instance_klass(); + ciInstanceKlass* iklass = tkls->as_instklassptr()->instance_klass(); return TypeInt::make(iklass->access_flags()); } if (tkls->offset() == in_bytes(Klass::misc_flags_offset())) { @@ -2321,7 +2311,7 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // If load can see a previous constant store, use that. Node* value = can_see_stored_value_through_membars(mem, phase); if (value != nullptr && value->is_Con()) { - if (phase->type(value)->isa_ptr() && _type->isa_narrowoop()) { + if (phase->type(value)->is_ptr() && _type->is_narrowoop()) { return phase->type(value)->make_narrowoop(); } else { assert(value->bottom_type()->higher_equal(_type), "sanity"); @@ -2329,8 +2319,8 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { } } // Try to guess loaded type from pointer type - if (tp->isa_aryptr()) { - const TypeAryPtr* ary = tp->is_aryptr(); + if (tp->is_aryptr()) { + const TypeAryPtr* ary = tp->as_aryptr(); const Type* t = ary->elem(); // Determine whether the reference is beyond the header or not, by comparing @@ -2372,8 +2362,8 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // In fact, that could have been the original type of p1, and p1 could have // had an original form like p1:(AddP x x (LShiftL quux 3)), where the // expression (LShiftL quux 3) independently optimized to the constant 8. - if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr) - && (_type->isa_vect() == nullptr) + if (!t->is_int() && !t->is_long() + && !_type->is_vect() && ary->is_not_flat() && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) { // t might actually be lower than _type, if _type is a unique @@ -2389,7 +2379,7 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { if (phase->C->eliminate_boxing() && adr->is_AddP()) { // The pointers in the autobox arrays are always non-null Node* base = adr->in(AddPNode::Base); - if ((base != nullptr) && base->is_DecodeN()) { + if (is(base)) { // Get LoadN node which loads IntegerCache.cache field base = base->in(1); } @@ -2406,22 +2396,22 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { } } } else if (tp->base() == Type::InstPtr) { - assert( off != Type::OffsetBot || - // arrays can be cast to Objects - !tp->isa_instptr() || - tp->is_instptr()->instance_klass()->is_java_lang_Object() || - // Default value load - tp->is_instptr()->instance_klass() == ciEnv::current()->Class_klass() || - // unsafe field access may not have a constant offset - is_unsafe_access(), - "Field accesses must be precise" ); + assert(off != Type::OffsetBot || + // arrays can be cast to Objects + !tp->is_instptr() || + tp->as_instptr()->instance_klass()->is_java_lang_Object() || + // Default value load + tp->as_instptr()->instance_klass() == ciEnv::current()->Class_klass() || + // unsafe field access may not have a constant offset + is_unsafe_access(), + "Field accesses must be precise"); // For oop loads, we expect the _type to be precise. - const TypeInstPtr* tinst = tp->is_instptr(); + const TypeInstPtr* tinst = tp->as_instptr(); BasicType bt = value_basic_type(); // Fold the field map loads only when stable folding is enabled - if (FoldStableValues && tinst != nullptr) { + if (FoldStableValues) { ciInstanceKlass* ik = tinst->instance_klass(); int offset = tinst->offset(); if (ik == phase->C->env()->Class_klass()) { @@ -2444,9 +2434,9 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { } } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) { assert(off != Type::OffsetBot || - !tp->isa_instklassptr() || + !tp->is_instklassptr() || // arrays can be cast to Objects - tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() || + tp->as_instklassptr()->instance_klass()->is_java_lang_Object() || // also allow array-loading from the primary supertype // array during subtype checks Opcode() == Op_LoadKlass, @@ -2489,10 +2479,10 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { } if (klass->is_obj_array_klass() && tkls->offset() == in_bytes(ObjArrayKlass::next_refined_array_klass_offset())) { // Fold loads from LibraryCallKit::load_default_refined_array_klass - return tkls->is_aryklassptr()->cast_to_refined_array_klass_ptr(); + return tkls->as_aryklassptr()->cast_to_refined_array_klass_ptr(); } if (klass->is_array_klass() && tkls->offset() == in_bytes(ObjArrayKlass::properties_offset())) { - assert(klass->is_type_array_klass() || tkls->is_aryklassptr()->is_refined_type(), "Must be a refined array klass pointer"); + assert(klass->is_type_array_klass() || tkls->as_aryklassptr()->is_refined_type(), "Must be a refined array klass pointer"); return TypeInt::make((jint)klass->as_array_klass()->properties().value()); } if (klass->is_flat_array_klass() && tkls->offset() == in_bytes(FlatArrayKlass::layout_kind_offset())) { @@ -2527,13 +2517,13 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // than or equal to its super depth are correct. if (tkls->is_loaded()) { ciKlass* klass = nullptr; - if (tkls->isa_instklassptr()) { - klass = tkls->is_instklassptr()->instance_klass(); + if (tkls->is_instklassptr()) { + klass = tkls->as_instklassptr()->instance_klass(); } else { int dims; - const Type* inner = tkls->is_aryklassptr()->base_element_type(dims); - if (inner->isa_instklassptr()) { - klass = inner->is_instklassptr()->instance_klass(); + const Type* inner = tkls->as_aryklassptr()->base_element_type(dims); + if (inner->is_instklassptr()) { + klass = inner->as_instklassptr()->instance_klass(); klass = ciObjArrayKlass::make(klass, dims); } } @@ -2556,8 +2546,8 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // we can give the layout_helper a positive interval type. // This will help short-circuit some reflective code. if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) && - tkls->isa_instklassptr() && // not directly typed as an array - !tkls->is_instklassptr()->might_be_an_array() // not the supertype of all T[] (java.lang.Object) or has an interface that is not Serializable or Cloneable + tkls->is_instklassptr() && // not directly typed as an array + !tkls->as_instklassptr()->might_be_an_array() // not the supertype of all T[] (java.lang.Object) or has an interface that is not Serializable or Cloneable ) { assert(Opcode() == Op_LoadI, "must load an int from _layout_helper"); jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false); @@ -2575,7 +2565,7 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // 3. Load has no matching store, i.e. the input is the initial memory state const TypeOopPtr* tinst = tp->isa_oopptr(); bool is_not_header = (tinst != nullptr) && tinst->is_known_instance_field(); - bool is_not_vect = (_type->isa_vect() == nullptr); + bool is_not_vect = !_type->is_vect(); if (is_not_header && is_not_vect) { Node* mem = in(MemNode::Memory); if (mem->is_Parm() && mem->in(0)->is_Start()) { @@ -2584,11 +2574,11 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { // Scalar replacement assumes that arrays are zero-initialized, which is not true for null-free arrays. // ConnectionGraph::split_unique_types will re-wire the memory of loads from such arrays around the allocation. // TestArrays::test6 and test152 and TestBasicFunctionality::test20 are affected by this. - if (tp->isa_aryptr() && tp->is_aryptr()->is_flat() && tp->is_aryptr()->is_null_free()) { + if (tp->is_aryptr() && tp->as_aryptr()->is_flat() && tp->as_aryptr()->is_null_free()) { intptr_t offset = 0; Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); AllocateNode* alloc = AllocateNode::Ideal_allocation(base); - if (alloc != nullptr && alloc->is_AllocateArray() && alloc->in(AllocateNode::InitValue) != nullptr) { + if (is(alloc) && alloc->in(AllocateNode::InitValue) != nullptr) { return _type; } } @@ -2759,7 +2749,7 @@ const Type* LoadSNode::Value(PhaseGVN* phase) const { Node* LoadNNode::Ideal(PhaseGVN* phase, bool can_reshape) { // Can see the corresponding value, may need to add an EncodeP Node* value = can_see_stored_value_through_membars(in(Memory), phase); - if (value != nullptr && phase->type(value)->isa_ptr() && type()->isa_narrowoop()) { + if (value != nullptr && phase->type(value)->is_ptr() && type()->is_narrowoop()) { return new EncodePNode(value, type()); } @@ -2796,7 +2786,7 @@ const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { Node *adr = in(MemNode::Address); const Type *t2 = phase->type( adr ); if (t2 == Type::TOP) return Type::TOP; - const TypePtr *tp = t2->is_ptr(); + const TypePtr* tp = t2->as_ptr(); if (TypePtr::is_top(tp->ptr()) || tp->ptr() == TypePtr::Null) return Type::TOP; // Return a more precise klass, if possible @@ -2841,7 +2831,7 @@ const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { const TypeAryPtr* tary = tp->isa_aryptr(); if (tary != nullptr && tary->offset() == oopDesc::klass_offset_in_bytes()) { - return tary->as_klass_type(true)->is_aryklassptr(); + return tary->as_klass_type(true)->as_aryklassptr(); } // Check for loading klass from an array klass @@ -2849,7 +2839,7 @@ const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { if (tkls != nullptr && !StressReflectiveCode) { if (!tkls->is_loaded()) return _type; // Bail out if not loaded - if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() && + if (tkls->is_aryklassptr() && tkls->as_aryklassptr()->elem()->is_klassptr() && tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) { // // Always returning precise element type is incorrect, // // e.g., element type could be object and array may contain strings @@ -2857,18 +2847,18 @@ const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { // The array's TypeKlassPtr was declared 'precise' or 'not precise' // according to the element type's subclassing. - return tkls->is_aryklassptr()->elem()->isa_klassptr()->cast_to_exactness(tkls->klass_is_exact()); + return tkls->as_aryklassptr()->elem()->as_klassptr()->cast_to_exactness(tkls->klass_is_exact()); } - if (tkls->isa_aryklassptr() != nullptr && tkls->klass_is_exact() && + if (tkls->is_aryklassptr() && tkls->klass_is_exact() && !tkls->exact_klass()->is_type_array_klass() && tkls->offset() == in_bytes(Klass::super_offset())) { // We are loading the super klass of a refined array klass, return the non-refined klass pointer - assert(tkls->is_aryklassptr()->is_refined_type(), "Must be a refined array klass pointer"); - return tkls->is_aryklassptr()->with_offset(0)->cast_to_non_refined(); + assert(tkls->as_aryklassptr()->is_refined_type(), "Must be a refined array klass pointer"); + return tkls->as_aryklassptr()->with_offset(0)->cast_to_non_refined(); } - if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() && + if (tkls->is_instklassptr() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::super_offset())) { - ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super(); + ciKlass* sup = tkls->as_instklassptr()->instance_klass()->super(); // The field is Klass::_super. Return its (constant) value. // (Folds up the 2nd indirection in aClassConstant.getSuperClass().) return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR; @@ -2934,7 +2924,7 @@ Node* LoadNode::find_known_klass(PhaseGVN* phase) const { // constant, it was obtained via load_klass which returns the refined type // and '.java_mirror.as_klass' should return the Java type instead. - if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass() + if (toop->is_instptr() && toop->as_instptr()->instance_klass() == phase->C->env()->Class_klass() && offset == java_lang_Class::klass_offset()) { if (base->is_Load()) { Node* base2 = base->in(MemNode::Address); @@ -2942,12 +2932,12 @@ Node* LoadNode::find_known_klass(PhaseGVN* phase) const { Node* adr2 = base2->in(MemNode::Address); const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr(); if (tkls != nullptr && !tkls->empty() - && ((tkls->isa_instklassptr() && !tkls->is_instklassptr()->might_be_an_array())) + && (tkls->is_instklassptr() && !tkls->as_instklassptr()->might_be_an_array()) && adr2->is_AddP()) { int mirror_field = in_bytes(Klass::java_mirror_offset()); if (tkls->offset() == mirror_field) { #ifdef ASSERT - const TypeKlassPtr* tkls2 = phase->type(adr2->in(AddPNode::Address))->is_klassptr(); + const TypeKlassPtr* tkls2 = phase->type(adr2->in(AddPNode::Address))->as_klassptr(); assert(tkls2->offset() == 0, "not a load of java_mirror"); #endif assert(adr2->in(AddPNode::Base)->is_top(), "not an off heap load"); @@ -2977,7 +2967,7 @@ LoadNode* LoadNode::clone_pinned() const { // need to pin it. LoadNode* LoadNode::pin_node_under_control_impl() const { const TypePtr* adr_type = this->in_adr_type(); - if (adr_type != nullptr && adr_type->isa_aryptr()) { + if (adr_type != nullptr && adr_type->is_aryptr()) { // Only array accesses have dependencies on their control input return clone_pinned(); } @@ -2998,7 +2988,7 @@ Node* LoadNKlassNode::Ideal(PhaseGVN* phase, bool can_reshape) { if (k != nullptr) { const Type* t = phase->type(k); if (t != Type::TOP) { - assert(t->isa_klassptr(), "must be a klass pointer"); + assert(t->is_klassptr(), "must be a klass pointer"); return new EncodePKlassNode(k, t->make_narrowklass()); } } @@ -3021,7 +3011,7 @@ const Type* LoadNKlassNode::Value(PhaseGVN* phase) const { Node* LoadNKlassNode::Identity(PhaseGVN* phase) { Node* x = klass_identity_common(phase); const Type* t = phase->type(x); - if (t == Type::TOP || t->isa_narrowklass()) { return x; } + if (t == Type::TOP || t->is_narrowklass()) { return x; } return this; } @@ -3033,7 +3023,7 @@ const Type* LoadRangeNode::Value(PhaseGVN* phase) const { Node *adr = in(MemNode::Address); const Type *t2 = phase->type( adr ); if( t2 == Type::TOP ) return Type::TOP; - const TypePtr *tp = t2->is_ptr(); + const TypePtr* tp = t2->as_ptr(); if (TypePtr::is_top(tp->ptr())) return Type::TOP; const TypeAryPtr *tap = tp->isa_aryptr(); if( !tap ) return _type; @@ -3109,10 +3099,10 @@ Node* LoadRangeNode::Identity(PhaseGVN* phase) { //============================================================================= //---------------------------StoreNode::make----------------------------------- // Polymorphic factory method: -StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access) { +StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access, bool store_special) { assert((mo == unordered || mo == release), "unexpected"); Compile* C = gvn.C; - assert(adr_type == nullptr || adr->is_top() || C->get_alias_index(gvn.type(adr)->is_ptr()) == C->get_alias_index(adr_type), "adr and adr_type must agree"); + assert(adr_type == nullptr || adr->is_top() || C->get_alias_index(gvn.type(adr)->as_ptr()) == C->get_alias_index(adr_type), "adr and adr_type must agree"); assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw || ctl != nullptr, "raw memory operations should have control edge"); @@ -3122,7 +3112,12 @@ StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const case T_INT: return new StoreINode(ctl, mem, adr, adr_type, val, mo); case T_CHAR: case T_SHORT: return new StoreCNode(ctl, mem, adr, adr_type, val, mo); - case T_LONG: return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); + case T_LONG: { + if (store_special) { + return new StoreLSpecialNode(ctl, mem, adr, adr_type, val, mo); + } + return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); + } case T_FLOAT: return new StoreFNode(ctl, mem, adr, adr_type, val, mo); case T_DOUBLE: return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); case T_METADATA: @@ -3134,7 +3129,7 @@ StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop())); return new StoreNNode(ctl, mem, adr, adr_type, val, mo); } else if (adr->bottom_type()->is_ptr_to_narrowklass() || - (val->bottom_type()->isa_klassptr() && adr->bottom_type()->isa_rawptr())) { + (val->bottom_type()->is_klassptr() && adr->bottom_type()->is_rawptr())) { val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass())); return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo); } @@ -3480,8 +3475,7 @@ bool MergePrimitiveStores::is_con_RShift(const Node* n, Node const*& base_out, j return shift_out >= 0; } - if (phase->type(n)->isa_int() != nullptr || - phase->type(n)->isa_long() != nullptr) { + if (phase->type(n)->is_int() || phase->type(n)->is_long()) { // (base >> 0) base_out = n; shift_out = 0; @@ -3699,7 +3693,7 @@ Node* MergePrimitiveStores::make_merged_input_value(const Node_Listtype(merged_input_value)->isa_long() != nullptr && new_memory_size <= 4) { + if (_phase->type(merged_input_value)->is_long() && new_memory_size <= 4) { // Example: // // long base = ...; @@ -3709,8 +3703,8 @@ Node* MergePrimitiveStores::make_merged_input_value(const Node_Listtransform(new ConvL2INode(merged_input_value)); } - assert((_phase->type(merged_input_value)->isa_int() != nullptr && new_memory_size <= 4) || - (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size == 8), + assert((_phase->type(merged_input_value)->is_int() && new_memory_size <= 4) || + (_phase->type(merged_input_value)->is_long() && new_memory_size == 8), "merged_input_value is either int or long, and new_memory_size is small enough"); if (_value_order == ValueOrder::Reverse) { @@ -3915,6 +3909,25 @@ const Type* StoreNode::Value(PhaseGVN* phase) const { if( t2 == Type::TOP ) return Type::TOP; const Type *t3 = phase->type( in(MemNode::ValueIn) ); if( t3 == Type::TOP ) return Type::TOP; + Node* addr = in(MemNode::Address); + // Writing to an oop header only happens during allocation as a raw memory Store. If that Store is to the header but + // not a raw memory Store, then it must be a dead Store. + const TypeOopPtr* addr_t = phase->type(addr)->isa_oopptr(); + if (addr_t != nullptr) { + int offset = addr_t->offset(); + if (offset != Type::OffsetBot) { + if (addr_t->isa_aryptr()) { + if (offset <= arrayOopDesc::length_offset_in_bytes()) { + return Type::TOP; + } + } else if (addr_t->isa_instptr()) { + if (offset < instanceOopDesc::base_offset_in_bytes()) { + return Type::TOP; + } + } + } + } + return Type::MEMORY; } @@ -4581,7 +4594,7 @@ Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, Node* adr = make_address(dest, phase->MakeConX(offset), raw_base, phase); const TypePtr* atp = TypeRawPtr::BOTTOM; if (val != nullptr) { - assert(phase->type(val)->isa_narrowoop(), "should be narrow oop"); + assert(phase->type(val)->is_narrowoop(), "should be narrow oop"); mem = new StoreNNode(ctl, mem, adr, atp, val, MemNode::unordered); } else { assert(raw_val == nullptr, "val may not be null"); @@ -4653,7 +4666,7 @@ Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, Node* adr = make_address(dest, phase->MakeConX(done_offset), raw_base, phase); const TypePtr* atp = TypeRawPtr::BOTTOM; if (val != nullptr) { - assert(phase->type(val)->isa_narrowoop(), "should be narrow oop"); + assert(phase->type(val)->is_narrowoop(), "should be narrow oop"); mem = new StoreNNode(ctl, mem, adr, atp, val, MemNode::unordered); } else { assert(raw_val == nullptr, "val may not be null"); @@ -4798,7 +4811,7 @@ Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) { } progress = true; } - if (my_mem != nullptr && my_mem->is_Mem()) { + if (is(my_mem)) { const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr(); // Check for scalar replaced object reference. if( t_oop != nullptr && t_oop->is_known_instance_field() && @@ -4810,8 +4823,8 @@ Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) { } else if (opc == Op_MemBarRelease || (UseStoreStoreForCtor && opc == Op_MemBarStoreStore)) { // Final field stores. Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent)); - if ((alloc != nullptr) && alloc->is_Allocate() && - alloc->as_Allocate()->does_not_escape_thread()) { + if (AllocateNode* allocate = isa(alloc); allocate != nullptr && + allocate->does_not_escape_thread()) { // The allocated object does not escape. eliminate = true; } @@ -5227,7 +5240,7 @@ intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool if (st->req() != MemNode::ValueIn + 1) return FAIL; // an inscrutable StoreNode (card mark?) Node* ctl = st->in(MemNode::Control); - if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this)) + if (!(is(ctl) && ctl->in(0) == this)) return FAIL; // must be unconditional after the initialization Node* mem = st->in(MemNode::Memory); if (!(mem->is_Proj() && mem->in(0) == this)) @@ -5424,7 +5437,6 @@ Node* InitializeNode::make_raw_address(intptr_t offset, PhaseGVN* phase) { Node* addr = in(RawAddress); if (offset != 0) { - Compile* C = phase->C; addr = phase->transform(AddPNode::make_off_heap(addr, phase->MakeConX(offset))); } return addr; @@ -5589,8 +5601,8 @@ InitializeNode::coalesce_subword_stores(intptr_t header_size, jlong con = 0; switch (type) { - case T_INT: con = val->is_int()->get_con(); break; - case T_LONG: con = val->is_long()->get_con(); break; + case T_INT: con = val->as_int()->get_con(); break; + case T_LONG: con = val->as_long()->get_con(); break; case T_FLOAT: con = jint_cast(val->getf()); break; case T_DOUBLE: con = jlong_cast(val->getd()); break; default: continue; //skip (odd store type) @@ -5621,12 +5633,12 @@ InitializeNode::coalesce_subword_stores(intptr_t header_size, st = nodes[j]; st_off -= BytesPerInt; con = intcon[0]; - if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) { + if (con != 0 && is_exact(st)) { assert(st_off >= header_size, "still ignoring header"); assert(get_store_offset(st, phase) == st_off, "must be"); assert(in(i-1) == zmem, "must be"); DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn))); - assert(con == tcon->is_int()->get_con(), "must be"); + assert(con == tcon->as_int()->get_con(), "must be"); // Undo the effects of the previous loop trip, which swallowed st: intcon[0] = 0; // undo store_constant() set_req(i-1, st); // undo set_req(i, zmem) @@ -5948,9 +5960,9 @@ Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr, if (zeroes_done + BytesPerLong >= size_limit) { AllocateNode* alloc = allocation(); assert(alloc != nullptr, "must be present"); - if (alloc != nullptr && alloc->Opcode() == Op_Allocate) { + if (is_exact(alloc)) { Node* klass_node = alloc->in(AllocateNode::KlassNode); - ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass(); + ciKlass* k = phase->type(klass_node)->as_instklassptr()->instance_klass(); if (zeroes_done == k->layout_helper()) zeroes_done = size_limit; } @@ -6152,8 +6164,7 @@ MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) { } assert(empty_memory() == empty_mem, ""); - if( new_base != nullptr && new_base->is_MergeMem() ) { - MergeMemNode* mdef = new_base->as_MergeMem(); + if (MergeMemNode* mdef = isa(new_base); mdef != nullptr) { assert(mdef->empty_memory() == empty_mem, "consistent sentinels"); for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) { mms.set_memory(mms.memory2()); @@ -6215,11 +6226,7 @@ Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) { if (old_base == empty_mem) return nullptr; // Dead memory path. - MergeMemNode* old_mbase; - if (old_base != nullptr && old_base->is_MergeMem()) - old_mbase = old_base->as_MergeMem(); - else - old_mbase = nullptr; + MergeMemNode* old_mbase = isa(old_base); Node* new_base = old_base; // simplify stacked MergeMems in base memory @@ -6246,11 +6253,7 @@ Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) { // simplify stacked MergeMems Node* new_mem = old_mem; - MergeMemNode* old_mmem; - if (old_mem != nullptr && old_mem->is_MergeMem()) - old_mmem = old_mem->as_MergeMem(); - else - old_mmem = nullptr; + MergeMemNode* old_mmem = isa(old_mem); if (old_mmem == this) { // This can happen if loops break up and safepoints disappear. // A merge of BotPtr (default) with a RawPtr memory derived from a diff --git a/src/hotspot/share/opto/memnode.hpp b/src/hotspot/share/opto/memnode.hpp index 36e78361c1fe..0fc52277c199 100644 --- a/src/hotspot/share/opto/memnode.hpp +++ b/src/hotspot/share/opto/memnode.hpp @@ -654,10 +654,6 @@ class StoreNode : public MemNode { : MemNode(c, mem, adr, at, val), _mo(mo) { init_class_id(Class_Store); } - StoreNode(Node *c, Node *mem, Node *adr, const TypePtr* at, Node *val, Node *oop_store, MemOrd mo) - : MemNode(c, mem, adr, at, val, oop_store), _mo(mo) { - init_class_id(Class_Store); - } inline bool is_unordered() const { return !is_release(); } inline bool is_release() const { @@ -689,7 +685,8 @@ class StoreNode : public MemNode { // point to a new object and may become externally visible. static StoreNode* make(PhaseGVN& gvn, Node* c, Node* mem, Node* adr, const TypePtr* at, Node* val, BasicType bt, - MemOrd mo, bool require_atomic_access = false); + MemOrd mo, bool require_atomic_access = false, + bool store_special = false); virtual uint hash() const; // Check the type @@ -782,19 +779,22 @@ class StoreLNode : public StoreNode { class StoreLSpecialNode : public StoreNode { public: - StoreLSpecialNode(Node* c, Node* mem, Node* adr, const TypePtr* at, Node* val, Node* oop_off, MemOrd mo) + enum { + OopOffset = ValueIn + 1, + FirstOop, + SecondOop, + }; + + StoreLSpecialNode(Node* c, Node* mem, Node* adr, const TypePtr* at, Node* val, MemOrd mo) : StoreNode(c, mem, adr, at, val, mo) { set_mismatched_access(); - if (oop_off != nullptr) { - add_req(oop_off); - } } virtual int Opcode() const; virtual BasicType value_basic_type() const { return T_LONG; } virtual uint match_edge(uint idx) const { return idx == MemNode::Address || idx == MemNode::ValueIn || - idx == MemNode::ValueIn + 1; } + idx == StoreLSpecialNode::OopOffset; } }; //------------------------------StoreFNode------------------------------------- @@ -1163,7 +1163,7 @@ class ClearArrayNode: public Node { public: ClearArrayNode( Node *ctrl, Node *arymem, Node *word_cnt, Node *base, Node* val, bool is_large) : Node(ctrl, arymem, word_cnt, base, val), _is_large(is_large), - _requires_word_fill(val->bottom_type()->isa_long() && (!val->bottom_type()->is_long()->is_con() || val->bottom_type()->is_long()->get_con() != 0)) { + _requires_word_fill(val->bottom_type()->is_long() && (!val->bottom_type()->as_long()->is_con() || val->bottom_type()->as_long()->get_con() != 0)) { init_class_id(Class_ClearArray); } virtual int Opcode() const; diff --git a/src/hotspot/share/opto/movenode.cpp b/src/hotspot/share/opto/movenode.cpp index 68a79b5dbc3d..00eb6dc6c3fe 100644 --- a/src/hotspot/share/opto/movenode.cpp +++ b/src/hotspot/share/opto/movenode.cpp @@ -186,12 +186,12 @@ const Type* CMoveNode::Value(PhaseGVN* phase) const { // from the inputs we do not need to specify it here. CMoveNode* CMoveNode::make(Node* bol, Node* false_value, Node* true_value, const Type* t) { switch (t->basic_type()) { - case T_INT: return new CMoveINode(bol, false_value, true_value, t->is_int()); + case T_INT: return new CMoveINode(bol, false_value, true_value, t->as_int()); case T_FLOAT: return new CMoveFNode(bol, false_value, true_value, t); case T_DOUBLE: return new CMoveDNode(bol, false_value, true_value, t); - case T_LONG: return new CMoveLNode(bol, false_value, true_value, t->is_long()); - case T_OBJECT: return new CMovePNode(bol, false_value, true_value, t->is_oopptr()); - case T_ADDRESS: return new CMovePNode(bol, false_value, true_value, t->is_ptr()); + case T_LONG: return new CMoveLNode(bol, false_value, true_value, t->as_long()); + case T_OBJECT: return new CMovePNode(bol, false_value, true_value, t->as_oopptr()); + case T_ADDRESS: return new CMovePNode(bol, false_value, true_value, t->as_ptr()); case T_NARROWOOP: return new CMoveNNode(bol, false_value, true_value, t); default: ShouldNotReachHere(); @@ -485,7 +485,7 @@ Node* MoveNode::Identity(PhaseGVN* phase) { const Type* MoveL2DNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeLong *tl = t->is_long(); + const TypeLong* tl = t->as_long(); if( !tl->is_con() ) return bottom_type(); JavaValue v; v.set_jlong(tl->get_con()); @@ -504,7 +504,7 @@ Node* MoveL2DNode::Identity(PhaseGVN* phase) { const Type* MoveI2FNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; - const TypeInt *ti = t->is_int(); + const TypeInt* ti = t->as_int(); if( !ti->is_con() ) return bottom_type(); JavaValue v; v.set_jint(ti->get_con()); @@ -524,7 +524,7 @@ const Type* MoveF2INode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::FLOAT ) return TypeInt::INT; - const TypeF *tf = t->is_float_constant(); + const TypeF* tf = t->as_float_constant(); JavaValue v; v.set_jfloat(tf->getf()); return TypeInt::make( v.get_jint() ); @@ -543,7 +543,7 @@ const Type* MoveD2LNode::Value(PhaseGVN* phase) const { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return Type::TOP; if( t == Type::DOUBLE ) return TypeLong::LONG; - const TypeD *td = t->is_double_constant(); + const TypeD* td = t->as_double_constant(); JavaValue v; v.set_jdouble(td->getd()); return TypeLong::make( v.get_jlong() ); diff --git a/src/hotspot/share/opto/mulnode.cpp b/src/hotspot/share/opto/mulnode.cpp index 7e13b38624cb..6cd4b06458bf 100644 --- a/src/hotspot/share/opto/mulnode.cpp +++ b/src/hotspot/share/opto/mulnode.cpp @@ -454,7 +454,7 @@ const Type* IntegerTypeMultiplication::create_type(jlong lo, jlong hi) co // Compute the product type of two integer ranges into this node. const Type* MulINode::mul_ring(const Type* type_left, const Type* type_right) const { - const IntegerTypeMultiplication integer_multiplication(type_left->is_int(), type_right->is_int()); + const IntegerTypeMultiplication integer_multiplication(type_left->as_int(), type_right->as_int()); return integer_multiplication.compute(); } @@ -465,7 +465,7 @@ bool MulINode::does_overflow(const TypeInt* type_left, const TypeInt* type_right // Compute the product type of two long ranges into this node. const Type* MulLNode::mul_ring(const Type* type_left, const Type* type_right) const { - const IntegerTypeMultiplication integer_multiplication(type_left->is_long(), type_right->is_long()); + const IntegerTypeMultiplication integer_multiplication(type_left->as_long(), type_right->as_long()); return integer_multiplication.compute(); } @@ -660,7 +660,7 @@ const Type* MulHiValue(const Type *t1, const Type *t2, const Type *bot) { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type* AndINode::mul_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_and(t1->is_int(), t2->is_int()); + return RangeInference::infer_and(t1->as_int(), t2->as_int()); } static bool AndIL_is_zero_element_under_mask(const PhaseGVN* phase, const Node* expr, const Node* mask, BasicType bt); @@ -683,8 +683,8 @@ Node* AndINode::Identity(PhaseGVN* phase) { return in(1); } - const TypeInt* t1 = phase->type(in(1))->is_int(); - const TypeInt* t2 = phase->type(in(2))->is_int(); + const TypeInt* t1 = phase->type(in(1))->as_int(); + const TypeInt* t2 = phase->type(in(2))->as_int(); if ((~t1->_bits._ones & ~t2->_bits._zeros) == 0) { // All bits that might be 0 in in1 are known to be 0 in in2 @@ -778,7 +778,7 @@ Node *AndINode::Ideal(PhaseGVN *phase, bool can_reshape) { // This also type-checks the inputs for sanity. Guaranteed never to // be passed a TOP or BOTTOM type, these are filtered out by pre-check. const Type* AndLNode::mul_ring(const Type* t1, const Type* t2) const { - return RangeInference::infer_and(t1->is_long(), t2->is_long()); + return RangeInference::infer_and(t1->as_long(), t2->as_long()); } const Type* AndLNode::Value(PhaseGVN* phase) const { @@ -799,8 +799,8 @@ Node* AndLNode::Identity(PhaseGVN* phase) { return in(1); } - const TypeLong* t1 = phase->type(in(1))->is_long(); - const TypeLong* t2 = phase->type(in(2))->is_long(); + const TypeLong* t1 = phase->type(in(1))->as_long(); + const TypeLong* t2 = phase->type(in(2))->as_long(); if ((~t1->_bits._ones & ~t2->_bits._zeros) == 0) { // All bits that might be 0 in in1 are known to be 0 in in2 @@ -867,7 +867,7 @@ Node *AndLNode::Ideal(PhaseGVN *phase, bool can_reshape) { } // Search for GraphKit::mark_word_test patterns and fold the test if the result is statically known - if (in1->is_Load() && phase->type(in1)->isa_long()) { + if (in1->is_Load() && phase->type(in1)->is_long()) { const TypePtr* adr_t = phase->type(in1->in(MemNode::Address))->isa_ptr(); if (adr_t != nullptr && adr_t->offset() == oopDesc::mark_offset_in_bytes()) { if (mask == markWord::value_type_pattern) { @@ -1156,9 +1156,9 @@ Node* LShiftNode::IdealIL(PhaseGVN* phase, bool can_reshape, BasicType bt) { } uint64_t known_ones; if (bt == T_INT) { - known_ones = mask_t->is_int()->_bits._ones; + known_ones = mask_t->as_int()->_bits._ones; } else { - known_ones = mask_t->is_long()->_bits._ones; + known_ones = mask_t->as_long()->_bits._ones; } if ((known_ones & bits_mask) == bits_mask) { return LShiftNode::make(add1->in(3 - i), in(2), bt); @@ -1206,13 +1206,13 @@ const Type* LShiftNode::ValueIL(PhaseGVN* phase, BasicType bt) const { return TypeInteger::bottom(bt); } - const TypeInteger* r1 = t1->is_integer(bt); // Handy access + const TypeInteger* r1 = t1->as_integer(bt); // Handy access // Since the shift semantics in Java take into account only the bottom five // bits for ints and the bottom six bits for longs, we can further constrain // the range of values of the shift amount by ANDing with the right mask based // on whether the type is int or long. const TypeInt* mask = TypeInt::make(bits_per_java_integer(bt) - 1); - const TypeInt* r2 = RangeInference::infer_and(t2->is_int(), mask); + const TypeInt* r2 = RangeInference::infer_and(t2->as_int(), mask); if (!r2->is_con()) { return TypeInteger::bottom(bt); @@ -1230,17 +1230,17 @@ const Type* LShiftNode::ValueIL(PhaseGVN* phase, BasicType bt) const { #ifdef ASSERT if (bt == T_INT) { jlong lo = r1->lo_as_long(), hi = r1->hi_as_long(); - jint lo_int = r1->is_int()->_lo, hi_int = r1->is_int()->_hi; + jint lo_int = r1->as_int()->_lo, hi_int = r1->as_int()->_hi; assert((java_shift_right(java_shift_left(lo, shift, bt), shift, bt) == lo) == (((lo_int << shift) >> shift) == lo_int), "inconsistent"); assert((java_shift_right(java_shift_left(hi, shift, bt), shift, bt) == hi) == (((hi_int << shift) >> shift) == hi_int), "inconsistent"); } #endif if (bt == T_INT) { - return RangeInference::infer_lshift(r1->is_int(), shift); + return RangeInference::infer_lshift(r1->as_int(), shift); } - return RangeInference::infer_lshift(r1->is_long(), shift); + return RangeInference::infer_lshift(r1->as_long(), shift); } return TypeInteger::make(java_shift_left(r1->get_con_as_long(bt), shift, bt), bt); @@ -1330,8 +1330,7 @@ Node* RShiftINode::Identity(PhaseGVN* phase) { Node* RShiftNode::IdealIL(PhaseGVN* phase, bool can_reshape, BasicType bt) { // Inputs may be TOP if they are dead. - const TypeInteger* t1 = phase->type(in(1))->isa_integer(bt); - if (t1 == nullptr) { + if (!phase->type(in(1))->is_integer(bt)) { return NodeSentinel; // Left input is an integer } @@ -1439,8 +1438,8 @@ const Type* RShiftNode::ValueIL(PhaseGVN* phase, BasicType bt) const { return TypeInteger::bottom(bt); } - const TypeInteger* r1 = t1->isa_integer(bt); - const TypeInt* r2 = t2->isa_int(); + const TypeInteger* r1 = t1->as_integer(bt); + const TypeInt* r2 = t2->as_int(); // If the shift is a constant, just shift the bounds of the type. // For example, if the shift is 31/63, we just propagate sign bits. @@ -1648,9 +1647,9 @@ Node* URShiftINode::Ideal(PhaseGVN* phase, bool can_reshape) { if ( in1_op == Op_RShiftI ) { Node *in11 = shr->in(1); Node *in12 = shr->in(2); - const TypeInt *t11 = phase->type(in11)->isa_int(); - const TypeInt *t12 = phase->type(in12)->isa_int(); - if ( t11 && t2 && t2->is_con(31) && t12 && t12->is_con() ) { + bool in11_is_int = phase->type(in11)->is_int(); + const TypeInt* t12 = phase->type(in12)->isa_int(); + if (in11_is_int && t2 != nullptr && t2->is_con(31) && t12 != nullptr && t12->is_con()) { return new URShiftINode(in11, phase->intcon(31)); } } @@ -1680,8 +1679,8 @@ const Type* URShiftINode::Value(PhaseGVN* phase) const { if (t2 == TypeInt::INT) return TypeInt::INT; - const TypeInt *r1 = t1->is_int(); // Handy access - const TypeInt *r2 = t2->is_int(); // Handy access + const TypeInt* r1 = t1->as_int(); // Handy access + const TypeInt* r2 = t2->as_int(); // Handy access if (r2->is_con()) { uint shift = r2->get_con(); @@ -1719,12 +1718,12 @@ const Type* URShiftINode::Value(PhaseGVN* phase) const { // // else if( t1->base() == Type::InstPtr ) { // - // const TypeInstPtr *o = t1->is_instptr(); + // const TypeInstPtr* o = t1->as_instptr(); // if( t1->singleton() ) // return TypeInt::make( ((uint32_t)o->const_oop() + o->_offset) >> shift ); // } // else if( t1->base() == Type::KlassPtr ) { - // const TypeKlassPtr *o = t1->is_klassptr(); + // const TypeKlassPtr* o = t1->as_klassptr(); // if( t1->singleton() ) // return TypeInt::make( ((uint32_t)o->const_oop() + o->_offset) >> shift ); // } @@ -1809,9 +1808,9 @@ Node* URShiftLNode::Ideal(PhaseGVN* phase, bool can_reshape) { if ( shr->Opcode() == Op_RShiftL ) { Node *in11 = shr->in(1); Node *in12 = shr->in(2); - const TypeLong *t11 = phase->type(in11)->isa_long(); - const TypeInt *t12 = phase->type(in12)->isa_int(); - if ( t11 && t2 && t2->is_con(63) && t12 && t12->is_con() ) { + bool in11_is_long = phase->type(in11)->is_long(); + const TypeInt* t12 = phase->type(in12)->isa_int(); + if (in11_is_long && t2 != nullptr && t2->is_con(63) && t12 != nullptr && t12->is_con()) { return new URShiftLNode(in11, phase->intcon(63)); } } @@ -1841,8 +1840,8 @@ const Type* URShiftLNode::Value(PhaseGVN* phase) const { if (t2 == TypeInt::INT) return TypeLong::LONG; - const TypeLong *r1 = t1->is_long(); // Handy access - const TypeInt *r2 = t2->is_int (); // Handy access + const TypeLong* r1 = t1->as_long(); // Handy access + const TypeInt* r2 = t2->as_int(); // Handy access if (r2->is_con()) { uint shift = r2->get_con(); @@ -1976,8 +1975,8 @@ Node* RotateLeftNode::Identity(PhaseGVN* phase) { return this; } uint count; - assert(t1->isa_int() || t1->isa_long(), "Unexpected type"); - uint num_bits = t1->isa_int() ? BitsPerJavaInteger : BitsPerJavaLong; + assert(t1->is_int() || t1->is_long(), "Unexpected type"); + uint num_bits = t1->is_int() ? BitsPerJavaInteger : BitsPerJavaLong; if (mask_shift_amount(phase, this, num_bits, count) && count == 0) { // Rotate by a multiple of 32/64 does nothing return in(1); @@ -1993,9 +1992,9 @@ const Type* RotateLeftNode::Value(PhaseGVN* phase) const { return Type::TOP; } - if (t1->isa_int()) { - const TypeInt* r1 = t1->is_int(); - const TypeInt* r2 = t2->is_int(); + if (t1->is_int()) { + const TypeInt* r1 = t1->as_int(); + const TypeInt* r2 = t2->as_int(); // Left input is ZERO ==> the result is ZERO. if (r1 == TypeInt::ZERO) { @@ -2012,9 +2011,9 @@ const Type* RotateLeftNode::Value(PhaseGVN* phase) const { } return TypeInt::INT; } else { - assert(t1->isa_long(), "Type must be a long"); - const TypeLong* r1 = t1->is_long(); - const TypeInt* r2 = t2->is_int(); + assert(t1->is_long(), "Type must be a long"); + const TypeLong* r1 = t1->as_long(); + const TypeInt* r2 = t2->as_int(); // Left input is ZERO ==> the result is ZERO. if (r1 == TypeLong::ZERO) { @@ -2036,13 +2035,13 @@ const Type* RotateLeftNode::Value(PhaseGVN* phase) const { Node* RotateLeftNode::Ideal(PhaseGVN *phase, bool can_reshape) { const Type* t1 = phase->type(in(1)); const Type* t2 = phase->type(in(2)); - if (t2->isa_int() && t2->is_int()->is_con()) { - if (t1->isa_int()) { - int lshift = t2->is_int()->get_con() & 31; + if (t2->is_int() && t2->as_int()->is_con()) { + if (t1->is_int()) { + int lshift = t2->as_int()->get_con() & 31; return new RotateRightNode(in(1), phase->intcon(32 - (lshift & 31)), TypeInt::INT); } else if (t1 != Type::TOP) { - assert(t1->isa_long(), "Type must be a long"); - int lshift = t2->is_int()->get_con() & 63; + assert(t1->is_long(), "Type must be a long"); + int lshift = t2->as_int()->get_con() & 63; return new RotateRightNode(in(1), phase->intcon(64 - (lshift & 63)), TypeLong::LONG); } } @@ -2055,8 +2054,8 @@ Node* RotateRightNode::Identity(PhaseGVN* phase) { return this; } uint count; - assert(t1->isa_int() || t1->isa_long(), "Unexpected type"); - uint num_bits = t1->isa_int() ? BitsPerJavaInteger : BitsPerJavaLong; + assert(t1->is_int() || t1->is_long(), "Unexpected type"); + uint num_bits = t1->is_int() ? BitsPerJavaInteger : BitsPerJavaLong; if (mask_shift_amount(phase, this, num_bits, count) && count == 0) { // Rotate by a multiple of 32/64 does nothing return in(1); @@ -2072,9 +2071,9 @@ const Type* RotateRightNode::Value(PhaseGVN* phase) const { return Type::TOP; } - if (t1->isa_int()) { - const TypeInt* r1 = t1->is_int(); - const TypeInt* r2 = t2->is_int(); + if (t1->is_int()) { + const TypeInt* r1 = t1->as_int(); + const TypeInt* r2 = t2->as_int(); // Left input is ZERO ==> the result is ZERO. if (r1 == TypeInt::ZERO) { @@ -2091,9 +2090,8 @@ const Type* RotateRightNode::Value(PhaseGVN* phase) const { } return TypeInt::INT; } else { - assert(t1->isa_long(), "Type must be a long"); - const TypeLong* r1 = t1->is_long(); - const TypeInt* r2 = t2->is_int(); + const TypeLong* r1 = t1->as_long(); + const TypeInt* r2 = t2->as_int(); // Left input is ZERO ==> the result is ZERO. if (r1 == TypeLong::ZERO) { return TypeLong::ZERO; diff --git a/src/hotspot/share/opto/multnode.cpp b/src/hotspot/share/opto/multnode.cpp index 29bb6cd8b793..35c5ca7193d3 100644 --- a/src/hotspot/share/opto/multnode.cpp +++ b/src/hotspot/share/opto/multnode.cpp @@ -130,7 +130,7 @@ const Type* ProjNode::proj_type(const Type* t) const { if (t == Type::BOTTOM) { return Type::BOTTOM; } - t = t->is_tuple()->field_at(_con); + t = t->as_tuple()->field_at(_con); CallStaticJavaNode* call = in(0)->isa_CallStaticJava(); if (call != nullptr && call->is_boxing_method()) { // The result of autoboxing is always non-null on normal path. @@ -179,12 +179,12 @@ void ProjNode::check_con() const { if (_con == SCMemProjNode::SCMEMPROJCON ) return; const Type* t = n->bottom_type(); if (t == Type::TOP) return; // multi is dead - assert(_con < t->is_tuple()->cnt(), "ProjNode::_con must be in range"); + assert(_con < t->as_tuple()->cnt(), "ProjNode::_con must be in range"); } //------------------------------Identity--------------------------------------- Node* ProjNode::Identity(PhaseGVN* phase) { - if (in(0) != nullptr && in(0)->Opcode() == Op_Tuple) { + if (is_exact(in(0))) { // Jumping over Tuples: the i-th projection of a Tuple is the i-th input of the Tuple. return in(0)->in(_con); } diff --git a/src/hotspot/share/opto/narrowptrnode.cpp b/src/hotspot/share/opto/narrowptrnode.cpp index 8fd944b3d879..68af0feee72a 100644 --- a/src/hotspot/share/opto/narrowptrnode.cpp +++ b/src/hotspot/share/opto/narrowptrnode.cpp @@ -22,9 +22,31 @@ * */ +#include "opto/cfgnode.hpp" #include "opto/narrowptrnode.hpp" #include "opto/phaseX.hpp" +Node* DecodeNNode::Ideal(PhaseGVN* phase, bool can_reshape) { + // DecodeN(Phi(EncodeP(n1), EncodeP(n2), ...)) -> Phi(n1, n2, ...) + Node* phi = in(1); + if (!phi->is_Phi()) { + return nullptr; + } + + for (uint i = 1; i < phi->req(); i++) { + if (phi->in(i) == nullptr || !phi->in(i)->is_EncodeP()) { + return nullptr; + } + } + + PhiNode* r = new PhiNode(phi->in(0), type()); + phase->set_type_bottom(r); + for (uint i = 1; i < phi->req(); i++) { + r->init_req(i, phi->in(i)->in(1)); + } + return r; +} + Node* DecodeNNode::Identity(PhaseGVN* phase) { const Type *t = phase->type( in(1) ); if( t == Type::TOP ) return in(1); @@ -41,7 +63,7 @@ const Type* DecodeNNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) return Type::TOP; if (t == TypeNarrowOop::NULL_PTR) return TypePtr::NULL_PTR; - assert(t->isa_narrowoop(), "only narrowoop here"); + assert(t->is_narrowoop(), "only narrowoop here"); return t->make_ptr(); } @@ -61,7 +83,7 @@ const Type* EncodePNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) return Type::TOP; if (t == TypePtr::NULL_PTR) return TypeNarrowOop::NULL_PTR; - assert(t->isa_oop_ptr(), "only oopptr here"); + assert(t->is_oopptr(), "only oopptr here"); return t->make_narrowoop(); } @@ -82,7 +104,7 @@ const Type* DecodeNKlassNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) return Type::TOP; assert(t != TypeNarrowKlass::NULL_PTR, "null klass?"); - assert(t->isa_narrowklass(), "only narrow klass ptr here"); + assert(t->is_narrowklass(), "only narrow klass ptr here"); return t->make_ptr(); } @@ -102,7 +124,7 @@ const Type* EncodePKlassNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) return Type::TOP; assert (t != TypePtr::NULL_PTR, "null klass?"); - assert(t->isa_klassptr(), "only klass ptr here"); + assert(t->is_klassptr(), "only klass ptr here"); return t->make_narrowklass(); } diff --git a/src/hotspot/share/opto/narrowptrnode.hpp b/src/hotspot/share/opto/narrowptrnode.hpp index e7cd19cb4244..207504403e91 100644 --- a/src/hotspot/share/opto/narrowptrnode.hpp +++ b/src/hotspot/share/opto/narrowptrnode.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -88,15 +88,16 @@ class DecodeNarrowPtrNode : public TypeNode { // Converts a narrow oop into a real oop ptr. // Takes an extra argument which is the real heap base as a long which // may be useful for code generation in the backend. -class DecodeNNode : public DecodeNarrowPtrNode { +class DecodeNNode final : public DecodeNarrowPtrNode { public: DecodeNNode(Node* value, const Type* type): DecodeNarrowPtrNode(value, type) { init_class_id(Class_DecodeN); } - virtual int Opcode() const; - virtual const Type* Value(PhaseGVN* phase) const; - virtual Node* Identity(PhaseGVN* phase); + int Opcode() const final; + Node* Ideal(PhaseGVN* phase, bool can_reshape) final; + Node* Identity(PhaseGVN* phase) final; + const Type* Value(PhaseGVN* phase) const final; }; //------------------------------DecodeNKlass-------------------------------- diff --git a/src/hotspot/share/opto/node.cpp b/src/hotspot/share/opto/node.cpp index 6da3e2b4df82..39447d32a792 100644 --- a/src/hotspot/share/opto/node.cpp +++ b/src/hotspot/share/opto/node.cpp @@ -1356,8 +1356,8 @@ bool Node::should_process_when_disconnect_output(Node* output) const { //--------------------------find_exact_control--------------------------------- // Skip Proj and CatchProj nodes chains. Check for Null and Top. Node* Node::find_exact_control(Node* ctrl) { - if (ctrl == nullptr && this->is_Region()) - ctrl = this->as_Region()->is_copy(); + if (auto this_as_region = isa(this); ctrl == nullptr && this_as_region != nullptr) + ctrl = this_as_region->is_copy(); if (ctrl != nullptr && ctrl->is_CatchProj()) { if (ctrl->as_CatchProj()->_con == CatchProjNode::fall_through_index) @@ -1366,7 +1366,7 @@ Node* Node::find_exact_control(Node* ctrl) { ctrl = ctrl->in(0); } - if (ctrl != nullptr && ctrl->is_Proj()) + if (is(ctrl)) ctrl = ctrl->in(0); return ctrl; @@ -1673,13 +1673,13 @@ const TypeInteger* Node::find_integer_type(BasicType bt) const { // Returns the constant if it is a pointer ConstNode intptr_t Node::get_ptr() const { assert( Opcode() == Op_ConP, "" ); - return ((ConPNode*)this)->type()->is_ptr()->get_con(); + return ((ConPNode*)this)->type()->as_ptr()->get_con(); } // Get a narrow oop constant from a ConNNode. intptr_t Node::get_narrowcon() const { assert( Opcode() == Op_ConN, "" ); - return ((ConNNode*)this)->type()->is_narrowoop()->get_con(); + return ((ConNNode*)this)->type()->as_narrowoop()->get_con(); } // Get a long constant from a ConNode. @@ -1713,21 +1713,21 @@ const TypePtr* Node::get_ptr_type() const { // Returns the constant if it is a double ConstNode jdouble Node::getd() const { assert( Opcode() == Op_ConD, "" ); - return ((ConDNode*)this)->type()->is_double_constant()->getd(); + return ((ConDNode*)this)->type()->as_double_constant()->getd(); } // Get a float constant from a ConstNode. // Returns the constant if it is a float ConstNode jfloat Node::getf() const { assert( Opcode() == Op_ConF, "" ); - return ((ConFNode*)this)->type()->is_float_constant()->getf(); + return ((ConFNode*)this)->type()->as_float_constant()->getf(); } // Get a half float constant from a ConstNode. // Returns the constant if it is a float ConstNode jshort Node::geth() const { assert( Opcode() == Op_ConH, "" ); - return ((ConHNode*)this)->type()->is_half_float_constant()->geth(); + return ((ConHNode*)this)->type()->as_half_float_constant()->geth(); } #ifndef PRODUCT @@ -2709,12 +2709,10 @@ void Node::dump(const char* suffix, bool mark, outputStream* st, DumpConfig* dc) const Type *t = bottom_type(); - if (t != nullptr && (t->isa_instptr() || t->isa_instklassptr())) { - const TypeInstPtr *toop = t->isa_instptr(); - const TypeInstKlassPtr *tkls = t->isa_instklassptr(); - if (toop) { + if (t != nullptr && (t->is_instptr() || t->is_instklassptr())) { + if (t->is_instptr()) { st->print(" Oop:"); - } else if (tkls) { + } else { st->print(" Klass:"); } t->dump_on(st); @@ -2723,12 +2721,12 @@ void Node::dump(const char* suffix, bool mark, outputStream* st, DumpConfig* dc) MemNode::dump_adr_type(out_adr_type(), st); } else if (Verbose || WizardMode) { st->print(" Type:"); - if (t) { + if (t != nullptr) { t->dump_on(st); } else { st->print("no type"); } - } else if (t->isa_vect() && this->is_MachSpillCopy()) { + } else if (t->is_vect() && this->is_MachSpillCopy()) { // Dump MachSpillcopy vector type. t->dump_on(st); } @@ -2971,7 +2969,7 @@ bool Node::is_iteratively_computed() { if (ideal_reg()) { // does operation have a result register? for (uint i = 1; i < req(); i++) { Node* n = in(i); - if (n != nullptr && n->is_Phi()) { + if (is(n)) { for (uint j = 1; j < n->req(); j++) { if (n->in(j) == this) { return true; diff --git a/src/hotspot/share/opto/node.hpp b/src/hotspot/share/opto/node.hpp index 97c8af5c49b2..c3fc2907a5b0 100644 --- a/src/hotspot/share/opto/node.hpp +++ b/src/hotspot/share/opto/node.hpp @@ -27,6 +27,7 @@ #define SHARE_OPTO_NODE_HPP #include "libadt/vectset.hpp" +#include "metaprogramming/dependentAlwaysFalse.hpp" #include "opto/compile.hpp" #include "opto/type.hpp" #include "utilities/copy.hpp" @@ -920,167 +921,181 @@ class Node { // Virtual inherited Node size virtual uint size_of() const; + template static bool is(const Node*); + template static T* isa(Node*); + template static const T* isa(const Node*); + template static T* isa(std::nullptr_t); + template static T* as(Node*); + template static const T* as(const Node*); + template static bool is_exact(const Node* n) { + if (n == nullptr) return false; + return n->Opcode() == Op; + } + +#define NODE_METHODS(do_node) \ + do_node(AbstractLock) \ + do_node(Add) \ + do_node(AddP) \ + do_node(Allocate) \ + do_node(AllocateArray) \ + do_node(ArrayCopy) \ + do_node(BaseCountedLoop) \ + do_node(BaseCountedLoopEnd) \ + do_node(Blackhole) \ + do_node(Bool) \ + do_node(BoxLock) \ + do_node(Call) \ + do_node(CallDynamicJava) \ + do_node(CallJava) \ + do_node(CallLeaf) \ + do_node(CallLeafNoFP) \ + do_node(CallLeafPure) \ + do_node(CallRuntime) \ + do_node(CallStaticJava) \ + do_node(Catch) \ + do_node(CatchProj) \ + do_node(CheckCastPP) \ + do_node(CastII) \ + do_node(CastLL) \ + do_node(CastFF) \ + do_node(ConI) \ + do_node(CastPP) \ + do_node(ConstraintCast) \ + do_node(ClearArray) \ + do_node(CMove) \ + do_node(Cmp) \ + do_node(Convert) \ + do_node(CountedLoop) \ + do_node(CountedLoopEnd) \ + do_node(CreateEx) \ + do_node(DecodeNarrowPtr) \ + do_node(DecodeN) \ + do_node(DecodeNKlass) \ + do_node(DivModInteger) \ + do_node(EncodeNarrowPtr) \ + do_node(EncodeP) \ + do_node(EncodePKlass) \ + do_node(FastLock) \ + do_node(FastUnlock) \ + do_node(FlatArrayCheck) \ + do_node(Halt) \ + do_node(If) \ + do_node(RangeCheck) \ + do_node(IfProj) \ + do_node(IfFalse) \ + do_node(IfTrue) \ + do_node(Initialize) \ + do_node(Jump) \ + do_node(JumpProj) \ + do_node(LongCountedLoop) \ + do_node(LongCountedLoopEnd) \ + do_node(Load) \ + do_node(LoadStore) \ + do_node(LoadStoreConditional) \ + do_node(Lock) \ + do_node(Loop) \ + do_node(LShift) \ + do_node(Mach) \ + do_node(MachBranch) \ + do_node(MachCall) \ + do_node(MachCallDynamicJava) \ + do_node(MachCallJava) \ + do_node(MachCallLeaf) \ + do_node(MachCallRuntime) \ + do_node(MachCallStaticJava) \ + do_node(MachConstantBase) \ + do_node(MachConstant) \ + do_node(MachGoto) \ + do_node(MachIf) \ + do_node(MachJump) \ + do_node(MachNullCheck) \ + do_node(MachProj) \ + do_node(MachProlog) \ + do_node(MachReturn) \ + do_node(MachSafePoint) \ + do_node(MachUncommonTrap) \ + do_node(MachSpillCopy) \ + do_node(MachTemp) \ + do_node(MachMemBar) \ + do_node(MachMerge) \ + do_node(MachVEP) \ + do_node(Mem) \ + do_node(MemBar) \ + do_node(MemBarStoreStore) \ + do_node(MergeMem) \ + do_node(MinMax) \ + do_node(Move) \ + do_node(Mul) \ + do_node(Multi) \ + do_node(MultiBranch) \ + do_node(MulVL) \ + do_node(NarrowMemProj) \ + do_node(Neg) \ + do_node(NegV) \ + do_node(NeverBranch) \ + do_node(Opaque1) \ + do_node(OpaqueConstantBool) \ + do_node(OpaqueInitializedAssertionPredicate) \ + do_node(OpaqueTemplateAssertionPredicate) \ + do_node(OpaqueLoopInit) \ + do_node(OpaqueLoopStride) \ + do_node(OpaqueMultiversioning) \ + do_node(OpaqueZeroTripGuard) \ + do_node(OuterStripMinedLoop) \ + do_node(OuterStripMinedLoopEnd) \ + do_node(Parm) \ + do_node(ParsePredicate) \ + do_node(PCTable) \ + do_node(Phi) \ + do_node(Proj) \ + do_node(ReachabilityFence) \ + do_node(Reduction) \ + do_node(Region) \ + do_node(Root) \ + do_node(SafePoint) \ + do_node(SafePointScalarObject) \ + do_node(SafePointScalarMerge) \ + do_node(Start) \ + do_node(Store) \ + do_node(Sub) \ + do_node(SubTypeCheck) \ + do_node(Type) \ + do_node(ValueType) \ + do_node(LoadFlat) \ + do_node(StoreFlat) \ + do_node(Vector) \ + do_node(VectorMaskCmp) \ + do_node(VectorUnbox) \ + do_node(VectorReinterpret) \ + do_node(CompressV) \ + do_node(ExpandV) \ + do_node(CompressM) \ + do_node(LoadVector) \ + do_node(LoadVectorGather) \ + do_node(LoadVectorMasked) \ + do_node(LoadVectorGatherMasked) \ + do_node(StoreVector) \ + do_node(StoreVectorScatter) \ + do_node(StoreVectorMasked) \ + do_node(StoreVectorScatterMasked) \ + do_node(SaturatingVector) \ + do_node(ShiftV) \ + do_node(Unlock) \ + // Other interesting Node properties #define DEFINE_CLASS_QUERY(type) \ bool is_##type() const { \ return ((_class_id & ClassMask_##type) == Class_##type); \ } \ - type##Node *as_##type() const { \ + type##Node* as_##type() const { \ assert(is_##type(), "invalid node class: %s", Name()); \ return (type##Node*)this; \ } \ type##Node* isa_##type() const { \ return (is_##type()) ? as_##type() : nullptr; \ - } + } \ - DEFINE_CLASS_QUERY(AbstractLock) - DEFINE_CLASS_QUERY(Add) - DEFINE_CLASS_QUERY(AddP) - DEFINE_CLASS_QUERY(Allocate) - DEFINE_CLASS_QUERY(AllocateArray) - DEFINE_CLASS_QUERY(ArrayCopy) - DEFINE_CLASS_QUERY(BaseCountedLoop) - DEFINE_CLASS_QUERY(BaseCountedLoopEnd) - DEFINE_CLASS_QUERY(Blackhole) - DEFINE_CLASS_QUERY(Bool) - DEFINE_CLASS_QUERY(BoxLock) - DEFINE_CLASS_QUERY(Call) - DEFINE_CLASS_QUERY(CallDynamicJava) - DEFINE_CLASS_QUERY(CallJava) - DEFINE_CLASS_QUERY(CallLeaf) - DEFINE_CLASS_QUERY(CallLeafNoFP) - DEFINE_CLASS_QUERY(CallLeafPure) - DEFINE_CLASS_QUERY(CallRuntime) - DEFINE_CLASS_QUERY(CallStaticJava) - DEFINE_CLASS_QUERY(Catch) - DEFINE_CLASS_QUERY(CatchProj) - DEFINE_CLASS_QUERY(CheckCastPP) - DEFINE_CLASS_QUERY(CastII) - DEFINE_CLASS_QUERY(CastLL) - DEFINE_CLASS_QUERY(CastFF) - DEFINE_CLASS_QUERY(ConI) - DEFINE_CLASS_QUERY(CastPP) - DEFINE_CLASS_QUERY(ConstraintCast) - DEFINE_CLASS_QUERY(ClearArray) - DEFINE_CLASS_QUERY(CMove) - DEFINE_CLASS_QUERY(Cmp) - DEFINE_CLASS_QUERY(Convert) - DEFINE_CLASS_QUERY(CountedLoop) - DEFINE_CLASS_QUERY(CountedLoopEnd) - DEFINE_CLASS_QUERY(CreateEx) - DEFINE_CLASS_QUERY(DecodeNarrowPtr) - DEFINE_CLASS_QUERY(DecodeN) - DEFINE_CLASS_QUERY(DecodeNKlass) - DEFINE_CLASS_QUERY(DivModInteger) - DEFINE_CLASS_QUERY(EncodeNarrowPtr) - DEFINE_CLASS_QUERY(EncodeP) - DEFINE_CLASS_QUERY(EncodePKlass) - DEFINE_CLASS_QUERY(FastLock) - DEFINE_CLASS_QUERY(FastUnlock) - DEFINE_CLASS_QUERY(FlatArrayCheck) - DEFINE_CLASS_QUERY(Halt) - DEFINE_CLASS_QUERY(If) - DEFINE_CLASS_QUERY(RangeCheck) - DEFINE_CLASS_QUERY(IfProj) - DEFINE_CLASS_QUERY(IfFalse) - DEFINE_CLASS_QUERY(IfTrue) - DEFINE_CLASS_QUERY(Initialize) - DEFINE_CLASS_QUERY(Jump) - DEFINE_CLASS_QUERY(JumpProj) - DEFINE_CLASS_QUERY(LongCountedLoop) - DEFINE_CLASS_QUERY(LongCountedLoopEnd) - DEFINE_CLASS_QUERY(Load) - DEFINE_CLASS_QUERY(LoadStore) - DEFINE_CLASS_QUERY(LoadStoreConditional) - DEFINE_CLASS_QUERY(Lock) - DEFINE_CLASS_QUERY(Loop) - DEFINE_CLASS_QUERY(LShift) - DEFINE_CLASS_QUERY(Mach) - DEFINE_CLASS_QUERY(MachBranch) - DEFINE_CLASS_QUERY(MachCall) - DEFINE_CLASS_QUERY(MachCallDynamicJava) - DEFINE_CLASS_QUERY(MachCallJava) - DEFINE_CLASS_QUERY(MachCallLeaf) - DEFINE_CLASS_QUERY(MachCallRuntime) - DEFINE_CLASS_QUERY(MachCallStaticJava) - DEFINE_CLASS_QUERY(MachConstantBase) - DEFINE_CLASS_QUERY(MachConstant) - DEFINE_CLASS_QUERY(MachGoto) - DEFINE_CLASS_QUERY(MachIf) - DEFINE_CLASS_QUERY(MachJump) - DEFINE_CLASS_QUERY(MachNullCheck) - DEFINE_CLASS_QUERY(MachProj) - DEFINE_CLASS_QUERY(MachProlog) - DEFINE_CLASS_QUERY(MachReturn) - DEFINE_CLASS_QUERY(MachSafePoint) - DEFINE_CLASS_QUERY(MachUncommonTrap) - DEFINE_CLASS_QUERY(MachSpillCopy) - DEFINE_CLASS_QUERY(MachTemp) - DEFINE_CLASS_QUERY(MachMemBar) - DEFINE_CLASS_QUERY(MachMerge) - DEFINE_CLASS_QUERY(MachVEP) - DEFINE_CLASS_QUERY(Mem) - DEFINE_CLASS_QUERY(MemBar) - DEFINE_CLASS_QUERY(MemBarStoreStore) - DEFINE_CLASS_QUERY(MergeMem) - DEFINE_CLASS_QUERY(MinMax) - DEFINE_CLASS_QUERY(Move) - DEFINE_CLASS_QUERY(Mul) - DEFINE_CLASS_QUERY(Multi) - DEFINE_CLASS_QUERY(MultiBranch) - DEFINE_CLASS_QUERY(MulVL) - DEFINE_CLASS_QUERY(NarrowMemProj) - DEFINE_CLASS_QUERY(Neg) - DEFINE_CLASS_QUERY(NegV) - DEFINE_CLASS_QUERY(NeverBranch) - DEFINE_CLASS_QUERY(Opaque1) - DEFINE_CLASS_QUERY(OpaqueConstantBool) - DEFINE_CLASS_QUERY(OpaqueInitializedAssertionPredicate) - DEFINE_CLASS_QUERY(OpaqueTemplateAssertionPredicate) - DEFINE_CLASS_QUERY(OpaqueLoopInit) - DEFINE_CLASS_QUERY(OpaqueLoopStride) - DEFINE_CLASS_QUERY(OpaqueMultiversioning) - DEFINE_CLASS_QUERY(OpaqueZeroTripGuard) - DEFINE_CLASS_QUERY(OuterStripMinedLoop) - DEFINE_CLASS_QUERY(OuterStripMinedLoopEnd) - DEFINE_CLASS_QUERY(Parm) - DEFINE_CLASS_QUERY(ParsePredicate) - DEFINE_CLASS_QUERY(PCTable) - DEFINE_CLASS_QUERY(Phi) - DEFINE_CLASS_QUERY(Proj) - DEFINE_CLASS_QUERY(ReachabilityFence) - DEFINE_CLASS_QUERY(Reduction) - DEFINE_CLASS_QUERY(Region) - DEFINE_CLASS_QUERY(Root) - DEFINE_CLASS_QUERY(SafePoint) - DEFINE_CLASS_QUERY(SafePointScalarObject) - DEFINE_CLASS_QUERY(SafePointScalarMerge) - DEFINE_CLASS_QUERY(Start) - DEFINE_CLASS_QUERY(Store) - DEFINE_CLASS_QUERY(Sub) - DEFINE_CLASS_QUERY(SubTypeCheck) - DEFINE_CLASS_QUERY(Type) - DEFINE_CLASS_QUERY(ValueType) - DEFINE_CLASS_QUERY(LoadFlat) - DEFINE_CLASS_QUERY(StoreFlat) - DEFINE_CLASS_QUERY(Vector) - DEFINE_CLASS_QUERY(VectorMaskCmp) - DEFINE_CLASS_QUERY(VectorUnbox) - DEFINE_CLASS_QUERY(VectorReinterpret) - DEFINE_CLASS_QUERY(CompressV) - DEFINE_CLASS_QUERY(ExpandV) - DEFINE_CLASS_QUERY(CompressM) - DEFINE_CLASS_QUERY(LoadVector) - DEFINE_CLASS_QUERY(LoadVectorGather) - DEFINE_CLASS_QUERY(LoadVectorMasked) - DEFINE_CLASS_QUERY(LoadVectorGatherMasked) - DEFINE_CLASS_QUERY(StoreVector) - DEFINE_CLASS_QUERY(StoreVectorScatter) - DEFINE_CLASS_QUERY(StoreVectorMasked) - DEFINE_CLASS_QUERY(StoreVectorScatterMasked) - DEFINE_CLASS_QUERY(SaturatingVector) - DEFINE_CLASS_QUERY(ShiftV) - DEFINE_CLASS_QUERY(Unlock) + NODE_METHODS(DEFINE_CLASS_QUERY) #undef DEFINE_CLASS_QUERY @@ -1270,7 +1285,6 @@ class Node { static bool may_be_loop_entry(Node* n) { return n != nullptr && n->is_IfProj() && n->in(0)->is_ParsePredicate(); } - //----------------- Optimization // Get the worst-case Type output for this Node. @@ -1571,6 +1585,81 @@ class Node { void make_path_dead(PhaseIterGVN* igvn, PhaseIdealLoop* loop, Node* ctrl_use, uint j, const char* phase_str); }; +template +bool Node::is(const Node* n) { + if (n == nullptr) { + return false; + } + if constexpr (false) { + return false; + } +#define NODE_IS_CASES(type) \ + else if constexpr (std::is_same_v) { \ + return n->is_##type(); \ + } +NODE_METHODS(NODE_IS_CASES) +#undef NODE_IS_CASES + else { + static_assert(DependentAlwaysFalse, "Node::is(const Node*) does not support this type."); + return false; + } +} + +template +T* Node::isa(Node* n) { + return const_cast(Node::isa(const_cast(n))); +} + +template +const T* Node::isa(const Node* n) { + if (n == nullptr) { + return nullptr; + } + if constexpr (false) { + return nullptr; + } +#define NODE_ISA_CONST_CASES(type) \ + else if constexpr (std::is_same_v) { \ + return n->isa_##type(); \ + } +NODE_METHODS(NODE_ISA_CONST_CASES) +#undef NODE_ISA_CONST_CASES + else { + static_assert(DependentAlwaysFalse, "Node::isa(const Node*) does not support this type."); + return nullptr; + } +} + +template +T* Node::isa(std::nullptr_t) { + return nullptr; +} + +template +T* Node::as(Node* n) { + return const_cast(Node::as(const_cast(n))); +} + +template +const T* Node::as(const Node* n) { + assert(n != nullptr, "invalid null node"); + if constexpr (false) { + return nullptr; + } +#define NODE_AS_CONST_CASES(type) \ + else if constexpr (std::is_same_v) { \ + return n->as_##type(); \ + } +NODE_METHODS(NODE_AS_CONST_CASES) +#undef NODE_AS_CONST_CASES + else { + static_assert(DependentAlwaysFalse, "Node::as(const Node*) does not support this type."); + return nullptr; + } +} + +#undef NODE_METHODS + inline bool not_a_node(const Node* n) { if (n == nullptr) return true; if (((intptr_t)n & 1) != 0) return true; // uninitialized, etc. diff --git a/src/hotspot/share/opto/output.cpp b/src/hotspot/share/opto/output.cpp index f30d647fab5d..cf5463145a52 100644 --- a/src/hotspot/share/opto/output.cpp +++ b/src/hotspot/share/opto/output.cpp @@ -799,7 +799,7 @@ void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, ObjectValue* sv = sv_for_node_id(objs, spobj->_idx); if (sv == nullptr) { - ciKlass* cik = t->is_oopptr()->exact_klass(); + ciKlass* cik = t->as_oopptr()->exact_klass(); assert(cik->is_instance_klass() || cik->is_array_klass(), "Not supported allocation."); uint first_ind = spobj->first_index(sfpt->jvms()); @@ -810,7 +810,7 @@ void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, Node* null_marker_node = sfpt->in(first_ind++); assert(null_marker_node != nullptr, "null_marker node not found"); if (!null_marker_node->is_top()) { - const TypeInt* null_marker_type = null_marker_node->bottom_type()->is_int(); + const TypeInt* null_marker_type = null_marker_node->bottom_type()->as_int(); if (null_marker_node->is_Con()) { properties = new ConstantIntValue(null_marker_type->get_con()); } else { @@ -820,7 +820,7 @@ void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, } } if (cik->is_array_klass() && !cik->is_type_array_klass()) { - properties = new ConstantIntValue(array_description_value(t->is_aryptr())); + properties = new ConstantIntValue(array_description_value(t->as_aryptr())); } sv = new ObjectValue(spobj->_idx, new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()), true, properties); @@ -949,35 +949,35 @@ void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, break; case Type::AryPtr: case Type::InstPtr: // fall through - array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding())); + array->append(new ConstantOopWriteValue(t->as_oopptr()->const_oop()->constant_encoding())); break; case Type::NarrowOop: if (t == TypeNarrowOop::NULL_PTR) { array->append(new ConstantOopWriteValue(nullptr)); } else { - array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding())); + array->append(new ConstantOopWriteValue(t->make_ptr()->as_oopptr()->const_oop()->constant_encoding())); } break; case Type::Int: - array->append(new ConstantIntValue(t->is_int()->get_con())); + array->append(new ConstantIntValue(t->as_int()->get_con())); break; case Type::RawPtr: // A return address (T_ADDRESS). - assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI"); + assert((intptr_t)t->as_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI"); #ifdef _LP64 // Must be restored to the full-width 64-bit stack slot. - array->append(new ConstantLongValue(t->is_ptr()->get_con())); + array->append(new ConstantLongValue(t->as_ptr()->get_con())); #else - array->append(new ConstantIntValue(t->is_ptr()->get_con())); + array->append(new ConstantIntValue(t->as_ptr()->get_con())); #endif break; case Type::FloatCon: { - float f = t->is_float_constant()->getf(); + float f = t->as_float_constant()->getf(); array->append(new ConstantIntValue(jint_cast(f))); break; } case Type::DoubleCon: { - jdouble d = t->is_double_constant()->getd(); + jdouble d = t->as_double_constant()->getd(); #ifdef _LP64 array->append(new ConstantIntValue((jint)0)); array->append(new ConstantDoubleValue(d)); @@ -997,7 +997,7 @@ void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, break; } case Type::Long: { - jlong d = t->is_long()->get_con(); + jlong d = t->as_long()->get_con(); #ifdef _LP64 array->append(new ConstantIntValue((jint)0)); array->append(new ConstantLongValue(d)); @@ -1157,13 +1157,13 @@ void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) { scval = PhaseOutput::sv_for_node_id(objs, spobj->_idx); if (scval == nullptr) { const Type *t = spobj->bottom_type(); - ciKlass* cik = t->is_oopptr()->exact_klass(); + ciKlass* cik = t->as_oopptr()->exact_klass(); assert(cik->is_instance_klass() || cik->is_array_klass(), "Not supported allocation."); assert(!cik->is_value_klass(), "Synchronization on value object?"); ScopeValue* properties = nullptr; if (cik->is_array_klass() && !cik->is_type_array_klass()) { - properties = new ConstantIntValue(array_description_value(t->is_aryptr())); + properties = new ConstantIntValue(array_description_value(t->as_aryptr())); } ObjectValue* sv = new ObjectValue(spobj->_idx, new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()), true, properties); @@ -1216,7 +1216,7 @@ void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) { } } else { const TypePtr *tp = obj_node->get_ptr_type(); - scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding()); + scval = new ConstantOopWriteValue(tp->as_oopptr()->const_oop()->constant_encoding()); } OptoReg::Name box_reg = BoxLockNode::reg(box_node); @@ -3061,8 +3061,8 @@ void Scheduling::ComputeRegisterAntidependencies(Block *b) { // Add precedence edge from following safepoint to use of derived pointer for (uint k = 1; k < m->req(); k++) { const Type *t = m->in(k)->bottom_type(); - if (t->isa_oop_ptr() && - t->is_ptr()->offset() != 0) { + if (t->is_oopptr() && + t->as_ptr()->offset() != 0) { need_safept_prec = true; break; } @@ -3135,7 +3135,7 @@ void Scheduling::garbage_collect_pinch_nodes() { int trace_cnt = 0; for (uint k = 0; k < _reg_node.max(); k++) { Node* pinch = _reg_node[k]; - if ((pinch != nullptr) && pinch->Opcode() == Op_Node && + if (Node::is_exact(pinch) && // no predecence input edges (pinch->req() == pinch->len() || pinch->in(pinch->req()) == nullptr) ) { cleanup_pinch(pinch); @@ -3160,7 +3160,7 @@ void Scheduling::garbage_collect_pinch_nodes() { // Clean up a pinch node for reuse. void Scheduling::cleanup_pinch( Node *pinch ) { - assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking"); + assert(Node::is_exact(pinch) && pinch->req() == 1, "just checking"); for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) { Node* use = pinch->last_out(i); diff --git a/src/hotspot/share/opto/parse.hpp b/src/hotspot/share/opto/parse.hpp index d8d34b8118ac..a9cbd66d3cbb 100644 --- a/src/hotspot/share/opto/parse.hpp +++ b/src/hotspot/share/opto/parse.hpp @@ -453,6 +453,7 @@ class Parse : public GraphKit { void init_blocks(); void load_state_from(Block* b); void store_state_to(Block* b) { b->record_state(this); } + void canonicalize_early_larval_aliases(); // Parse all the basic blocks. void do_all_blocks(); diff --git a/src/hotspot/share/opto/parse1.cpp b/src/hotspot/share/opto/parse1.cpp index 53eadf3e1dbb..32ee4d8dbe83 100644 --- a/src/hotspot/share/opto/parse1.cpp +++ b/src/hotspot/share/opto/parse1.cpp @@ -50,6 +50,7 @@ #include "runtime/sharedRuntime.hpp" #include "utilities/bitMap.inline.hpp" #include "utilities/copy.hpp" +#include "utilities/resizableHashTable.hpp" // Static array so we can figure out which bytecodes stop us from compiling // the most. Some of the non-static variables are needed in bytecodeInfo.cpp @@ -180,7 +181,7 @@ Node* Parse::check_interpreter_type(Node* l, ciType* ci_type, SafePointNode* &ba // are still in effect. if (unwrapped_ci_type->is_klass()) { // TypeFlow asserted a specific object type. Value must have that type. - assert(_gvn.type(l) == TypePtr::NULL_PTR || _gvn.type(l)->isa_oopptr(), "must be an oop"); + assert(_gvn.type(l) == TypePtr::NULL_PTR || _gvn.type(l)->is_oopptr(), "must be an oop"); if (ci_type->is_null_free()) { // Check value types for null here to prevent checkcast from adding an // exception state before the bytecode entry (use 'bad_type_ctrl' instead). @@ -305,7 +306,7 @@ void Parse::load_interpreter_state(Node* osr_buf) { const Type *type = osr_block->local_type_at(index); - if (type->isa_oopptr() != nullptr) { + if (type->is_oopptr()) { // 6403625: Verify that the interpreter oopMap thinks that the oop is live // else we might load a stale oop if the MethodLiveness disagrees with the @@ -390,12 +391,12 @@ void Parse::load_interpreter_state(Node* osr_buf) { // value and the expected type is a constant. continue; } - if (StressReachabilityFences && type->isa_oopptr() != nullptr) { + if (StressReachabilityFences && type->is_oopptr()) { // Keep all oop locals alive until the method returns as if there are // reachability fences for them at the end of the method. Node* loc = local(index); if (!loc->is_ValueType() && loc->bottom_type() != TypePtr::NULL_PTR) { - assert(loc->bottom_type()->isa_oopptr() != nullptr, "%s", Type::str(loc->bottom_type())); + assert(loc->bottom_type()->is_oopptr(), "%s", Type::str(loc->bottom_type())); _stress_rf_hook->add_req(loc); } } @@ -407,12 +408,12 @@ void Parse::load_interpreter_state(Node* osr_buf) { break; } const Type *type = osr_block->local_type_at(index); - if (StressReachabilityFences && type->isa_oopptr() != nullptr) { + if (StressReachabilityFences && type->is_oopptr()) { // Keep all oops on stack alive until the method returns as if there are // reachability fences for them at the end of the method. Node* stk = stack(index); if (!stk->is_ValueType() && stk->bottom_type() != TypePtr::NULL_PTR) { - assert(stk->bottom_type()->isa_oopptr() != nullptr, "%s", Type::str(stk->bottom_type())); + assert(stk->bottom_type()->is_oopptr(), "%s", Type::str(stk->bottom_type())); _stress_rf_hook->add_req(stk); } } @@ -755,19 +756,26 @@ void Parse::do_all_blocks() { set_map(clone_map()); } - if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) { - // In the absence of irreducible loops, the Region and Phis - // associated with a merge that doesn't involve a backedge can - // be simplified now since the RPO parsing order guarantees - // that any path which was supposed to reach here has already - // been parsed or must be dead. - Node* c = control(); - Node* result = _gvn.transform(control()); - if (c != result && TraceOptoParse) { - tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx); + if (control()->is_Region()) { + if (Arguments::is_valhalla_enabled()) { + // Canonicalize early larval aliases after creating merge Phis + canonicalize_early_larval_aliases(); } - if (result != top()) { - record_for_igvn(result); + + if (!block->is_loop_head() && !has_irreducible && !block->is_handler()) { + // In the absence of irreducible loops, the Region and Phis + // associated with a merge that doesn't involve a backedge can + // be simplified now since the RPO parsing order guarantees + // that any path which was supposed to reach here has already + // been parsed or must be dead. + Node* c = control(); + Node* result = _gvn.transform(control()); + if (c != result && TraceOptoParse) { + tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx); + } + if (result != top()) { + record_for_igvn(result); + } } } @@ -847,7 +855,7 @@ void Parse::build_exits() { // Add a return value to the exit state. (Do not push it yet.) if (tf()->range_sig()->cnt() > TypeFunc::Parms) { const Type* ret_type = tf()->range_sig()->field_at(TypeFunc::Parms); - if (ret_type->isa_int()) { + if (ret_type->is_int()) { BasicType ret_bt = method()->return_type()->basic_type(); if (ret_bt == T_BOOLEAN || ret_bt == T_CHAR || @@ -1145,7 +1153,7 @@ void Parse::do_exits() { C->record_method_not_compilable("Can't determine return type."); return; } - if (ret_type->isa_int()) { + if (ret_type->is_int()) { BasicType ret_bt = method()->return_type()->basic_type(); ret_phi = mask_int_value(ret_phi, ret_bt, &_gvn); } @@ -1453,7 +1461,7 @@ void Parse::do_method_entry() { // constructor to satisfy the memory model for strict fields. if (Arguments::is_valhalla_enabled() && method()->intrinsic_id() == vmIntrinsics::_Object_init) { Node* receiver_obj = local(0); - const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr(); + const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->as_instptr(); // If there's no exact type, check if the declared type has no implementors and add a dependency const TypeKlassPtr* klass_ptr = receiver_type->as_klass_type(/* try_for_exact= */ true); ciType* klass = klass_ptr->klass_is_exact() ? klass_ptr->exact_klass() : nullptr; @@ -1490,7 +1498,7 @@ void Parse::do_method_entry() { for (int idx = 0; idx < max_locals; idx++) { Node* loc = local(idx); if (!loc->is_ValueType() && - loc->bottom_type()->isa_oopptr() != nullptr && + loc->bottom_type()->is_oopptr() && !is_auto_boxed_primitive(loc)) { // ignore auto-boxed primitives _stress_rf_hook->add_req(loc); } @@ -1568,7 +1576,7 @@ void Parse::do_method_entry() { Node* vt = ValueTypeNode::make_from_oop(this, parm, t->value_klass()); replace_in_map(parm, vt); } - } else if (UseTypeSpeculation && (i == (arg_size - 1)) && depth() == 1 && method()->is_varargs() && t->isa_aryptr()) { + } else if (UseTypeSpeculation && (i == (arg_size - 1)) && depth() == 1 && method()->is_varargs() && t->is_aryptr()) { // Speculate on varargs Object array being the default array refined type. The assumption is // that a vararg method test(Object... o) is often called as test(o1, o2, o3). javac will // translate the call so that the caller will create a new default array of Object, put o1, @@ -1576,7 +1584,7 @@ void Parse::do_method_entry() { // the method we are parsing is the top-level method of the compilation unit. Otherwise, if // it is truly called according to our assumption, we must know the exact type of the // argument because the allocation happens inside the compilation unit. - const TypePtr* spec_type = (t->speculative() != nullptr) ? t->speculative() : t->remove_speculative()->is_aryptr(); + const TypePtr* spec_type = (t->speculative() != nullptr) ? t->speculative() : t->remove_speculative()->as_aryptr(); ciSignature* method_signature = method()->signature(); ciType* parm_citype = method_signature->type_at(method_signature->count() - 1); if (!parm_citype->is_obj_array_klass()) { @@ -1590,8 +1598,8 @@ void Parse::do_method_entry() { continue; } - const TypePtr* improved_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, improved_spec_type->is_ptr()); - improved_type = improved_type->join_speculative(t)->is_ptr(); + const TypePtr* improved_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, improved_spec_type->as_ptr()); + improved_type = improved_type->join_speculative(t)->as_ptr(); if (improved_type != t) { Node* cast = _gvn.transform(new CheckCastPPNode(control(), parm, improved_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing)); replace_in_map(parm, cast); @@ -1830,6 +1838,62 @@ void Parse::load_state_from(Block* block) { set_sp( block->start_sp()); } +// Aliases of the same early larval object can end up as different Phi nodes at +// a control-flow merge. Canonicalize all live aliases in locals and stack slots +// by their ciWrapper identity, ensuring that scalarization after '' is +// applied consistently to every alias of the same allocation. +void Parse::canonicalize_early_larval_aliases() { + ResourceMark rm; + const JVMState* state = jvms(); + const uint first = state->locoff(); + const uint limit = state->stkoff() + sp(); + MethodLivenessResult liveness; + bool liveness_computed = false; + using AliasHashTable = ResizeableHashTable; + AliasHashTable* aliases = nullptr; + + // Iterate over all early larvals in locals and stack in the parser map + for (uint i = first; i < limit; i++) { + Node* value = map()->in(i); + if (value == top()) { + continue; + } + ciType* type; + const bool is_local = state->is_loc(i); + const int idx = is_local ? i - state->locoff() : i - state->stkoff(); + if (is_local) { + type = block()->flow()->local_type_at(idx); + } else { + assert(state->is_stk(i), "must be an active stack slot"); + type = block()->flow()->stack_type_at(idx); + } + if (!type->is_early_larval()) { + continue; + } + if (is_local) { + if (!liveness_computed) { + liveness = method()->raw_liveness_at_bci(block()->start()); + liveness_computed = true; + } + // Exclude dead locals which may contain stale nodes + // or Phis of unrelated allocations. + if (!liveness.is_valid() || !liveness.at(idx)) { + continue; + } + } + assert(!value->is_ValueType() && _gvn.type(value)->isa_oopptr() != nullptr, "unexpected early larval"); + + if (aliases == nullptr) { + aliases = new AliasHashTable(4, MAX2(4u, limit - i)); + } + // Same ciWrapper identity -> aliases of the same early larval object + bool created; + Node** canonical_alias = aliases->put_if_absent(type->ident(), value, &created); + if (!created && value != *canonical_alias) { + map()->set_req(i, *canonical_alias); + } + } +} //-----------------------------record_state------------------------------------ void Parse::Block::record_state(Parse* p) { @@ -2227,11 +2291,10 @@ void Parse::merge_common(Parse::Block* target, int pnum) { // It is a bug if we create a phi which sees a garbage value on a live path. // Merging two value types? - if (phi != nullptr && phi->is_ValueType()) { + if (ValueTypeNode* vtm = Node::isa(phi); vtm != nullptr) { // Current value type // Reload current state because it may have been updated by ensure_phi assert(phi == map()->in(j), "unexpected value in map"); - assert(phi->as_ValueType()->has_phi_inputs(r), ""); - ValueTypeNode* vtm = phi->as_ValueType(); // Current value type + assert(vtm->has_phi_inputs(r), ""); ValueTypeNode* vtn = n->as_ValueType(); // Incoming value type assert(vtm == phi, "Value type should have Phi input"); @@ -2441,7 +2504,7 @@ int Parse::Block::add_new_path() { // unsound, as we may replace a Phi which has a narrower Type with one of its input which has a // wider Type. Node* Parse::maybe_narrow_phi_input(Node* ctrl, Node* n, const Type* phi_type) { - if (phi_type->isa_oopptr() != nullptr && !_gvn.type(n)->higher_equal(phi_type)) { + if (phi_type->is_oopptr() && !_gvn.type(n)->higher_equal(phi_type)) { n = new CheckCastPPNode(ctrl, n, phi_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing); n = _gvn.transform(n); } @@ -2567,7 +2630,7 @@ PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) { // class need finalization. void Parse::call_register_finalizer() { Node* receiver = local(0); - assert(receiver != nullptr && receiver->bottom_type()->isa_instptr() != nullptr, + assert(receiver != nullptr && receiver->bottom_type()->is_instptr(), "must have non-null instance type"); const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr(); @@ -2692,7 +2755,7 @@ void Parse::return_current(Node* value) { // Insert reachability fences for all oop arguments at the end of the method. for (uint i = 1; i < _stress_rf_hook->req(); i++) { Node* referent = _stress_rf_hook->in(i); - assert(referent->bottom_type()->isa_oopptr(), "%s", Type::str(referent->bottom_type())); + assert(referent->bottom_type()->is_oopptr(), "%s", Type::str(referent->bottom_type())); insert_reachability_fence(referent); } } diff --git a/src/hotspot/share/opto/parse2.cpp b/src/hotspot/share/opto/parse2.cpp index 82f902a389ae..7996c44217b8 100644 --- a/src/hotspot/share/opto/parse2.cpp +++ b/src/hotspot/share/opto/parse2.cpp @@ -84,7 +84,7 @@ void Parse::array_load(BasicType bt) { // Handle value type arrays const TypeOopPtr* element_ptr = elemtype->make_oopptr(); - const TypeAryPtr* array_type = _gvn.type(array)->is_aryptr(); + const TypeAryPtr* array_type = _gvn.type(array)->as_aryptr(); if (!array_type->is_not_flat()) { // Cannot statically determine if array is a flat array, emit runtime check @@ -99,7 +99,7 @@ void Parse::array_load(BasicType bt) { if (!array_type->is_flat()) { assert(array_type->is_flat() || control()->in(0)->as_If()->is_flat_array_check(&_gvn), "Should be found"); // Loading from a non-flat array, casting array to not flat. - const TypeAryPtr* ary_type = _gvn.type(prep_array)->is_aryptr(); + const TypeAryPtr* ary_type = _gvn.type(prep_array)->as_aryptr(); ary_type = ary_type->cast_to_not_flat(); Node* not_flat_ary = _gvn.transform(new CheckCastPPNode(control(), prep_array, ary_type)); Node* adr = get_ptr_to_array_element(not_flat_ary, array_index, bt, ary_type->size(), control()); @@ -198,7 +198,7 @@ Node* Parse::load_from_unknown_flat_array(Node* array, Node* array_index, const insert_mem_bar_volatile(Op_MemBarCPUOrder, C->get_alias_index(TypeAryPtr::INLINES)); // Keep track of the information that the value type is in flat arrays - const Type* unknown_value = element_ptr->is_instptr()->cast_to_flat_in_array(); + const Type* unknown_value = element_ptr->as_instptr()->cast_to_flat_in_array(); return _gvn.transform(new CheckCastPPNode(control(), buffer, unknown_value)); } @@ -209,7 +209,7 @@ void Parse::array_store(BasicType bt) { if (stopped()) return; // guaranteed null or range check Node* adr = get_ptr_to_array_element(prep_array, /* index */peek(0+type2size[bt]), bt, - _gvn.type(prep_array)->is_aryptr()->size(), control()); + _gvn.type(prep_array)->as_aryptr()->size(), control()); Node* stored_value_casted = nullptr; if (bt == T_OBJECT) { @@ -222,7 +222,7 @@ void Parse::array_store(BasicType bt) { Node* const array_index = pop(); // Index in the array Node* array = pop(); // The array itself - const TypeAryPtr* array_type = _gvn.type(array)->is_aryptr(); + const TypeAryPtr* array_type = _gvn.type(array)->as_aryptr(); const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt); if (elemtype == TypeInt::BOOL) { @@ -233,7 +233,7 @@ void Parse::array_store(BasicType bt) { // Based on the value to be stored, try to determine if the array is not null-free and/or not flat. // This is only legal for non-null stores because the array_store_check always passes for null, even // if the array is null-free. Null stores are handled in GraphKit::value_array_null_guard(). - bool not_value = !stored_value_casted_type->maybe_null() && !stored_value_casted_type->is_oopptr()->can_be_value_type(); + bool not_value = !stored_value_casted_type->maybe_null() && !stored_value_casted_type->as_oopptr()->can_be_value_type(); bool not_null_free = not_value; bool not_flat = not_value || ( stored_value_casted_type->is_valueklassptr() && !stored_value_casted_type->value_klass()->maybe_flat_in_array()); @@ -260,7 +260,7 @@ void Parse::array_store(BasicType bt) { if (!array_type->is_not_flat()) { // Array might be a flat array, emit runtime checks (for null, a simple value_array_null_guard is sufficient). - assert(UseArrayFlattening && !not_flat && elemtype->is_oopptr()->can_be_value_type() && + assert(UseArrayFlattening && !not_flat && elemtype->as_oopptr()->can_be_value_type() && (!array_type->klass_is_exact() || array_type->is_flat()), "array can't be a flat array"); // If by chance (or using layout disabling flags), only the nullable version is flattenable // we could avoid this test in the else branch thereunder (the "Flat array" block) and do it @@ -271,7 +271,7 @@ void Parse::array_store(BasicType bt) { // only apply with extra (experimental) flags which makes the optimization not worth. array = value_array_null_guard(array, stored_value_casted, 3); // Reload array type which could have been updated by value_array_null_guard(). - array_type = _gvn.type(array)->is_aryptr(); + array_type = _gvn.type(array)->as_aryptr(); IdealKit ideal(this); ideal.if_then(flat_array_test(array, /* flat = */ false)); { // Non-flat array @@ -279,7 +279,7 @@ void Parse::array_store(BasicType bt) { sync_kit(ideal); assert(array_type->is_not_flat() || ideal.ctrl()->in(0)->as_If()->is_flat_array_check(&_gvn), "Should be found"); inc_sp(3); - access_store_at(array, adr, adr_type, stored_value_casted, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY, false); + access_store_at(array, adr, adr_type, stored_value_casted, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY, false, nullptr); dec_sp(3); ideal.sync_kit(this); } @@ -328,7 +328,7 @@ void Parse::array_store(BasicType bt) { return; } else if (!array_type->is_not_null_free()) { // Array is not flat but may be null free - assert(elemtype->is_oopptr()->can_be_value_type(), "array can't be null-free"); + assert(elemtype->as_oopptr()->can_be_value_type(), "array can't be null-free"); array = value_array_null_guard(array, stored_value_casted, 3); } } @@ -374,14 +374,14 @@ Node* Parse::prepare_array_addressing(BasicType type, int vals, const Type*& ele // Compile-time detect of null-exception? if (stopped()) return top(); - const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr(); + const TypeAryPtr* arytype = _gvn.type(ary)->as_aryptr(); const TypeInt* sizetype = arytype->size(); elemtype = arytype->elem(); if (UseUniqueSubclasses) { const Type* el = elemtype->make_ptr(); - if (el && el->isa_instptr()) { - const TypeInstPtr* toop = el->is_instptr(); + if (el != nullptr && el->is_instptr()) { + const TypeInstPtr* toop = el->as_instptr(); if (toop->instance_klass()->unique_concrete_subklass()) { // If we load from "AbstractClass[]" we must see "ConcreteSubClass". const Type* subklass = Type::get_const_type(toop->instance_klass()); @@ -427,7 +427,7 @@ Node* Parse::get_ptr_to_array_element(Node* array, Node* idx, BasicType elembt, // Check if we need a range check for an array access. This is the case if the index is either negative or if it could // be greater or equal the smallest possible array size (i.e. out-of-bounds). bool Parse::needs_range_check(const TypeInt* size_type, const Node* index) const { - const TypeInt* index_type = _gvn.type(index)->is_int(); + const TypeInt* index_type = _gvn.type(index)->as_int(); return index_type->_hi >= size_type->_lo || index_type->_lo < 0; } @@ -537,7 +537,7 @@ Node* Parse::cast_to_speculative_array_type(Node* const array, const TypeAryPtr* uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile); } replace_in_map(array, casted_array); - array_type = _gvn.type(casted_array)->is_aryptr(); + array_type = _gvn.type(casted_array)->as_aryptr(); element_type = array_type->elem(); return casted_array; } @@ -565,7 +565,7 @@ Node* Parse::speculate_non_null_free_array(Node* const array, const TypeAryPtr*& bool null_free_array = true; Deoptimization::DeoptReason reason = Deoptimization::Reason_none; if (array_type->speculative() != nullptr && - array_type->speculative()->is_aryptr()->is_not_null_free() && + array_type->speculative()->as_aryptr()->is_not_null_free() && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) { null_free_array = false; reason = Deoptimization::Reason_speculate_class_check; @@ -586,7 +586,7 @@ Node* Parse::speculate_non_null_free_array(Node* const array, const TypeAryPtr*& assert(!stopped(), "null-free array should have been caught earlier"); Node* casted_array = _gvn.transform(new CheckCastPPNode(control(), array, array_type->cast_to_not_null_free())); replace_in_map(array, casted_array); - array_type = _gvn.type(casted_array)->is_aryptr(); + array_type = _gvn.type(casted_array)->as_aryptr(); return casted_array; } return array; @@ -598,7 +598,7 @@ Node* Parse::speculate_non_flat_array(Node* const array, const TypeAryPtr* const bool flat_array = true; Deoptimization::DeoptReason reason = Deoptimization::Reason_none; if (array_type->speculative() != nullptr && - array_type->speculative()->is_aryptr()->is_not_flat() && + array_type->speculative()->as_aryptr()->is_not_flat() && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) { flat_array = false; reason = Deoptimization::Reason_speculate_class_check; @@ -2501,7 +2501,7 @@ IfNode* Parse::acmp_fast_path_if_from_substitutable_call(PhaseGVN* phase, CallSt if (!node->is_Con()) return false; TypeNode* con = node->as_Type(); assert(con->type()->is_intptr_t(), ""); - return con->type()->is_intptr_t()->is_con(in_bytes(n)); + return con->type()->as_intptr_t()->is_con(in_bytes(n)); }; assert(call->in(TypeFunc::Control) != nullptr, ""); @@ -2509,9 +2509,7 @@ IfNode* Parse::acmp_fast_path_if_from_substitutable_call(PhaseGVN* phase, CallSt IfProjNode* if_proj = call->in(TypeFunc::Control)->as_IfProj(); if (if_proj->_con != 1) return nullptr; - assert(if_proj->in(0) != nullptr, ""); - assert(if_proj->in(0)->is_If(), ""); - IfNode* iff = if_proj->in(0)->as_If(); + IfNode* iff = Node::as(if_proj->in(0)); assert(iff->in(1) != nullptr, ""); if (!iff->in(1)->is_Bool()) return nullptr; @@ -2529,8 +2527,7 @@ IfNode* Parse::acmp_fast_path_if_from_substitutable_call(PhaseGVN* phase, CallSt LoadNode* load_offset = cmp_i->in(1)->as_Load(); if (!cmp_i->in(2)->is_ConI()) return nullptr; ConINode* zero_i = cmp_i->in(2)->as_ConI(); - assert(zero_i->type()->is_int() != nullptr, ""); - if (!zero_i->type()->is_int()->is_con(0)) return nullptr; + if (!zero_i->type()->as_int()->is_con(0)) return nullptr; assert(load_offset->in(2) != nullptr, ""); if (!load_offset->in(2)->is_AddP()) return nullptr; @@ -2552,7 +2549,7 @@ IfNode* Parse::acmp_fast_path_if_from_substitutable_call(PhaseGVN* phase, CallSt assert(members_addr_add->in(AddPNode::Address) != nullptr, ""); assert(members_addr_add->in(AddPNode::Offset) != nullptr, ""); if (!members_addr_add->in(AddPNode::Base)->is_top()) return nullptr; - if (!phase->type(members_addr_add->in(AddPNode::Address))->isa_instklassptr()) return nullptr; + if (!phase->type(members_addr_add->in(AddPNode::Address))->is_instklassptr()) return nullptr; if (!is_con_offset(members_addr_add->in(AddPNode::Offset), ValueKlass::adr_members_offset())) return nullptr; return iff; @@ -2702,15 +2699,15 @@ static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) { } else { ldk = n; } - assert(ldk != nullptr && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node"); + assert(Node::is(ldk), "should have found a LoadKlass or LoadNKlass node"); Node* adr = ldk->in(MemNode::Address); intptr_t off = 0; Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off); if (obj == nullptr || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass? return nullptr; - const TypePtr* tp = gvn->type(obj)->is_ptr(); - if (tp == nullptr || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr? + const TypePtr* tp = gvn->type(obj)->as_ptr(); + if (!(tp->is_instptr() || tp->is_aryptr())) // is obj a Java object ptr? return nullptr; return obj; @@ -2731,7 +2728,7 @@ static bool match_type_check(PhaseGVN& gvn, // Look for opportunities to sharpen the type of a node whose klass is compared with a constant klass. // The constant klass being tested against can come from many bytecode instructions (implicitly or explicitly), // and also from profile data used by speculative casts. - if (btest == BoolTest::eq && tcon->isa_klassptr()) { + if (btest == BoolTest::eq && tcon->is_klassptr()) { // Found: // Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq]) // or the narrowOop equivalent. @@ -2742,7 +2739,7 @@ static bool match_type_check(PhaseGVN& gvn, // These patterns with nullable klasses arise from example from // load_array_klass_from_mirror. if (*obj == nullptr) { return false; } - (*cast_type) = tcon->isa_klassptr()->as_exact_instance_type(); + (*cast_type) = tcon->as_klassptr()->as_exact_instance_type(); return true; // found } @@ -2769,11 +2766,11 @@ static bool match_type_check(PhaseGVN& gvn, // Bool [btest] // | // - if (tcon->isa_int() && val->is_Phi() && val->in(0)->as_Region()->is_diamond()) { + if (tcon->is_int() && val->is_Phi() && val->in(0)->as_Region()->is_diamond()) { RegionNode* diamond = val->in(0)->as_Region(); IfNode* if1 = diamond->in(1)->in(0)->as_If(); BoolNode* b1 = if1->in(1)->isa_Bool(); - if (b1 != nullptr && b1->in(1)->isa_SubTypeCheck()) { + if (b1 != nullptr && b1->in(1)->is_SubTypeCheck()) { assert(b1->_test._test == BoolTest::eq || b1->_test._test == BoolTest::ne, "%d", b1->_test._test); @@ -2785,15 +2782,15 @@ static bool match_type_check(PhaseGVN& gvn, // gen_instanceof() emits 1 on success and 0 on failure. // Check whether current comparison selects the success value. const Type* success_tval = gvn.type(val->in(success_idx)); - assert(success_tval->isa_int(), "not an int: %s", Type::str(success_tval)); + assert(success_tval->is_int(), "not an int: %s", Type::str(success_tval)); if ((btest == BoolTest::eq && tcon == success_tval) || (btest == BoolTest::ne && tcon->join(success_tval)->empty())) { SubTypeCheckNode* sub = b1->in(1)->as_SubTypeCheck(); Node* obj_or_subklass = sub->in(SubTypeCheckNode::ObjOrSubKlass); Node* superklass = sub->in(SubTypeCheckNode::SuperKlass); - if (gvn.type(obj_or_subklass)->isa_oopptr()) { - const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->is_klassptr(); + if (gvn.type(obj_or_subklass)->is_oopptr()) { + const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->as_klassptr(); const TypeKlassPtr* improved_klass_ptr_type = klass_ptr_type->try_improve(); (*obj) = obj_or_subklass; @@ -2834,7 +2831,7 @@ void Parse::sharpen_type_after_if(BoolTest::mask btest, _gvn.set_type_bottom(ccast); record_for_igvn(ccast); if (tboth->is_valueklassptr()) { - ccast = ValueTypeNode::make_from_oop(this, ccast, tboth->isa_oopptr()->exact_klass(true)->as_value_klass()); + ccast = ValueTypeNode::make_from_oop(this, ccast, tboth->as_oopptr()->exact_klass(true)->as_value_klass()); } // Here's the payoff. replace_in_map(obj, ccast); @@ -2862,7 +2859,7 @@ void Parse::sharpen_type_after_if(BoolTest::mask btest, { const Type* tboth = tcon->join_speculative(tval); if (tboth == tval) break; // Nothing to gain. - if (tcon->isa_int()) { + if (tcon->is_int()) { ccast = new CastIINode(control(), val, tboth); } else if (tcon == TypePtr::NULL_PTR) { // Cast to null, but keep the pointer identity temporarily live. @@ -2933,7 +2930,7 @@ Node* Parse::optimize_cmp_with_klass(Node* c) { if (load_klass->in(2)->is_AddP()) { Node* addp = load_klass->in(2); Node* obj = addp->in(AddPNode::Address); - const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); + const TypeOopPtr* obj_type = _gvn.type(obj)->as_oopptr(); if (obj_type->speculative_type_not_null() != nullptr) { ciKlass* k = obj_type->speculative_type(); inc_sp(2); diff --git a/src/hotspot/share/opto/parse3.cpp b/src/hotspot/share/opto/parse3.cpp index 7284be3720fb..7f8d8662d1f2 100644 --- a/src/hotspot/share/opto/parse3.cpp +++ b/src/hotspot/share/opto/parse3.cpp @@ -157,8 +157,9 @@ void Parse::do_get_xxx(Node* obj, ciField* field) { Node* ld = nullptr; if (field_klass->is_value_klass()) { // could also have an abstract value class ciValueKlass* vk = field_klass->as_value_klass(); - if (field->is_null_free() && vk->is_empty()) { - // Loading from a field of an empty value type. Just return the default instance. + if (field->is_null_free() && !field->is_volatile() && vk->is_empty()) { + // Loading from a null-free field of an empty value type. Just return the default instance. + // Skip volatile fields because their memory barriers need to remain. ld = ValueTypeNode::make_all_zero(_gvn, vk); } else if (field->is_flat()) { // Loading from a flat value type field. @@ -183,7 +184,7 @@ void Parse::do_get_xxx(Node* obj, ciField* field) { if (con->is_null_object()) { type = TypePtr::NULL_PTR; } else { - type = TypeOopPtr::make_from_constant(con)->isa_oopptr(); + type = TypeOopPtr::make_from_constant(con); } assert(type != nullptr, "field singleton type must be consistent"); } else { @@ -408,7 +409,7 @@ Node* Parse::expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, in guarantee(length_con >= 0, "non-constant multianewarray"); ciArrayKlass* array_klass_1 = array_klass->as_obj_array_klass()->element_klass()->as_array_klass(); const TypePtr* adr_type = TypeAryPtr::OOPS; - const TypeOopPtr* elemtype = _gvn.type(array)->is_aryptr()->elem()->make_oopptr(); + const TypeOopPtr* elemtype = _gvn.type(array)->as_aryptr()->elem()->make_oopptr(); const intptr_t header = arrayOopDesc::base_offset_in_bytes(T_OBJECT); for (jint i = 0; i < length_con; i++) { Node* elem = expand_multianewarray(array_klass_1, &lengths[1], ndimensions-1, nargs); @@ -534,12 +535,12 @@ void Parse::do_multianewarray() { const Type* type = TypeOopPtr::make_from_klass_raw(array_klass, Type::trust_interfaces); // Improve the type: We know it's not null, exact, and of a given length. - type = type->is_ptr()->cast_to_ptr_type(TypePtr::NotNull); - type = type->is_aryptr()->cast_to_exactness(true); + type = type->as_ptr()->cast_to_ptr_type(TypePtr::NotNull); + type = type->as_aryptr()->cast_to_exactness(true); const TypeInt* ltype = _gvn.find_int_type(length[0]); if (ltype != nullptr) - type = type->is_aryptr()->cast_to_size(ltype); + type = type->as_aryptr()->cast_to_size(ltype); // We cannot sharpen the nested sub-arrays, since the top level is mutable. diff --git a/src/hotspot/share/opto/parseHelper.cpp b/src/hotspot/share/opto/parseHelper.cpp index ef161d758d1d..7e4e1713c631 100644 --- a/src/hotspot/share/opto/parseHelper.cpp +++ b/src/hotspot/share/opto/parseHelper.cpp @@ -160,7 +160,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { // This cutout lets us avoid the uncommon_trap(Reason_array_check) // below, which turns into a performance liability if the // gen_checkcast folds up completely. - if (_gvn.type(ary)->is_aryptr()->is_null_free()) { + if (_gvn.type(ary)->as_aryptr()->is_null_free()) { null_check(obj); } return obj; @@ -169,7 +169,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { // Extract the array klass type Node* array_klass = load_object_klass(ary); // Get the array klass - const TypeKlassPtr* tak = _gvn.type(array_klass)->is_klassptr(); + const TypeKlassPtr* tak = _gvn.type(array_klass)->as_klassptr(); // The type of array_klass is usually INexact array-of-oop. Heroically // cast array_klass to EXACT array and uncommon-trap if the cast fails. @@ -178,13 +178,13 @@ Node* Parse::array_store_check(const Type*& elemtype) { if (MonomorphicArrayCheck && !tak->klass_is_exact()) { // Make a constant out of the inexact array klass const TypeAryKlassPtr* extak = nullptr; - const TypeOopPtr* ary_t = _gvn.type(ary)->is_oopptr(); + const TypeOopPtr* ary_t = _gvn.type(ary)->as_oopptr(); ciKlass* ary_spec = ary_t->speculative_type(); Deoptimization::DeoptReason reason = Deoptimization::Reason_none; // Try to cast the array to an exact type from profile data. First // check the speculative type. if (ary_spec != nullptr && !too_many_traps(Deoptimization::Reason_speculate_class_check)) { - extak = TypeKlassPtr::make(ary_spec)->is_aryklassptr(); + extak = TypeKlassPtr::make(ary_spec)->as_aryklassptr(); reason = Deoptimization::Reason_speculate_class_check; } else if (UseArrayLoadStoreProfile) { // No speculative type: check profile data at this bci. @@ -197,10 +197,10 @@ Node* Parse::array_store_check(const Type*& elemtype) { bool null_free_array = true; method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array); if (array_type != nullptr) { - extak = TypeKlassPtr::make(array_type)->is_aryklassptr(); + extak = TypeKlassPtr::make(array_type)->as_aryklassptr(); } } - } else if (!too_many_traps(Deoptimization::Reason_array_check) && tak->isa_aryklassptr()) { + } else if (!too_many_traps(Deoptimization::Reason_array_check) && tak->is_aryklassptr()) { // If the compiler has determined that the type of array 'ary' (represented // by 'array_klass') is java/lang/Object, the compiler must not assume that // the array 'ary' is monomorphic. @@ -219,7 +219,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { // 'array_klass' to be ObjArrayKlass, which can result in invalid memory accesses. // // See issue JDK-8057622 for details. - extak = tak->cast_to_exactness(true)->is_aryklassptr(); + extak = tak->cast_to_exactness(true)->as_aryklassptr(); reason = Deoptimization::Reason_array_check; } if (extak != nullptr && extak->exact_klass(true) != nullptr) { @@ -242,7 +242,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, extak->as_exact_instance_type())); replace_in_map(ary, cast); ary = cast; - elemtype = _gvn.type(ary)->is_aryptr()->elem(); + elemtype = _gvn.type(ary)->as_aryptr()->elem(); CompileLog* log = C->log(); if (log != nullptr) { @@ -261,7 +261,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { Node* a_e_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p2, tak)); // If we statically know that this is a value type array, use precise element klass for checkcast - const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr(); + const TypeAryPtr* arytype = _gvn.type(ary)->as_aryptr(); const TypePtr* elem_ptr = elemtype->make_ptr(); bool null_free = arytype->is_null_free(); if (elem_ptr->is_valueklassptr()) { @@ -285,7 +285,7 @@ Node* Parse::array_store_check(const Type*& elemtype) { // merged or hidden behind super types. Therefore, an inexact null-free array always represents some kind of // value type array - either of an abstract value class or Object. if (null_free) { - ciKlass* klass = elem_ptr->is_instptr()->instance_klass(); + ciKlass* klass = elem_ptr->as_instptr()->instance_klass(); if (klass->exact_klass()) { assert(elem_ptr->is_valueklassptr() || arytype->is_autobox_cache(), "elements must be value type or autobox cache"); } else { @@ -348,8 +348,7 @@ void Parse::do_new() { // Debug dump of the mapping from address types to MergeMemNode indices. void Parse::dump_map_adr_mem() const { tty->print_cr("--- Mapping from address types to memory Nodes ---"); - MergeMemNode *mem = map() == nullptr ? nullptr : (map()->memory()->is_MergeMem() ? - map()->memory()->as_MergeMem() : nullptr); + MergeMemNode* mem = map() == nullptr ? nullptr : map()->memory()->isa_MergeMem(); for (uint i = 0; i < (uint)C->num_alias_types(); i++) { C->alias_type(i)->print_on(tty); tty->print("\t"); diff --git a/src/hotspot/share/opto/phaseX.cpp b/src/hotspot/share/opto/phaseX.cpp index 937a575cdc4c..70c1d9d2ccc1 100644 --- a/src/hotspot/share/opto/phaseX.cpp +++ b/src/hotspot/share/opto/phaseX.cpp @@ -36,6 +36,7 @@ #include "opto/idealGraphPrinter.hpp" #include "opto/loopnode.hpp" #include "opto/machnode.hpp" +#include "opto/node.hpp" #include "opto/opcodes.hpp" #include "opto/phaseX.hpp" #include "opto/regalloc.hpp" @@ -534,13 +535,13 @@ int PhaseRenumberLive::update_embedded_ids(Node* n) { } const Type* type = _new_type_array.fast_lookup(n->_idx); - if (type != nullptr && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) { + if (type != nullptr && type->is_oopptr() && type->as_oopptr()->is_known_instance()) { if (!_is_pass_finished) { return -1; // delay } - int old_idx = type->is_oopptr()->instance_id(); + int old_idx = type->as_oopptr()->instance_id(); int new_idx = new_index(old_idx); - const Type* new_type = type->is_oopptr()->with_instance_id(new_idx); + const Type* new_type = type->as_oopptr()->with_instance_id(new_idx); _new_type_array.map(n->_idx, new_type); no_of_updates++; } @@ -604,8 +605,8 @@ ConNode* PhaseValues::makecon(const Type* t) { switch (t->base()) { // fast paths case Type::Half: case Type::Top: return (ConNode*) C->top(); - case Type::Int: return intcon( t->is_int()->get_con() ); - case Type::Long: return longcon( t->is_long()->get_con() ); + case Type::Int: return intcon(t->as_int()->get_con()); + case Type::Long: return longcon(t->as_long()->get_con()); default: break; } if (t->is_zero_type()) @@ -1075,8 +1076,8 @@ bool PhaseIterGVN::needs_deep_revisit(const Node* n) const { if (n->Opcode() == Op_CmpP) { const Type* t1 = type_or_null(n->in(1)); const Type* t2 = type_or_null(n->in(2)); - return t1 != nullptr && t1->isa_oopptr() && - t2 != nullptr && t2->isa_oopptr(); + return t1 != nullptr && t1->is_oopptr() && + t2 != nullptr && t2->is_oopptr(); } // IfNode::Ideal() -> search_identical() walks up the CFG dominator tree. // RangeCheckNode::Ideal() scans up to ~999 nodes up the chain. @@ -1246,8 +1247,8 @@ void PhaseIterGVN::optimize(bool deep) { static bool klass_bottom_type_invalidated(const Node* n, const Type* new_type) { // Concurrent class loading can invalidate a klass bottom type. const Type* bt = n->bottom_type(); - return (bt->isa_klassptr() != nullptr || - bt->isa_narrowklass() != nullptr) && + return (bt->is_klassptr() || + bt->is_narrowklass()) && !new_type->higher_equal_speculative(bt); } @@ -1336,9 +1337,9 @@ void PhaseIterGVN::verify_Value_for(const Node* n, const Type* tnew, bool strict } // Exception (1) // Integer "widen" changes, but range is the same. - if (told->isa_integer(tnew->basic_type()) != nullptr) { // both either int or long - const TypeInteger* t0 = told->is_integer(tnew->basic_type()); - const TypeInteger* t1 = tnew->is_integer(tnew->basic_type()); + if (told->is_integer(tnew->basic_type())) { // both either int or long + const TypeInteger* t0 = told->as_integer(tnew->basic_type()); + const TypeInteger* t1 = tnew->as_integer(tnew->basic_type()); if (t0->lo_as_long() == t1->lo_as_long() && t0->hi_as_long() == t1->hi_as_long()) { return; // ignore integer widen @@ -1354,7 +1355,7 @@ void PhaseIterGVN::verify_Value_for(const Node* n, const Type* tnew, bool strict } // Exception (3) // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away. - if (!strict && n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) { + if (!strict && n->Opcode() == Op_CmpP && type(n->in(1))->is_oopptr() && type(n->in(2))->is_oopptr()) { // SubNode::Value // CmpPNode::sub // MemNode::detect_ptr_independence @@ -2273,7 +2274,7 @@ void PhaseIterGVN::remove_globally_dead_node(Node* dead, NodeOrigin origin) { _worklist.push(in); } if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory && - in->is_Proj() && in->in(0) != nullptr && in->in(0)->is_Initialize()) { + in->is_Proj() && Node::is(in->in(0))) { // A Load that directly follows an InitializeNode is // going away. The Stores that follow are candidates // again to be captured by the InitializeNode. @@ -2536,10 +2537,10 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ Node* castii = in1->fast_out(j); if (castii->is_CastII() && castii->as_CastII()->carry_dependency()) { // Find If. - if (castii->in(0) != nullptr && castii->in(0)->in(0) != nullptr && castii->in(0)->in(0)->is_If()) { + if (castii->in(0) != nullptr && Node::is(castii->in(0)->in(0))) { Node* ifnode = castii->in(0)->in(0); // Check that if connects to the cmp - if (ifnode->in(1) != nullptr && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == cmp) { + if (Node::is(ifnode->in(1)) && ifnode->in(1)->in(1) == cmp) { worklist.push(castii); } } @@ -2832,6 +2833,19 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ } } } + // Check for MinI/MaxI(MinI/MaxI(AddI(x, conx), other), AddI(y, cony)) + // -> MinI/MaxI(AddI(x, MinI/MaxI(conx, cony)), other), where all + // operations are either MinI or MaxI. This requires a 3-hop + // notification like above. + if (use_op == Op_AddI) { + for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) { + if (Node* u2 = use->fast_out(i); Node::is(u2)) { + add_users_to_worklist_if(worklist, u2, [](Node* u1) { + return u1->is_MinMax(); + }); + } + } + } // Check for A | (B | C) and (B | C) | A where A == B or A == C. if (use_op == Op_OrI || use_op == Op_OrL) { @@ -2887,11 +2901,11 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ } } } - if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) { + if (use_op == Op_LoadP && use->bottom_type()->is_rawptr()) { for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) { Node* u = use->fast_out(i2); const Type* ut = u->bottom_type(); - if (u->Opcode() == Op_LoadP && ut->isa_instptr()) { + if (u->Opcode() == Op_LoadP && ut->is_instptr()) { worklist.push(u); } } @@ -2901,8 +2915,8 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ Node* c = use; do { c = c->unique_ctrl_out_or_null(); - } while (c != nullptr && c->is_Region()); - if (c != nullptr && c->is_CallStaticJava() && c->as_CallStaticJava()->uncommon_trap_request() != 0) { + } while (Node::is(c)); + if (auto call = Node::isa(c); call != nullptr && call->uncommon_trap_request() != 0) { worklist.push(c); } } @@ -2982,10 +2996,7 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ // set_req_X() after clearing one input leaves the shared input with a // single user and has_special_unique_user() is true. 'u' is still being // disconnected, so a required input may already be null. - Node* in1 = u->in(1); - Node* in2 = u->in(2); - return (in1 != nullptr && in1->Opcode() == Op_Replicate) || - (in2 != nullptr && in2->Opcode() == Op_Replicate); + return Node::is_exact(u->in(1)) || Node::is_exact(u->in(2)); }); } @@ -3124,6 +3135,12 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ }; use->visit_uses(push_phi_to_worklist, is_boundary); } + // DecodeN of a Phi of EncodePs is transformed into a Phi of the EncodePs' inputs + if (use->is_Phi()) { + add_users_to_worklist_if(worklist, use, [](Node* u) { + return u->is_DecodeN(); + }); + } } /** @@ -3171,8 +3188,8 @@ void PhaseCCP::verify_type(Node* n, const Type* tnew, const Type* told) { tty->print("tnew = "); tnew->dump(); tty->cr(); fatal("Not monotonic"); } - assert(!told->isa_int() || !tnew->isa_int() || told->is_int()->_widen <= tnew->is_int()->_widen, "widen increases"); - assert(!told->isa_long() || !tnew->isa_long() || told->is_long()->_widen <= tnew->is_long()->_widen, "widen increases"); + assert(!told->is_int() || !tnew->is_int() || told->as_int()->_widen <= tnew->as_int()->_widen, "widen increases"); + assert(!told->is_long() || !tnew->is_long() || told->as_long()->_widen <= tnew->as_long()->_widen, "widen increases"); } #endif //ASSERT @@ -3275,7 +3292,7 @@ bool PhaseCCP::needs_revisit(Node* n) const { return true; } // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away. - if (n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) { + if (n->Opcode() == Op_CmpP && type(n->in(1))->is_oopptr() && type(n->in(2))->is_oopptr()) { return true; } return false; @@ -3483,11 +3500,11 @@ void PhaseCCP::push_cast(Unique_Node_List& worklist, const Node* use) { // Loading the java mirror from a Klass requires two loads and the type of the mirror load depends on the type of 'n'. // See LoadNode::Value(). void PhaseCCP::push_loadp(Unique_Node_List& worklist, const Node* use) const { - if (use->Opcode() == Op_LoadP && use->bottom_type()->isa_rawptr()) { + if (use->Opcode() == Op_LoadP && use->bottom_type()->is_rawptr()) { for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) { Node* loadp = use->fast_out(i); const Type* ut = loadp->bottom_type(); - if (loadp->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(loadp)) { + if (loadp->Opcode() == Op_LoadP && ut->is_instptr() && ut != type(loadp)) { worklist.push(loadp); } } diff --git a/src/hotspot/share/opto/reachability.hpp b/src/hotspot/share/opto/reachability.hpp index ba435c8484f2..d8a61b3b0dd4 100644 --- a/src/hotspot/share/opto/reachability.hpp +++ b/src/hotspot/share/opto/reachability.hpp @@ -43,8 +43,8 @@ class ReachabilityFenceNode : public Node { public: ReachabilityFenceNode(Compile* C, Node* ctrl, Node* referent) : Node(1) { - assert(referent->bottom_type()->isa_oopptr() || - referent->bottom_type()->isa_narrowoop() != nullptr || + assert(referent->bottom_type()->is_oopptr() || + referent->bottom_type()->is_narrowoop() || referent->bottom_type() == TypePtr::NULL_PTR, "%s", Type::str(referent->bottom_type())); init_class_id(Class_ReachabilityFence); diff --git a/src/hotspot/share/opto/reg_split.cpp b/src/hotspot/share/opto/reg_split.cpp index f1958009bbf9..13def025b1f1 100644 --- a/src/hotspot/share/opto/reg_split.cpp +++ b/src/hotspot/share/opto/reg_split.cpp @@ -670,7 +670,7 @@ uint PhaseChaitin::Split(uint maxlrg, ResourceArea* split_arena) { for( insidx = 1; insidx <= b->end_idx(); insidx++ ) { n1 = b->get_node(insidx); // bail if this is not a phi - phi = n1->is_Phi() ? n1->as_Phi() : nullptr; + phi = n1->isa_Phi(); if( phi == nullptr ) { // Keep track of index of first non-PhiNode instruction in block non_phi = insidx; @@ -959,7 +959,7 @@ uint PhaseChaitin::Split(uint maxlrg, ResourceArea* split_arena) { insidx += b->number_of_nodes()-old_size; } - MachNode *mach = n->is_Mach() ? n->as_Mach() : nullptr; + MachNode* mach = n->isa_Mach(); // Base pointers and oopmap references do not care where they live. if ((inpidx >= oopoff) || (mach && mach->ideal_Opcode() == Op_AddP && inpidx == AddPNode::Base)) { diff --git a/src/hotspot/share/opto/split_if.cpp b/src/hotspot/share/opto/split_if.cpp index 6fddf38bc13b..ba03999fa76a 100644 --- a/src/hotspot/share/opto/split_if.cpp +++ b/src/hotspot/share/opto/split_if.cpp @@ -141,7 +141,7 @@ bool PhaseIdealLoop::split_up( Node *n, Node *blk1, Node *blk2 ) { // operations on anti-dep loads as we do their killing stores. if( n->is_Store() && n->in(MemNode::Memory)->in(0) == n->in(0) ) { // Get store's memory slice - int alias_idx = C->get_alias_index(_igvn.type(n->in(MemNode::Address))->is_ptr()); + int alias_idx = C->get_alias_index(_igvn.type(n->in(MemNode::Address))->as_ptr()); // Get memory-phi anti-dep loads will be using Node *memphi = n->in(MemNode::Memory); @@ -150,7 +150,7 @@ bool PhaseIdealLoop::split_up( Node *n, Node *blk1, Node *blk2 ) { // it will then "split-up". for (DUIterator_Fast imax,i = memphi->fast_outs(imax); i < imax; i++) { Node *load = memphi->fast_out(i); - if( load->is_Load() && alias_idx == C->get_alias_index(_igvn.type(load->in(MemNode::Address))->is_ptr()) ) + if (load->is_Load() && alias_idx == C->get_alias_index(_igvn.type(load->in(MemNode::Address))->as_ptr())) set_ctrl(load,blk1); } } diff --git a/src/hotspot/share/opto/stringopts.cpp b/src/hotspot/share/opto/stringopts.cpp index 09c797714e42..28d77348995d 100644 --- a/src/hotspot/share/opto/stringopts.cpp +++ b/src/hotspot/share/opto/stringopts.cpp @@ -554,7 +554,7 @@ StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) { } // Find the constructor call Node* result = alloc->result_cast(); - if (result == nullptr || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) { + if (!Node::is(result) || alloc->in(TypeFunc::Memory)->is_top()) { // strange looking allocation #ifndef PRODUCT if (PrintOptimizeStringConcat) { @@ -598,7 +598,7 @@ StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) { // StringBuilder(int) case. Node* parm = use->in(TypeFunc::Parms + 1); assert(parm != nullptr, "must exist"); - const TypeInt* type = _gvn->type(parm)->is_int(); + const TypeInt* type = _gvn->type(parm)->as_int(); if (type->_hi < 0) { // Initial capacity argument is always negative in which case StringBuilder(int) throws // a NegativeArraySizeException. Bail out from string opts. @@ -932,8 +932,8 @@ bool StringConcat::validate_mem_flow() { ctrl = copy->is_copy(); } else { // a cast assert(ctrl->req() == 3 && - ctrl->in(1) != nullptr && ctrl->in(1)->is_Proj() && - ctrl->in(2) != nullptr && ctrl->in(2)->is_Proj() && + Node::is(ctrl->in(1)) && + Node::is(ctrl->in(2)) && ctrl->in(1)->in(0) == ctrl->in(2)->in(0) && ctrl->in(1)->in(0) != nullptr && ctrl->in(1)->in(0)->is_If(), "must be a simple diamond"); @@ -1160,10 +1160,10 @@ bool StringConcat::validate_control_flow() { continue; } if (ptr->req() == 3 && - ptr->in(1) != nullptr && ptr->in(1)->is_Proj() && - ptr->in(2) != nullptr && ptr->in(2)->is_Proj() && + Node::is(ptr->in(1)) && + Node::is(ptr->in(2)) && ptr->in(1)->in(0) == ptr->in(2)->in(0) && - ptr->in(1)->in(0) != nullptr && ptr->in(1)->in(0)->is_If()) { + Node::is(ptr->in(1)->in(0))) { // Simple diamond. // XXX should check for possibly merging stores. simple data merges are ok. // The IGVN will make this simple diamond go away when it @@ -1452,7 +1452,7 @@ void PhaseStringOpts::getChars(GraphKit& kit, Node* arg, Node* dst_array, BasicT Node* ch = __ AddI(r, __ intcon('0')); Node* st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE), ch, bt, MemNode::unordered, false /* require_atomic_access */, - false /* unaligned */, (bt != T_BYTE) /* mismatched */); + false /* unaligned */, (bt != T_BYTE) /* mismatched */, false, false, 0); iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne), PROB_FAIR, COUNT_UNKNOWN); @@ -1491,7 +1491,7 @@ void PhaseStringOpts::getChars(GraphKit& kit, Node* arg, Node* dst_array, BasicT Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2)); st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE), sign, bt, MemNode::unordered, false /* require_atomic_access */, false /* unaligned */, - (bt != T_BYTE) /* mismatched */); + (bt != T_BYTE) /* mismatched */, false, false, 0); final_merge->init_req(merge_index + 1, kit.control()); final_mem->init_req(merge_index + 1, st); @@ -1588,7 +1588,7 @@ void PhaseStringOpts::arraycopy(GraphKit& kit, IdealKit& ideal, Node* src_array, bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0); // If true, then check if dst array address is aligned to HeapWordSize if (aligned) { - const TypeInt* tdst = __ gvn().type(start)->is_int(); + const TypeInt* tdst = __ gvn().type(start)->as_int(); aligned = tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tdst->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0); } @@ -1824,7 +1824,7 @@ Node* PhaseStringOpts::allocate_byte_array(GraphKit& kit, IdealKit* ideal, Node* jbyte PhaseStringOpts::get_constant_coder(GraphKit& kit, Node* str) { assert(str->is_Con(), "String must be constant"); - const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr(); + const TypeOopPtr* str_type = kit.gvn().type(str)->as_oopptr(); ciInstance* str_instance = str_type->const_oop()->as_instance(); jbyte coder = str_instance->field_value_by_offset(java_lang_String::coder_offset()).as_byte(); assert(CompactStrings || (coder == java_lang_String::CODER_UTF16), "Strings must be UTF16 encoded"); @@ -1838,7 +1838,7 @@ int PhaseStringOpts::get_constant_length(GraphKit& kit, Node* str) { ciTypeArray* PhaseStringOpts::get_constant_value(GraphKit& kit, Node* str) { assert(str->is_Con(), "String must be constant"); - const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr(); + const TypeOopPtr* str_type = kit.gvn().type(str)->as_oopptr(); ciInstance* str_instance = str_type->const_oop()->as_instance(); ciObject* src_array = str_instance->field_value_by_offset(java_lang_String::value_offset()).as_object(); return src_array->as_type_array(); @@ -1922,7 +1922,7 @@ void PhaseStringOpts::replace_string_concat(StringConcat* sc) { case StringConcat::NegativeIntCheckMode: { // Initial capacity argument might be negative in which case StringBuilder(int) throws // a NegativeArraySizeException. Insert a runtime check with an uncommon trap. - const TypeInt* type = kit.gvn().type(arg)->is_int(); + const TypeInt* type = kit.gvn().type(arg)->as_int(); assert(type->_hi >= 0 && type->_lo < 0, "no runtime int check needed"); Node* p = __ Bool(__ CmpI(arg, kit.intcon(0)), BoolTest::ge); IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN); @@ -2031,7 +2031,7 @@ void PhaseStringOpts::replace_string_concat(StringConcat* sc) { } case StringConcat::CharMode: { // one character only - const TypeInt* t = kit.gvn().type(arg)->is_int(); + const TypeInt* t = kit.gvn().type(arg)->as_int(); if (!coder_fixed && t->is_con()) { // Constant char if (t->get_con() <= 255) { diff --git a/src/hotspot/share/opto/subnode.cpp b/src/hotspot/share/opto/subnode.cpp index c6bb7343db7e..c9f1e64ff4e8 100644 --- a/src/hotspot/share/opto/subnode.cpp +++ b/src/hotspot/share/opto/subnode.cpp @@ -192,7 +192,7 @@ Node *SubINode::Ideal(PhaseGVN *phase, bool can_reshape){ if( t2 == Type::TOP ) return nullptr; // Convert "x-c0" into "x+ -c0". if( t2->base() == Type::Int ){ // Might be bottom or top... - const TypeInt *i = t2->is_int(); + const TypeInt* i = t2->as_int(); if( i->is_con() ) return new AddINode(in1, phase->intcon(java_negate(i->get_con()))); } @@ -214,11 +214,11 @@ Node *SubINode::Ideal(PhaseGVN *phase, bool can_reshape){ if (op2 == Op_AddI && ok_to_convert(in2, in1) && in2->in(2)->Opcode() == Op_ConI) { - jint c0 = phase->type(in2->in(2))->isa_int()->get_con(); + jint c0 = phase->type(in2->in(2))->as_int()->get_con(); Node* in21 = in2->in(1); if (in1->Opcode() == Op_ConI) { // Match c1 - jint c1 = phase->type(in1)->isa_int()->get_con(); + jint c1 = phase->type(in1)->as_int()->get_con(); Node* sub2 = phase->intcon(java_subtract(c1, c0)); return new SubINode(sub2, in21); } else { @@ -323,13 +323,13 @@ Node *SubINode::Ideal(PhaseGVN *phase, bool can_reshape){ } // Convert "0-(A>>31)" into "(A>>>31)" - if ( op2 == Op_RShiftI ) { - Node *in21 = in2->in(1); - Node *in22 = in2->in(2); - const TypeInt *zero = phase->type(in1)->isa_int(); - const TypeInt *t21 = phase->type(in21)->isa_int(); - const TypeInt *t22 = phase->type(in22)->isa_int(); - if ( t21 && t22 && zero == TypeInt::ZERO && t22->is_con(31) ) { + if (op2 == Op_RShiftI) { + Node* in21 = in2->in(1); + Node* in22 = in2->in(2); + const TypeInt* zero = phase->type(in1)->isa_int(); + bool in21_is_int = phase->type(in21)->is_int(); + const TypeInt* t22 = phase->type(in22)->isa_int(); + if (in21_is_int && t22 != nullptr && zero == TypeInt::ZERO && t22->is_con(31)) { return new URShiftINode(in21, in22); } } @@ -339,8 +339,8 @@ Node *SubINode::Ideal(PhaseGVN *phase, bool can_reshape){ // A subtract node computes the difference of its two inputs. const Type* SubINode::sub(const Type* t1, const Type* t2) const { - const TypeInt* range0 = t1->is_int(); - const TypeInt* range1 = t2->is_int(); + const TypeInt* range0 = t1->as_int(); + const TypeInt* range1 = t2->as_int(); jlong lo_sub = (jlong)range0->_lo - (jlong)range1->_hi; jlong hi_sub = (jlong)range0->_hi - (jlong)range1->_lo; @@ -409,11 +409,11 @@ Node *SubLNode::Ideal(PhaseGVN *phase, bool can_reshape) { if (op2 == Op_AddL && ok_to_convert(in2, in1) && in2->in(2)->Opcode() == Op_ConL) { - jlong c0 = phase->type(in2->in(2))->isa_long()->get_con(); + jlong c0 = phase->type(in2->in(2))->as_long()->get_con(); Node* in21 = in2->in(1); if (in1->Opcode() == Op_ConL) { // Match c1 - jlong c1 = phase->type(in1)->isa_long()->get_con(); + jlong c1 = phase->type(in1)->as_long()->get_con(); Node* sub2 = phase->longcon(java_subtract(c1, c0)); return new SubLNode(sub2, in21); } else { @@ -510,13 +510,13 @@ Node *SubLNode::Ideal(PhaseGVN *phase, bool can_reshape) { } // Convert "0L-(A>>63)" into "(A>>>63)" - if ( op2 == Op_RShiftL ) { - Node *in21 = in2->in(1); - Node *in22 = in2->in(2); - const TypeLong *zero = phase->type(in1)->isa_long(); - const TypeLong *t21 = phase->type(in21)->isa_long(); - const TypeInt *t22 = phase->type(in22)->isa_int(); - if ( t21 && t22 && zero == TypeLong::ZERO && t22->is_con(63) ) { + if (op2 == Op_RShiftL) { + Node* in21 = in2->in(1); + Node* in22 = in2->in(2); + const TypeLong* zero = phase->type(in1)->isa_long(); + bool in21_is_long = phase->type(in21)->is_long(); + const TypeInt* t22 = phase->type(in22)->isa_int(); + if (in21_is_long && t22 != nullptr && zero == TypeLong::ZERO && t22->is_con(63)) { return new URShiftLNode(in21, in22); } } @@ -527,8 +527,8 @@ Node *SubLNode::Ideal(PhaseGVN *phase, bool can_reshape) { //------------------------------sub-------------------------------------------- // A subtract node differences it's two inputs. const Type *SubLNode::sub( const Type *t1, const Type *t2 ) const { - const TypeLong *r0 = t1->is_long(); // Handy access - const TypeLong *r1 = t2->is_long(); + const TypeLong* r0 = t1->as_long(); // Handy access + const TypeLong* r1 = t2->as_long(); jlong lo = java_subtract(r0->_lo, r1->_hi); jlong hi = java_subtract(r0->_hi, r1->_lo); @@ -577,8 +577,8 @@ const Type* SubFPNode::Value(PhaseGVN* phase) const { const Type* SubHFNode::sub(const Type* t1, const Type* t2) const { // Half precision floating point subtraction follows the rules of IEEE 754 // applicable to other floating point types. - if (t1->isa_half_float_constant() != nullptr && - t2->isa_half_float_constant() != nullptr) { + if (t1->is_half_float_constant() && + t2->is_half_float_constant()) { return TypeH::make(t1->getf() - t2->getf()); } else { return Type::HALF_FLOAT; @@ -694,8 +694,8 @@ CmpNode *CmpNode::make(Node *in1, Node *in2, BasicType bt, bool unsigned_comp) { // Simplify a CmpI (compare 2 integers) node, based on local information. // If both inputs are constants, compare them. const Type *CmpINode::sub( const Type *t1, const Type *t2 ) const { - const TypeInt *r0 = t1->is_int(); // Handy access - const TypeInt *r1 = t2->is_int(); + const TypeInt* r0 = t1->as_int(); // Handy access + const TypeInt* r1 = t2->as_int(); if( r0->_hi < r1->_lo ) // Range is always low? return TypeInt::CC_LT; @@ -761,8 +761,8 @@ const Type* CmpINode::Value(PhaseGVN* phase) const { // Simplify a CmpU (compare 2 integers) node, based on local information. // If both inputs are constants, compare them. const Type* CmpUNode::sub(const Type* t1, const Type* t2) const { - const TypeInt* r0 = t1->is_int(); - const TypeInt* r1 = t2->is_int(); + const TypeInt* r0 = t1->as_int(); + const TypeInt* r1 = t2->as_int(); // Check for special case in Hashtable::get - the hash index is // mod'ed to the table size so the following range check is useless. @@ -805,7 +805,7 @@ const Type* CmpUNode::Value(PhaseGVN* phase) const { const Node* in2 = in(2); const Type* t1 = phase->type(in1); const Type* t2 = phase->type(in2); - assert(t1->isa_int(), "CmpU has only Int type inputs"); + assert(t1->is_int(), "CmpU has only Int type inputs"); if (t2 == TypeInt::INT) { // Compare to bottom? return bottom_type(); } @@ -832,8 +832,8 @@ const Type* CmpUNode::Value(PhaseGVN* phase) const { // Skip cases when input types are top or bottom. if ((t11 != Type::TOP) && (t11 != TypeInt::INT) && (t12 != Type::TOP) && (t12 != TypeInt::INT)) { - const TypeInt *ti11 = t11->is_int(); - const TypeInt *ti12 = t12->is_int(); + const TypeInt* ti11 = t11->as_int(); + const TypeInt* ti12 = t12->as_int(); jlong lo_ti11_range = ti11->_lo; jlong hi_ti11_range = ti11->_hi; jlong lo_ti12_range = ti12->_lo; @@ -860,8 +860,8 @@ const Type* CmpUNode::Value(PhaseGVN* phase) const { int w = MAX2(ti11->_widen, ti12->_widen); // _widen does not matter here const TypeInt* wrapped_range1 = TypeInt::make(min_jint, hi_wrapped_range, w); const TypeInt* wrapped_range2 = TypeInt::make(lo_wrapped_range, max_jint, w); - const TypeInt* cmp1 = sub(wrapped_range1, t2)->is_int(); - const TypeInt* cmp2 = sub(wrapped_range2, t2)->is_int(); + const TypeInt* cmp1 = sub(wrapped_range1, t2)->as_int(); + const TypeInt* cmp2 = sub(wrapped_range2, t2)->as_int(); // Compute union, so that cmp handles all possible results from the two cases const Type* t_cmp = cmp1->meet(cmp2); // Pick narrowest type, based on overflow computation and on immediate inputs @@ -942,8 +942,8 @@ Node* CmpLNode::Ideal(PhaseGVN* phase, bool can_reshape) { // Simplify a CmpL (compare 2 longs ) node, based on local information. // If both inputs are constants, compare them. const Type *CmpLNode::sub( const Type *t1, const Type *t2 ) const { - const TypeLong *r0 = t1->is_long(); // Handy access - const TypeLong *r1 = t2->is_long(); + const TypeLong* r0 = t1->as_long(); // Handy access + const TypeLong* r1 = t2->as_long(); if( r0->_hi < r1->_lo ) // Range is always low? return TypeInt::CC_LT; @@ -970,8 +970,8 @@ const Type *CmpLNode::sub( const Type *t1, const Type *t2 ) const { // Simplify a CmpUL (compare 2 unsigned longs) node, based on local information. // If both inputs are constants, compare them. const Type* CmpULNode::sub(const Type* t1, const Type* t2) const { - const TypeLong* r0 = t1->is_long(); - const TypeLong* r1 = t2->is_long(); + const TypeLong* r0 = t1->as_long(); + const TypeLong* r1 = t2->as_long(); if (r0->_uhi < r1->_ulo) { return TypeInt::CC_LT; @@ -1000,8 +1000,8 @@ const Type* CmpULNode::sub(const Type* t1, const Type* t2) const { // Simplify an CmpP (compare 2 pointers) node, based on local information. // If both inputs are constants, compare them. const Type *CmpPNode::sub( const Type *t1, const Type *t2 ) const { - const TypePtr *r0 = t1->is_ptr(); // Handy access - const TypePtr *r1 = t2->is_ptr(); + const TypePtr* r0 = t1->as_ptr(); // Handy access + const TypePtr* r1 = t2->as_ptr(); // Undefined inputs makes for an undefined result if (TypePtr::is_top(r0->_ptr) || TypePtr::is_top(r1->_ptr)) { @@ -1085,7 +1085,7 @@ static inline Node* isa_java_mirror_load(PhaseGVN* phase, Node* n, bool& might_b Node* adr = n->in(MemNode::Address); // First load from OopHandle: ((OopHandle)mirror)->resolve(); may need barrier. - if (adr->Opcode() != Op_LoadP || !phase->type(adr)->isa_rawptr()) return nullptr; + if (adr->Opcode() != Op_LoadP || !phase->type(adr)->is_rawptr()) return nullptr; adr = adr->in(MemNode::Address); intptr_t off = 0; @@ -1093,7 +1093,7 @@ static inline Node* isa_java_mirror_load(PhaseGVN* phase, Node* n, bool& might_b if (k == nullptr) return nullptr; const TypeKlassPtr* tkp = phase->type(k)->isa_klassptr(); if (!tkp || off != in_bytes(Klass::java_mirror_offset())) return nullptr; - might_be_an_array |= tkp->isa_aryklassptr() || tkp->is_instklassptr()->might_be_an_array(); + might_be_an_array |= tkp->is_aryklassptr() || tkp->as_instklassptr()->might_be_an_array(); // We've found the klass node of a Java mirror load. return k; @@ -1288,7 +1288,7 @@ Node* CmpPNode::Ideal(PhaseGVN *phase, bool can_reshape) { return nullptr; } else { // Special case for non-value arrays: They only have one (default) refined class, use it - set_req_X(2, phase->makecon(t2->is_aryklassptr()->cast_to_refined_array_klass_ptr()), phase); + set_req_X(2, phase->makecon(t2->as_aryklassptr()->cast_to_refined_array_klass_ptr()), phase); } } @@ -1301,9 +1301,9 @@ Node* CmpPNode::Ideal(PhaseGVN *phase, bool can_reshape) { const Type* CmpPNode::Value(PhaseGVN* phase) const { const Type* res = CmpNode::Value(phase); if (res == TypeInt::CC) { - const TypeOopPtr* p0 = phase->type(in(1))->isa_oopptr(); - const TypeOopPtr* p1 = phase->type(in(2))->isa_oopptr(); - if (p0 != nullptr && p1 != nullptr) { + bool in0_is_oopptr = phase->type(in(1))->is_oopptr(); + bool in1_is_oopptr = phase->type(in(2))->is_oopptr(); + if (in0_is_oopptr && in1_is_oopptr) { Node* in1 = in(1)->uncast(); Node* in2 = in(2)->uncast(); AllocateNode* alloc1 = AllocateNode::Ideal_allocation(in1); @@ -1407,7 +1407,7 @@ Node *CmpDNode::Ideal(PhaseGVN *phase, bool can_reshape){ if( ConvertCmpD2CmpF && in(idx_f2d)->Opcode() == Op_ConvF2D && in(idx_con)->Opcode() == Op_ConD ) { - const TypeD *t2 = in(idx_con)->bottom_type()->is_double_constant(); + const TypeD* t2 = in(idx_con)->bottom_type()->as_double_constant(); double t2_value_as_double = t2->_d; float t2_value_as_float = (float)t2_value_as_double; if( t2_value_as_double == (double)t2_value_as_float ) { @@ -1439,10 +1439,10 @@ const Type* FlatArrayCheckNode::Value(PhaseGVN* phase) const { if (t == Type::TOP) { return Type::TOP; } - if (t->is_ptr()->is_flat()) { + if (t->as_ptr()->is_flat()) { // One of the input arrays is flat, check always passes return TypeInt::CC_EQ; - } else if (!t->is_ptr()->is_not_flat()) { + } else if (!t->as_ptr()->is_not_flat()) { // One of the input arrays might be flat all_not_flat = false; } @@ -1460,7 +1460,7 @@ Node* FlatArrayCheckNode::Ideal(PhaseGVN* phase, bool can_reshape) { // Remove inputs that are known to be non-flat for (uint i = ArrayOrKlass; i < req(); ++i) { const Type* t = phase->type(in(i)); - if (t->isa_ptr() && t->is_ptr()->is_not_flat()) { + if (t->is_ptr() && t->as_ptr()->is_not_flat()) { del_req(i--); changed = true; } @@ -1474,7 +1474,7 @@ Node* FlatArrayCheckNode::Ideal(PhaseGVN* phase, bool can_reshape) { const Type *BoolTest::cc2logical( const Type *CC ) const { if( CC == Type::TOP ) return Type::TOP; if( CC->base() != Type::Int ) return TypeInt::BOOL; // Bottom or worse - const TypeInt *ti = CC->is_int(); + const TypeInt* ti = CC->as_int(); if( ti->is_con() ) { // Only 1 kind of condition codes set? // Match low order 2 bits int tmp = ((ti->get_con()&3) == (_test&3)) ? 1 : 0; @@ -1634,8 +1634,7 @@ Node* BoolNode::fold_cmpI(PhaseGVN* phase, SubNode* cmp, Node* cmp1, int cmp_op, static bool is_counted_loop_cmp(Node *cmp) { Node *n = cmp->in(1)->in(1); - return n != nullptr && - n->is_Phi() && + return Node::is(n) && n->in(0) != nullptr && n->in(0)->is_CountedLoop() && n->in(0)->as_CountedLoop()->phi() == n; @@ -1762,6 +1761,19 @@ Node *BoolNode::Ideal(PhaseGVN *phase, bool can_reshape) { } } + // Change x u< 1 or x u<= 0 to x == 0 + // and x u> 0 or u>= 1 to x != 0 + if ((cop == Op_CmpU || cop == Op_CmpUL) && cmp1_op != Op_LoadRange) { + const BasicType bt = cop == Op_CmpU ? T_INT : T_LONG; + const jlong limit = bt == T_INT ? cmp2->find_int_con(-1) : cmp2->find_long_con(-1); + if (((_test._test == BoolTest::lt || _test._test == BoolTest::ge) && limit == 1) || + ((_test._test == BoolTest::le || _test._test == BoolTest::gt) && limit == 0)) { + Node* zero = phase->integercon(0, bt); + Node* ncmp = phase->transform(CmpNode::make(cmp1, zero, bt)); + return new BoolNode(ncmp, _test.is_less() ? BoolTest::eq : BoolTest::ne); + } + } + // Change "bool eq/ne (cmp (xor X 1) 0)" into "bool ne/eq (cmp X 0)". // The XOR-1 is an idiom used to flip the sense of a bool. We flip the // test instead. @@ -1794,18 +1806,6 @@ Node *BoolNode::Ideal(PhaseGVN *phase, bool can_reshape) { } } - // Change x u< 1 or x u<= 0 to x == 0 - // and x u> 0 or u>= 1 to x != 0 - if (cop == Op_CmpU && - cmp1_op != Op_LoadRange && - (((_test._test == BoolTest::lt || _test._test == BoolTest::ge) && - cmp2->find_int_con(-1) == 1) || - ((_test._test == BoolTest::le || _test._test == BoolTest::gt) && - cmp2->find_int_con(-1) == 0))) { - Node* ncmp = phase->transform(new CmpINode(cmp1, phase->intcon(0))); - return new BoolNode(ncmp, _test.is_less() ? BoolTest::eq : BoolTest::ne); - } - // Change (arraylength <= 0) or (arraylength == 0) // into (arraylength u<= 0) // Also change (arraylength != 0) into (arraylength u> 0) @@ -1830,9 +1830,9 @@ Node *BoolNode::Ideal(PhaseGVN *phase, bool can_reshape) { cmp1_op == Op_Conv2B && (_test._test == BoolTest::eq || _test._test == BoolTest::ne) ) { - Node *ncmp = phase->transform(phase->type(c2b->in(1))->isa_int() - ? (Node*)new CmpINode(c2b->in(1),cmp2) - : (Node*)new CmpPNode(c2b->in(1),phase->makecon(TypePtr::NULL_PTR)) + Node* ncmp = phase->transform(phase->type(c2b->in(1))->is_int() + ? (Node*)new CmpINode(c2b->in(1), cmp2) + : (Node*)new CmpPNode(c2b->in(1), phase->makecon(TypePtr::NULL_PTR)) ); return new BoolNode( ncmp, _test._test ); } @@ -1853,12 +1853,12 @@ Node *BoolNode::Ideal(PhaseGVN *phase, bool can_reshape) { cop == Op_CmpI && cmp1_op == Op_AddI && cmp1->in(2) != nullptr && - phase->type(cmp1->in(2))->isa_int() && - phase->type(cmp1->in(2))->is_int()->is_con() && + phase->type(cmp1->in(2))->is_int() && + phase->type(cmp1->in(2))->as_int()->is_con() && cmp2_type == TypeInt::ZERO && !is_counted_loop_cmp(cmp) // modifying the exit test of a counted loop messes the counted loop shape ) { - const TypeInt* cmp1_in2 = phase->type(cmp1->in(2))->is_int(); + const TypeInt* cmp1_in2 = phase->type(cmp1->in(2))->as_int(); Node *ncmp = phase->transform( new CmpINode(cmp1->in(1),phase->intcon(-cmp1_in2->_hi))); return new BoolNode( ncmp, _test._test ); } @@ -2008,7 +2008,7 @@ Node *BoolNode::Ideal(PhaseGVN *phase, bool can_reshape) { // in BoolNode::Ideal since we create a new non-constant node (see [CMPU_MASK]). const Type* BoolNode::Value_cmpu_and_mask(PhaseValues* phase) const { Node* cmp = in(1); - if (cmp != nullptr && cmp->Opcode() == Op_CmpU) { + if (is_exact(cmp)) { Node* cmp1 = cmp->in(1); Node* cmp2 = cmp->in(2); @@ -2106,12 +2106,12 @@ const Type* AbsNode::Value(PhaseGVN* phase) const { switch (t1->base()) { case Type::Int: { - const TypeInt* ti = t1->is_int(); + const TypeInt* ti = t1->as_int(); return integral_abs_value(ti); } case Type::Long: { - const TypeLong* tl = t1->is_long(); + const TypeLong* tl = t1->as_long(); return integral_abs_value(tl); } @@ -2131,8 +2131,8 @@ Node* AbsNode::Identity(PhaseGVN* phase) { Node* in1 = in(1); // No need to do abs for non-negative values const Type* in_type = phase->type(in1); - if ((in_type->isa_int() && in_type->is_int()->_lo >= 0) || - (in_type->isa_long() && in_type->is_long()->_lo >= 0)) { + if ((in_type->is_int() && in_type->as_int()->_lo >= 0) || + (in_type->is_long() && in_type->as_long()->_lo >= 0)) { return in1; } // Convert "abs(abs(x))" into "abs(x)" @@ -2187,10 +2187,10 @@ static const Type* reverse_bytes(int opcode, const Type* con) { switch (opcode) { // It is valid in bytecode to load any int and pass it to a method that expects a smaller type (i.e., short, char). // Let's cast the value to match the Java behavior. - case Op_ReverseBytesS: return TypeInt::make(byteswap(static_cast(con->is_int()->get_con()))); - case Op_ReverseBytesUS: return TypeInt::make(byteswap(static_cast(con->is_int()->get_con()))); - case Op_ReverseBytesI: return TypeInt::make(byteswap(con->is_int()->get_con())); - case Op_ReverseBytesL: return TypeLong::make(byteswap(con->is_long()->get_con())); + case Op_ReverseBytesS: return TypeInt::make(byteswap(static_cast(con->as_int()->get_con()))); + case Op_ReverseBytesUS: return TypeInt::make(byteswap(static_cast(con->as_int()->get_con()))); + case Op_ReverseBytesI: return TypeInt::make(byteswap(con->as_int()->get_con())); + case Op_ReverseBytesL: return TypeLong::make(byteswap(con->as_long()->get_con())); default: ShouldNotReachHere(); } } @@ -2239,7 +2239,7 @@ static Node* simplify_involution(PhaseGVN* phase, Node* involution) { // Operations on sub-int types might not be "real" involutions for values outside their type range, // for example, a ReverseBytesS node with an input larger than short. // Make sure not to drop potential truncations. - if (type == nullptr || involution->bottom_type()->is_int()->contains(type)) { + if (type == nullptr || involution->bottom_type()->as_int()->contains(type)) { return original; } } diff --git a/src/hotspot/share/opto/subtypenode.cpp b/src/hotspot/share/opto/subtypenode.cpp index 7adefe138e13..b6f65b4d6913 100644 --- a/src/hotspot/share/opto/subtypenode.cpp +++ b/src/hotspot/share/opto/subtypenode.cpp @@ -33,12 +33,12 @@ #include "opto/subtypenode.hpp" const Type* SubTypeCheckNode::sub(const Type* sub_t, const Type* super_t) const { - const TypeKlassPtr* super_klass_type = super_t->isa_klassptr(); + const TypeKlassPtr* super_klass_type = super_t->as_klassptr(); assert(sub_t != Type::TOP && !TypePtr::NULL_PTR->higher_equal(sub_t), "should be not null"); - const TypeKlassPtr* sub_klass_type = sub_t->isa_klassptr() ? sub_t->is_klassptr() : sub_t->is_oopptr()->as_klass_type(); + const TypeKlassPtr* sub_klass_type = sub_t->is_klassptr() ? sub_t->as_klassptr() : sub_t->as_oopptr()->as_klass_type(); // Oop can't be a subtype of abstract type that has no subclass. - if (sub_t->isa_oopptr() && super_klass_type->isa_instklassptr() && super_klass_type->klass_is_exact()) { + if (sub_t->is_oopptr() && super_klass_type->is_instklassptr() && super_klass_type->klass_is_exact()) { ciKlass* superklass = super_klass_type->exact_klass(); if (!superklass->is_interface() && superklass->is_abstract() && !superklass->as_instance_klass()->has_subklass()) { @@ -62,7 +62,7 @@ const Type* SubTypeCheckNode::sub(const Type* sub_t, const Type* super_t) const // array property for the super klass (all done in cast_to_exactness()) in order to check whether the sub klass is // flat in array and the super klass is not flat in array. If that's the case, the classes must be unrelated. const TypeKlassPtr* super_klass_type_for_flat_in_array = super_klass_type; - if (super_klass_type->isa_instklassptr()) { + if (super_klass_type->is_instklassptr()) { // Only relevant for TypeInstKlassPtr. TypeAryKlassPtr will always be not flat in array. super_klass_type_for_flat_in_array = super_klass_type->cast_to_exactness(false); } @@ -79,7 +79,7 @@ const Type* SubTypeCheckNode::sub(const Type* sub_t, const Type* super_t) const unrelated_classes = true; } if (unrelated_classes) { - TypePtr::PTR jp = sub_t->is_ptr()->join_ptr(super_t->is_ptr()->_ptr); + TypePtr::PTR jp = sub_t->as_ptr()->join_ptr(super_t->as_ptr()->_ptr); if (jp != TypePtr::Null && jp != TypePtr::BotPTR) { return TypeInt::CC_GT; } @@ -112,15 +112,14 @@ Node *SubTypeCheckNode::Ideal(PhaseGVN* phase, bool can_reshape) { const Type* sub_t = phase->type(obj_or_subklass); const Type* super_t = phase->type(superklass); - if (!super_t->isa_klassptr() || - (!sub_t->isa_klassptr() && !sub_t->isa_oopptr())) { + if (!super_t->is_klassptr() || + (!sub_t->is_klassptr() && !sub_t->is_oopptr())) { return nullptr; } Node* addr = nullptr; if (obj_or_subklass->is_DecodeNKlass()) { - if (obj_or_subklass->in(1) != nullptr && - obj_or_subklass->in(1)->Opcode() == Op_LoadNKlass) { + if (is_exact(obj_or_subklass->in(1))) { addr = obj_or_subklass->in(1)->in(MemNode::Address); } } else if (obj_or_subklass->Opcode() == Op_LoadKlass) { @@ -154,13 +153,13 @@ Node *SubTypeCheckNode::Ideal(PhaseGVN* phase, bool can_reshape) { #ifdef ASSERT bool SubTypeCheckNode::is_oop(PhaseGVN* phase, Node* n) { - const Type* t = phase->type(n); - if (!t->isa_oopptr() && t != Type::TOP) { - n->dump(); - t->dump(); tty->cr(); - return false; - } - return true; + const Type* t = phase->type(n); + if (!t->is_oopptr() && t != Type::TOP) { + n->dump(); + t->dump(); tty->cr(); + return false; + } + return true; } static Node* record_for_cleanup(Node* n, PhaseGVN* phase) { @@ -202,8 +201,8 @@ bool SubTypeCheckNode::verify(PhaseGVN* phase) { const Type* sub_t = phase->type(obj_or_subklass); const Type* super_t = phase->type(superklass); - const TypeKlassPtr* superk = super_t->isa_klassptr(); - const TypeKlassPtr* subk = sub_t->isa_klassptr() ? sub_t->is_klassptr() : sub_t->is_oopptr()->as_klass_type(); + const TypeKlassPtr* superk = super_t->as_klassptr(); + const TypeKlassPtr* subk = sub_t->is_klassptr() ? sub_t->as_klassptr() : sub_t->as_oopptr()->as_klass_type(); if (super_t->singleton() && subk != nullptr) { if (obj_or_subklass->bottom_type() == Type::TOP) { @@ -222,7 +221,7 @@ bool SubTypeCheckNode::verify(PhaseGVN* phase) { } case Compile::SSC_full_test: { Node* p1 = phase->transform(AddPNode::make_off_heap(superklass, phase->MakeConX(in_bytes(Klass::super_check_offset_offset())))); - Node* chk_off = phase->transform(new LoadINode(nullptr, C->immutable_memory(), p1, phase->type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered)); + Node* chk_off = phase->transform(new LoadINode(nullptr, C->immutable_memory(), p1, phase->type(p1)->as_ptr(), TypeInt::INT, MemNode::unordered)); record_for_cleanup(chk_off, phase); int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset()); @@ -234,7 +233,7 @@ bool SubTypeCheckNode::verify(PhaseGVN* phase) { chk_off_X = phase->transform(new ConvI2LNode(chk_off_X)); #endif Node* p2 = phase->transform(AddPNode::make_off_heap(subklass, chk_off_X)); - Node* nkls = phase->transform(LoadKlassNode::make(*phase, C->immutable_memory(), p2, phase->type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL)); + Node* nkls = phase->transform(LoadKlassNode::make(*phase, C->immutable_memory(), p2, phase->type(p2)->as_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL)); return verify_helper(phase, nkls, cached_t); } @@ -255,7 +254,7 @@ Node* SubTypeCheckNode::load_klass(PhaseGVN* phase) const { Node* obj_or_subklass = in(ObjOrSubKlass); const Type* sub_t = phase->type(obj_or_subklass); Node* subklass = nullptr; - if (sub_t->isa_oopptr()) { + if (sub_t->is_oopptr()) { Node* adr = phase->transform(AddPNode::make_with_base(obj_or_subklass, phase->MakeConX(oopDesc::klass_offset_in_bytes()))); subklass = phase->transform(LoadKlassNode::make(*phase, phase->C->immutable_memory(), adr, TypeInstPtr::KLASS)); record_for_cleanup(subklass, phase); diff --git a/src/hotspot/share/opto/superword.cpp b/src/hotspot/share/opto/superword.cpp index 3cd36fcb1faf..9611b76f27dd 100644 --- a/src/hotspot/share/opto/superword.cpp +++ b/src/hotspot/share/opto/superword.cpp @@ -2207,9 +2207,8 @@ bool SuperWord::is_vector_use(Node* use, int u_idx) const { // in use pack have inputs of iv plus node index. Node* use_in = u_pk->at(i)->in(u_idx); if (!use_in->is_Add() || use_in->in(1) != n) return false; - const TypeInt* offset_t = use_in->in(2)->bottom_type()->is_int(); - if (offset_t == nullptr || !offset_t->is_con() || - offset_t->get_con() != (jint) i) return false; + const TypeInt* offset_t = use_in->in(2)->bottom_type()->as_int(); + if (!offset_t->is_con() || offset_t->get_con() != (jint) i) return false; } } else { // check for scalar promotion @@ -2493,7 +2492,7 @@ static bool can_subword_truncate(Node* in, const Type* type) { } // Vector nodes should not truncate. - if (type->isa_vect() != nullptr || type->isa_pvectmask() != nullptr || in->is_Reduction()) { + if (type->is_vect() || type->is_pvectmask() || in->is_Reduction()) { return false; } @@ -3052,7 +3051,7 @@ void VTransform::adjust_pre_loop_limit_to_align_main_loop_vectors() { Node* invar_variable = s.variable(); jint invar_scale = s.scale().value(); TRACE_ALIGN_VECTOR_NODE(invar_variable); - if (igvn().type(invar_variable)->isa_long()) { + if (igvn().type(invar_variable)->is_long()) { // Computations are done % (vector width/element size) so it's // safe to simply convert invar to an int and loose the upper 32 // bit half. @@ -3088,13 +3087,13 @@ void VTransform::adjust_pre_loop_limit_to_align_main_loop_vectors() { // bit half. The base could be ptr, long or int. We cast all // to int. Node* xbase = base; - if (igvn().type(xbase)->isa_ptr()) { + if (igvn().type(xbase)->is_ptr()) { // ptr -> int/long xbase = new CastP2XNode(nullptr, xbase); phase()->register_new_node(xbase, pre_ctrl); TRACE_ALIGN_VECTOR_NODE(xbase); } - if (igvn().type(xbase)->isa_long()) { + if (igvn().type(xbase)->is_long()) { // long -> int xbase = new ConvL2INode(xbase); phase()->register_new_node(xbase, pre_ctrl); diff --git a/src/hotspot/share/opto/superwordVTransformBuilder.cpp b/src/hotspot/share/opto/superwordVTransformBuilder.cpp index 4b185c0eb493..5afedbc76b13 100644 --- a/src/hotspot/share/opto/superwordVTransformBuilder.cpp +++ b/src/hotspot/share/opto/superwordVTransformBuilder.cpp @@ -322,7 +322,7 @@ VTransformNode* SuperWordVTransformBuilder::get_or_make_vtnode_vector_input_at_i BasicType element_bt = p0->is_Convert() ? p0->in(1)->bottom_type()->basic_type() : _vloop_analyzer.types().velt_basic_type(p0); if (index == 2 && VectorNode::is_scalar_rotate(p0) && element_bt == T_LONG) { // Scalar rotate has int rotation value, but the scalar rotate expects longs. - assert(same_input->bottom_type()->isa_int(), "scalar rotate expects int rotation"); + assert(same_input->bottom_type()->is_int(), "scalar rotate expects int rotation"); VTransformNode* conv = new (_vtransform.arena()) VTransformConvI2LNode(_vtransform); conv->init_req(1, same_input_vtn); same_input_vtn = conv; diff --git a/src/hotspot/share/opto/type.cpp b/src/hotspot/share/opto/type.cpp index 7fae3e0b6f1b..0068dc6f6235 100644 --- a/src/hotspot/share/opto/type.cpp +++ b/src/hotspot/share/opto/type.cpp @@ -115,66 +115,66 @@ void Type::Offset::dump2(outputStream *st) const { // Array which maps compiler types to Basic Types const Type::TypeInfo Type::_type_info[Type::lastype] = { - { T_ILLEGAL, "bad", false, Node::NotAMachineReg}, // Bad - { T_ILLEGAL, "control", false, 0 }, // Control - { T_VOID, "top", false, 0 }, // Top - { T_INT, "int:", false, Op_RegI }, // Int - { T_LONG, "long:", false, Op_RegL }, // Long - { T_VOID, "half", false, 0 }, // Half - { T_NARROWOOP, "narrowoop:", false, Op_RegN }, // NarrowOop - { T_NARROWKLASS,"narrowklass:", false, Op_RegN }, // NarrowKlass - { T_ILLEGAL, "tuple:", false, Node::NotAMachineReg}, // Tuple - { T_ARRAY, "array:", false, Node::NotAMachineReg}, // Array - { T_ARRAY, "interfaces:", false, Node::NotAMachineReg}, // Interfaces + { T_ILLEGAL, "bad", Node::NotAMachineReg}, // Bad + { T_ILLEGAL, "control", 0 }, // Control + { T_VOID, "top", 0 }, // Top + { T_INT, "int:", Op_RegI }, // Int + { T_LONG, "long:", Op_RegL }, // Long + { T_VOID, "half", 0 }, // Half + { T_NARROWOOP, "narrowoop:", Op_RegN }, // NarrowOop + { T_NARROWKLASS,"narrowklass:", Op_RegN }, // NarrowKlass + { T_ILLEGAL, "tuple:", Node::NotAMachineReg}, // Tuple + { T_ARRAY, "array:", Node::NotAMachineReg}, // Array + { T_ARRAY, "interfaces:", Node::NotAMachineReg}, // Interfaces #if defined(PPC64) - { T_ILLEGAL, "vectormask:", false, Op_RegVectMask }, // VectorMask. - { T_ILLEGAL, "vectora:", false, Op_VecA }, // VectorA. - { T_ILLEGAL, "vectors:", false, 0 }, // VectorS - { T_ILLEGAL, "vectord:", false, Op_RegL }, // VectorD - { T_ILLEGAL, "vectorx:", false, Op_VecX }, // VectorX - { T_ILLEGAL, "vectory:", false, 0 }, // VectorY - { T_ILLEGAL, "vectorz:", false, 0 }, // VectorZ + { T_ILLEGAL, "vectormask:", Op_RegVectMask }, // VectorMask. + { T_ILLEGAL, "vectora:", Op_VecA }, // VectorA. + { T_ILLEGAL, "vectors:", 0 }, // VectorS + { T_ILLEGAL, "vectord:", Op_RegL }, // VectorD + { T_ILLEGAL, "vectorx:", Op_VecX }, // VectorX + { T_ILLEGAL, "vectory:", 0 }, // VectorY + { T_ILLEGAL, "vectorz:", 0 }, // VectorZ #elif defined(S390) - { T_ILLEGAL, "vectormask:", false, Op_RegVectMask }, // VectorMask. - { T_ILLEGAL, "vectora:", false, Op_VecA }, // VectorA. - { T_ILLEGAL, "vectors:", false, 0 }, // VectorS - { T_ILLEGAL, "vectord:", false, Op_RegL }, // VectorD - { T_ILLEGAL, "vectorx:", false, Op_VecX }, // VectorX - { T_ILLEGAL, "vectory:", false, 0 }, // VectorY - { T_ILLEGAL, "vectorz:", false, 0 }, // VectorZ + { T_ILLEGAL, "vectormask:", Op_RegVectMask }, // VectorMask. + { T_ILLEGAL, "vectora:", Op_VecA }, // VectorA. + { T_ILLEGAL, "vectors:", 0 }, // VectorS + { T_ILLEGAL, "vectord:", Op_RegL }, // VectorD + { T_ILLEGAL, "vectorx:", Op_VecX }, // VectorX + { T_ILLEGAL, "vectory:", 0 }, // VectorY + { T_ILLEGAL, "vectorz:", 0 }, // VectorZ #else // all other - { T_ILLEGAL, "vectormask:", false, Op_RegVectMask }, // VectorMask. - { T_ILLEGAL, "vectora:", false, Op_VecA }, // VectorA. - { T_ILLEGAL, "vectors:", false, Op_VecS }, // VectorS - { T_ILLEGAL, "vectord:", false, Op_VecD }, // VectorD - { T_ILLEGAL, "vectorx:", false, Op_VecX }, // VectorX - { T_ILLEGAL, "vectory:", false, Op_VecY }, // VectorY - { T_ILLEGAL, "vectorz:", false, Op_VecZ }, // VectorZ + { T_ILLEGAL, "vectormask:", Op_RegVectMask }, // VectorMask. + { T_ILLEGAL, "vectora:", Op_VecA }, // VectorA. + { T_ILLEGAL, "vectors:", Op_VecS }, // VectorS + { T_ILLEGAL, "vectord:", Op_VecD }, // VectorD + { T_ILLEGAL, "vectorx:", Op_VecX }, // VectorX + { T_ILLEGAL, "vectory:", Op_VecY }, // VectorY + { T_ILLEGAL, "vectorz:", Op_VecZ }, // VectorZ #endif - { T_ADDRESS, "anyptr:", false, Op_RegP }, // AnyPtr - { T_ADDRESS, "rawptr:", false, Op_RegP }, // RawPtr - { T_OBJECT, "oop:", true, Op_RegP }, // OopPtr - { T_OBJECT, "inst:", true, Op_RegP }, // InstPtr - { T_OBJECT, "ary:", true, Op_RegP }, // AryPtr - { T_METADATA, "metadata:", false, Op_RegP }, // MetadataPtr - { T_METADATA, "klass:", false, Op_RegP }, // KlassPtr - { T_METADATA, "instklass:", false, Op_RegP }, // InstKlassPtr - { T_METADATA, "aryklass:", false, Op_RegP }, // AryKlassPtr - { T_OBJECT, "func", false, 0 }, // Function - { T_ILLEGAL, "abIO", false, 0 }, // Abio - { T_ADDRESS, "return_address",false, Op_RegP }, // Return_Address - { T_ILLEGAL, "memory", false, 0 }, // Memory - { T_SHORT, "halffloat_top", false, Op_RegF }, // HalfFloatTop - { T_SHORT, "hfcon:", false, Op_RegF }, // HalfFloatCon - { T_SHORT, "short", false, Op_RegF }, // HalfFloatBot - { T_FLOAT, "float_top", false, Op_RegF }, // FloatTop - { T_FLOAT, "ftcon:", false, Op_RegF }, // FloatCon - { T_FLOAT, "float", false, Op_RegF }, // FloatBot - { T_DOUBLE, "double_top", false, Op_RegD }, // DoubleTop - { T_DOUBLE, "dblcon:", false, Op_RegD }, // DoubleCon - { T_DOUBLE, "double", false, Op_RegD }, // DoubleBot - { T_ILLEGAL, "bottom", false, 0 } // Bottom + { T_ADDRESS, "anyptr:", Op_RegP }, // AnyPtr + { T_ADDRESS, "rawptr:", Op_RegP }, // RawPtr + { T_OBJECT, "oop:", Op_RegP }, // OopPtr + { T_OBJECT, "inst:", Op_RegP }, // InstPtr + { T_OBJECT, "ary:", Op_RegP }, // AryPtr + { T_METADATA, "metadata:", Op_RegP }, // MetadataPtr + { T_METADATA, "klass:", Op_RegP }, // KlassPtr + { T_METADATA, "instklass:", Op_RegP }, // InstKlassPtr + { T_METADATA, "aryklass:", Op_RegP }, // AryKlassPtr + { T_OBJECT, "func", 0 }, // Function + { T_ILLEGAL, "abIO", 0 }, // Abio + { T_ADDRESS, "return_address",Op_RegP }, // Return_Address + { T_ILLEGAL, "memory", 0 }, // Memory + { T_SHORT, "halffloat_top", Op_RegF }, // HalfFloatTop + { T_SHORT, "hfcon:", Op_RegF }, // HalfFloatCon + { T_SHORT, "short", Op_RegF }, // HalfFloatBot + { T_FLOAT, "float_top", Op_RegF }, // FloatTop + { T_FLOAT, "ftcon:", Op_RegF }, // FloatCon + { T_FLOAT, "float", Op_RegF }, // FloatBot + { T_DOUBLE, "double_top", Op_RegD }, // DoubleTop + { T_DOUBLE, "dblcon:", Op_RegD }, // DoubleCon + { T_DOUBLE, "double", Op_RegD }, // DoubleBot + { T_ILLEGAL, "bottom", 0 } // Bottom }; // Map ideal registers (machine types) to ideal types @@ -303,12 +303,12 @@ const Type* Type::make_from_constant(ciConstant constant, bool require_constant, guarantee(require_constant || oop_constant->should_be_constant(), "con_type must get computed"); con_type = TypeOopPtr::make_from_constant(oop_constant, require_constant); if (Compile::current()->eliminate_boxing() && is_autobox_cache) { - con_type = con_type->is_aryptr()->cast_to_autobox_cache(); + con_type = con_type->as_aryptr()->cast_to_autobox_cache(); } if (stable_dimension > 0) { assert(FoldStableValues, "sanity"); assert(!con_type->is_zero_type(), "default value for stable field"); - con_type = con_type->is_aryptr()->cast_to_stable(true, stable_dimension); + con_type = con_type->as_aryptr()->cast_to_stable(true, stable_dimension); } } if (is_narrow_oop) { @@ -555,14 +555,14 @@ void Type::Initialize_shared(Compile* current) { TypeInt::CC_LT = TypeInt::make(-1,-1, WidenMin); // == TypeInt::MINUS_1 TypeInt::CC_GT = TypeInt::make( 1, 1, WidenMin); // == TypeInt::ONE TypeInt::CC_EQ = TypeInt::make( 0, 0, WidenMin); // == TypeInt::ZERO - TypeInt::CC_NE = TypeInt::make_or_top(TypeIntPrototype{{-1, 1}, {1, max_juint}, {0, 1}}, WidenMin)->is_int(); + TypeInt::CC_NE = TypeInt::make_or_top(TypeIntPrototype{{-1, 1}, {1, max_juint}, {0, 1}}, WidenMin)->as_int(); TypeInt::CC_LE = TypeInt::make(-1, 0, WidenMin); TypeInt::CC_GE = TypeInt::make( 0, 1, WidenMin); // == TypeInt::BOOL TypeInt::BYTE = TypeInt::make(-128, 127, WidenMin); // Bytes TypeInt::UBYTE = TypeInt::make(0, 255, WidenMin); // Unsigned Bytes TypeInt::CHAR = TypeInt::make(0, 65535, WidenMin); // Java chars TypeInt::SHORT = TypeInt::make(-32768, 32767, WidenMin); // Java shorts - TypeInt::NON_ZERO = TypeInt::make_or_top(TypeIntPrototype{{min_jint, max_jint}, {1, max_juint}, {0, 0}}, WidenMin)->is_int(); + TypeInt::NON_ZERO = TypeInt::make_or_top(TypeIntPrototype{{min_jint, max_jint}, {1, max_juint}, {0, 0}}, WidenMin)->as_int(); TypeInt::POS = TypeInt::make(0, max_jint, WidenMin); // Non-neg values TypeInt::POS1 = TypeInt::make(1, max_jint, WidenMin); // Positive values TypeInt::INT = TypeInt::make(min_jint, max_jint, WidenMax); // 32-bit integers @@ -581,7 +581,7 @@ void Type::Initialize_shared(Compile* current) { TypeLong::MINUS_1 = TypeLong::make(-1); // -1 TypeLong::ZERO = TypeLong::make( 0); // 0 TypeLong::ONE = TypeLong::make( 1); // 1 - TypeLong::NON_ZERO = TypeLong::make_or_top(TypeIntPrototype{{min_jlong, max_jlong}, {1, max_julong}, {0, 0}}, WidenMin)->is_long(); + TypeLong::NON_ZERO = TypeLong::make_or_top(TypeIntPrototype{{min_jlong, max_jlong}, {1, max_julong}, {0, 0}}, WidenMin)->as_long(); TypeLong::POS = TypeLong::make(0, max_jlong, WidenMin); // Non-neg values TypeLong::LONG = TypeLong::make(min_jlong, max_jlong, WidenMax); // 64-bit integers TypeLong::INT = TypeLong::make((jlong)min_jint, (jlong)max_jint,WidenMin); @@ -1130,11 +1130,11 @@ void Type::check_fundamental_laws(const Type* t1, const Type* t2, VerifyMeetJoin template const Type* Type::meet_join_helper(F op, const Type* t1, const Type* t2, bool include_speculative) { - if (t1->isa_narrowoop() && t2->isa_narrowoop()) { + if (t1->is_narrowoop() && t2->is_narrowoop()) { const Type* result = meet_join_helper(op, t1->make_ptr(), t2->make_ptr(), include_speculative); return result->make_narrowoop(); } - if (t1->isa_narrowklass() && t2->isa_narrowklass()) { + if (t1->is_narrowklass() && t2->is_narrowklass()) { const Type* result = meet_join_helper(op, t1->make_ptr(), t2->make_ptr(), include_speculative); return result->make_narrowklass(); } @@ -1333,7 +1333,7 @@ bool Type::has_memory() const { Type::TYPES tx = base(); if (tx == Memory) return true; if (tx == Tuple) { - const TypeTuple *t = is_tuple(); + const TypeTuple* t = as_tuple(); for (uint i=0; i < t->cnt(); i++) { tx = t->field_at(i)->base(); if (tx == Memory) return true; @@ -1463,7 +1463,7 @@ Type::Category Type::category() const { // Recursive case. Return CatMixed if the tuple contains types of // different categories (e.g. CallStaticJavaNode's type), or the specific // category if all types are of the same category (e.g. IfNode's type). - tuple = is_tuple(); + tuple = as_tuple(); if (tuple->cnt() == 0) { return Category::Undef; } else { @@ -1486,7 +1486,7 @@ bool Type::has_category(Type::Category cat) const { return true; } if (category() == Category::Mixed) { - const TypeTuple* tuple = is_tuple(); + const TypeTuple* tuple = as_tuple(); for (uint i = 0; i < tuple->cnt(); i++) { if (tuple->field_at(i)->has_category(cat)) { return true; @@ -1528,27 +1528,27 @@ void Type::verify_meet_join() { case DoubleBot: case DoubleCon: case DoubleTop: - return t2->isa_double() != nullptr; + return t2->is_double(); case FloatBot: case FloatCon: case FloatTop: - return t2->isa_float() != nullptr; + return t2->is_float(); case HalfFloatBot: case HalfFloatCon: case HalfFloatTop: - return t2->isa_half_float() != nullptr; + return t2->is_half_float(); case AnyPtr: - return t2->isa_ptr() != nullptr; + return t2->is_ptr(); case OopPtr: case InstPtr: - return t2->isa_oopptr() != nullptr; + return t2->is_oopptr(); case AryPtr: // When UseCompressedOops is false, not all AryPtr instances agree on whether their elems // are compressed (e.g. TypeAryPtr::NARROWOOPS and TypeAryPtr::OOPS) - return t2->isa_oopptr() != nullptr && UseCompressedOops; + return t2->is_oopptr() && UseCompressedOops; case InstKlassPtr: case AryKlassPtr: - return t2->isa_klassptr() != nullptr; + return t2->is_klassptr(); case VectorA: case VectorS: case VectorD: @@ -1697,7 +1697,7 @@ const Type* TypeH::xmeet(const Type* t) const { case HalfFloatTop: return this; case HalfFloatCon: - assert(_f != t->is_half_float_constant()->_f, "Equivalent instances should not appear here"); + assert(_f != t->as_half_float_constant()->_f, "Equivalent instances should not appear here"); return Type::HALF_FLOAT; case HalfFloatBot: return t; @@ -1712,7 +1712,7 @@ const Type* TypeH::xjoin(const Type* t) const { case HalfFloatTop: return t; case HalfFloatCon: - assert(_f != t->is_half_float_constant()->_f, "Equivalent instances should not appear here"); + assert(_f != t->as_half_float_constant()->_f, "Equivalent instances should not appear here"); return Type::make(HalfFloatTop); case HalfFloatBot: return this; @@ -1880,10 +1880,10 @@ const TypeInteger* TypeInteger::make(jlong con, BasicType bt) { jlong TypeInteger::get_con_as_long(BasicType bt) const { if (bt == T_INT) { - return is_int()->get_con(); + return as_int()->get_con(); } assert(bt == T_LONG, "basic type not an int or long"); - return is_long()->get_con(); + return as_long()->get_con(); } const TypeInteger* TypeInteger::bottom(BasicType bt) { @@ -1953,18 +1953,18 @@ TypeInt::TypeInt(const TypeIntPrototype& t, int widen) const TypeInt* TypeInt::make(jint con) { juint ucon = con; return (new TypeInt(TypeIntPrototype{{con, con}, {ucon, ucon}, {~ucon, ucon}}, - WidenMin))->hashcons()->is_int(); + WidenMin))->hashcons()->as_int(); } const TypeInt* TypeInt::make(jint lo, jint hi, int widen) { assert(lo <= hi, "must be legal bounds"); - return make_or_top(TypeIntPrototype{{lo, hi}, {0, max_juint}, {0, 0}}, widen)->is_int(); + return make_or_top(TypeIntPrototype{{lo, hi}, {0, max_juint}, {0, 0}}, widen)->as_int(); } const TypeInt* TypeInt::make_unsigned(juint ulo, juint uhi, int widen) { assert(ulo <= uhi, "must be legal bounds"); // By creating the TypeInt with the full signed range and the given unsigned range, the signed bounds are inferred from the unsigned bounds. - return make_or_top(TypeIntPrototype{{min_jint, max_jint}, {ulo, uhi}, {0, 0}}, widen)->is_int(); + return make_or_top(TypeIntPrototype{{min_jint, max_jint}, {ulo, uhi}, {0, 0}}, widen)->as_int(); } const Type* TypeInt::make_or_top(const TypeIntPrototype& t, int widen) { @@ -1972,7 +1972,7 @@ const Type* TypeInt::make_or_top(const TypeIntPrototype& t, int wid if (canonicalized_t.empty()) { return Type::TOP; } - return (new TypeInt(canonicalized_t._data, widen))->hashcons()->is_int(); + return (new TypeInt(canonicalized_t._data, widen))->hashcons()->as_int(); } bool TypeInt::contains(jint i) const { @@ -1996,14 +1996,14 @@ const Type* TypeInt::xmeet(const Type* t) const { if (base() != Int || t->base() != Int) { typerr(t); } - return TypeIntHelper::int_type_xmeet(this, t->is_int()); + return TypeIntHelper::int_type_xmeet(this, t->as_int()); } const Type* TypeInt::xjoin(const Type* t) const { if (base() != Int || t->base() != Int) { typerr(t); } - return TypeIntHelper::int_type_xjoin(this, t->is_int()); + return TypeIntHelper::int_type_xjoin(this, t->as_int()); } const Type* TypeInt::widen(const Type* old, const Type* limit) const { @@ -2036,7 +2036,7 @@ const Type* TypeInt::filter_helper(const Type* kills, bool include_speculative) //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeInt::eq(const Type* t) const { - const TypeInt* r = t->is_int(); + const TypeInt* r = t->as_int(); return TypeIntHelper::int_type_is_equal(this, r) && _widen == r->_widen; } @@ -2086,18 +2086,18 @@ TypeLong::TypeLong(const TypeIntPrototype& t, int widen) const TypeLong* TypeLong::make(jlong con) { julong ucon = con; return (new TypeLong(TypeIntPrototype{{con, con}, {ucon, ucon}, {~ucon, ucon}}, - WidenMin))->hashcons()->is_long(); + WidenMin))->hashcons()->as_long(); } const TypeLong* TypeLong::make(jlong lo, jlong hi, int widen) { assert(lo <= hi, "must be legal bounds"); - return make_or_top(TypeIntPrototype{{lo, hi}, {0, max_julong}, {0, 0}}, widen)->is_long(); + return make_or_top(TypeIntPrototype{{lo, hi}, {0, max_julong}, {0, 0}}, widen)->as_long(); } const TypeLong* TypeLong::make_unsigned(julong ulo, julong uhi, int widen) { assert(ulo <= uhi, "must be legal bounds"); // By creating the TypeLong with the full signed range and the given unsigned range, the signed bounds are inferred from the unsigned bounds. - return make_or_top(TypeIntPrototype{{min_jlong, max_jlong}, {ulo, uhi}, {0, 0}}, widen)->is_long(); + return make_or_top(TypeIntPrototype{{min_jlong, max_jlong}, {ulo, uhi}, {0, 0}}, widen)->as_long(); } const Type* TypeLong::make_or_top(const TypeIntPrototype& t, int widen) { @@ -2105,7 +2105,7 @@ const Type* TypeLong::make_or_top(const TypeIntPrototype& t, int if (canonicalized_t.empty()) { return Type::TOP; } - return (new TypeLong(canonicalized_t._data, widen))->hashcons()->is_long(); + return (new TypeLong(canonicalized_t._data, widen))->hashcons()->as_long(); } bool TypeLong::contains(jlong i) const { @@ -2129,14 +2129,14 @@ const Type* TypeLong::xmeet(const Type* t) const { if (base() != Long || t->base() != Long) { typerr(t); } - return TypeIntHelper::int_type_xmeet(this, t->is_long()); + return TypeIntHelper::int_type_xmeet(this, t->as_long()); } const Type* TypeLong::xjoin(const Type* t) const { if (base() != Long || t->base() != Long) { typerr(t); } - return TypeIntHelper::int_type_xjoin(this, t->is_long()); + return TypeIntHelper::int_type_xjoin(this, t->as_long()); } const Type* TypeLong::widen(const Type* old, const Type* limit) const { @@ -2169,7 +2169,7 @@ const Type* TypeLong::filter_helper(const Type* kills, bool include_speculative) //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeLong::eq(const Type* t) const { - const TypeLong* r = t->is_long(); + const TypeLong* r = t->as_long(); return TypeIntHelper::int_type_is_equal(this, r) && _widen == r->_widen; } @@ -2397,7 +2397,7 @@ const Type **TypeTuple::fields( uint arg_cnt ) { //------------------------------meet------------------------------------------- // Compute the MEET of two types. It returns a new Type object. const Type* TypeTuple::xmeet(const Type* t) const { - const TypeTuple* x = t->is_tuple(); + const TypeTuple* x = t->as_tuple(); assert(_cnt == x->_cnt, "mismatched shape: %d != %d", _cnt, x->_cnt); const Type** fields = static_cast(Compile::current()->type_arena()->AmallocWords(_cnt * sizeof(Type*))); for (uint i = 0; i < _cnt; i++) { @@ -2407,7 +2407,7 @@ const Type* TypeTuple::xmeet(const Type* t) const { } const Type* TypeTuple::xjoin(const Type* t) const { - const TypeTuple* x = t->is_tuple(); + const TypeTuple* x = t->as_tuple(); assert(_cnt == x->_cnt, "mismatched shape: %d != %d", _cnt, x->_cnt); const Type** fields = static_cast(Compile::current()->type_arena()->AmallocWords(_cnt * sizeof(Type*))); for (uint i = 0; i < _cnt; i++) { @@ -2492,7 +2492,7 @@ inline const TypeInt* normalize_array_size(const TypeInt* size) { //------------------------------make------------------------------------------- const TypeAry* TypeAry::make(const Type* elem, const TypeInt* size, bool stable, bool flat, bool not_flat, bool null_free, bool not_null_free, bool atomic) { - if (UseCompressedOops && elem->isa_oopptr()) { + if (UseCompressedOops && elem->is_oopptr()) { elem = elem->make_narrowoop(); } size = normalize_array_size(size); @@ -2674,7 +2674,7 @@ const TypeVect* TypeVect::makemask(BasicType elem_bt, uint length) { //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeVect::eq(const Type* t) const { - const TypeVect* v = t->is_vect(); + const TypeVect* v = t->as_vect(); return (element_basic_type() == v->element_basic_type()) && (length() == v->length()); } @@ -2776,11 +2776,11 @@ intptr_t TypePtr::get_con() const { // Compute the MEET of two types. It returns a new Type object. const Type *TypePtr::xmeet(const Type *t) const { const Type* res = xmeet_helper(t); - if (res->isa_ptr() == nullptr) { + if (!res->is_ptr()) { return res; } - const TypePtr* res_ptr = res->is_ptr(); + const TypePtr* res_ptr = res->as_ptr(); if (res_ptr->speculative() != nullptr) { // type->speculative() is null means that speculation is no better // than type, i.e. type->speculative() == type. So there are 2 @@ -2803,7 +2803,7 @@ const Type* TypePtr::xmeet_helper(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); const TypePtr* speculative = xmeet_speculative(tp); int depth = meet_inline_depth(tp->inline_depth()); return make(AnyPtr, meet_ptr(tp->ptr()), meet_offset(tp->offset()), speculative, depth); @@ -2817,7 +2817,7 @@ const Type* TypePtr::xmeet_helper(const Type* t) const { case InstKlassPtr: case AryKlassPtr: // Call in reverse direction, delegate to the subtypes to implement the meet - return t->is_ptr()->xmeet(this); + return t->as_ptr()->xmeet(this); default: typerr(t); } @@ -2825,11 +2825,11 @@ const Type* TypePtr::xmeet_helper(const Type* t) const { const Type* TypePtr::xjoin(const Type* t) const { const Type* res = xjoin_helper(t); - if (res->isa_ptr() == nullptr) { + if (!res->is_ptr()) { return res; } - const TypePtr* res_ptr = res->is_ptr(); + const TypePtr* res_ptr = res->as_ptr(); if (res_ptr->speculative() != nullptr) { // type->speculative() is null means that speculation is no better // than type, i.e. type->speculative() == type. So there are 2 @@ -2852,7 +2852,7 @@ const Type* TypePtr::xjoin_helper(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR ptr = offset == Offset::top ? TopPTR : join_ptr(tp->ptr()); const TypePtr* speculative = xjoin_speculative(tp); @@ -2868,7 +2868,7 @@ const Type* TypePtr::xjoin_helper(const Type* t) const { case InstKlassPtr: case AryKlassPtr: // Call in reverse direction - return t->is_ptr()->xjoin(this); + return t->as_ptr()->xjoin(this); default: typerr(t); } @@ -2979,7 +2979,7 @@ const TypePtr* TypePtr::xmeet_speculative(const TypePtr* other) const { other_spec = other; } - return this_spec->meet(other_spec)->is_ptr(); + return this_spec->meet(other_spec)->as_ptr(); } const TypePtr* TypePtr::xjoin_speculative(const TypePtr* other) const { @@ -3002,7 +3002,7 @@ const TypePtr* TypePtr::xjoin_speculative(const TypePtr* other) const { other_spec = other; } - return this_spec->join(other_spec)->is_ptr(); + return this_spec->join(other_spec)->as_ptr(); } /** @@ -3055,22 +3055,22 @@ const TypePtr* TypePtr::add_offset_speculative(intptr_t offset) const { if (_speculative == nullptr) { return nullptr; } - return _speculative->add_offset(offset)->is_ptr(); + return _speculative->add_offset(offset)->as_ptr(); } const TypePtr* TypePtr::with_offset_speculative(intptr_t offset) const { if (_speculative == nullptr) { return nullptr; } - return _speculative->with_offset(offset)->is_ptr(); + return _speculative->with_offset(offset)->as_ptr(); } /** * return exact klass from the speculative type if there's one */ ciKlass* TypePtr::speculative_type() const { - if (_speculative != nullptr && _speculative->isa_oopptr()) { - const TypeOopPtr* speculative = _speculative->join(this)->is_oopptr(); + if (_speculative != nullptr && _speculative->is_oopptr()) { + const TypeOopPtr* speculative = _speculative->join(this)->as_oopptr(); if (speculative->klass_is_exact()) { return speculative->exact_klass(); } @@ -3083,7 +3083,7 @@ ciKlass* TypePtr::speculative_type() const { */ bool TypePtr::speculative_maybe_null() const { if (_speculative != nullptr) { - const TypePtr* speculative = _speculative->join(this)->is_ptr(); + const TypePtr* speculative = _speculative->join(this)->as_ptr(); return speculative->maybe_null(); } return true; @@ -3091,7 +3091,7 @@ bool TypePtr::speculative_maybe_null() const { bool TypePtr::speculative_always_null() const { if (_speculative != nullptr) { - const TypePtr* speculative = _speculative->join(this)->is_ptr(); + const TypePtr* speculative = _speculative->join(this)->as_ptr(); return speculative == TypePtr::NULL_PTR; } return false; @@ -3168,7 +3168,7 @@ bool TypePtr::would_improve_ptr(ProfilePtrKind ptr_kind) const { if (speculative_always_null()) { return false; } - if (ptr_kind == ProfileAlwaysNull && speculative() != nullptr && speculative()->isa_oopptr()) { + if (ptr_kind == ProfileAlwaysNull && speculative() != nullptr && speculative()->is_oopptr()) { return false; } return true; @@ -3317,7 +3317,7 @@ const Type* TypeRawPtr::xmeet(const Type* t) const { case AnyPtr: break; case RawPtr: { - PTR tptr = t->is_ptr()->ptr(); + PTR tptr = t->as_ptr()->ptr(); PTR ptr = meet_ptr(tptr); if (ptr == Constant) { // Same constant cases have been handled in Type::xmeet(const Type*, const Type*) @@ -3333,7 +3333,7 @@ const Type* TypeRawPtr::xmeet(const Type* t) const { } // Found an AnyPtr type vs self-RawPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); switch (tp->ptr()) { case TypePtr::TopPTR: return this; case TypePtr::BotPTR: return t; @@ -3353,7 +3353,7 @@ const Type* TypeRawPtr::xjoin(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); PTR ptr = join_ptr(tp->ptr()); switch (tp->ptr()) { case TopPTR: @@ -3368,7 +3368,7 @@ const Type* TypeRawPtr::xjoin(const Type* t) const { } case RawPtr: { - const TypeRawPtr* tp = t->is_rawptr(); + const TypeRawPtr* tp = t->as_rawptr(); PTR ptr = join_ptr(tp->ptr()); // this->ptr() can only be Constant, NotNull, BotPTR if (ptr != Constant) { @@ -3750,9 +3750,9 @@ TypeOopPtr::TypeOopPtr(TYPES t, PTR ptr, ciKlass* k, const TypeInterfaces* inter _is_ptr_to_narrowklass = true; } else if (klass() == nullptr) { // Array with unknown body type - assert(this->isa_aryptr(), "only arrays without klass"); + assert(this->is_aryptr(), "only arrays without klass"); _is_ptr_to_narrowoop = UseCompressedOops; - } else if (UseCompressedOops && this->isa_aryptr() && this->offset() != arrayOopDesc::length_offset_in_bytes()) { + } else if (UseCompressedOops && this->is_aryptr() && this->offset() != arrayOopDesc::length_offset_in_bytes()) { if (klass()->is_flat_array_klass() && field_offset != Offset::top && field_offset != Offset::bottom) { // Check if the field of the value type array element contains oops ciValueKlass* vk = klass()->as_flat_array_klass()->element_klass()->as_value_klass(); @@ -3770,18 +3770,18 @@ TypeOopPtr::TypeOopPtr(TYPES t, PTR ptr, ciKlass* k, const TypeInterfaces* inter _is_ptr_to_narrowoop = true; } } else if (klass()->is_instance_klass()) { - if (this->isa_klassptr()) { + if (this->is_klassptr()) { // Perm objects don't use compressed references } else if (_offset == Offset::bottom || _offset == Offset::top) { // unsafe access _is_ptr_to_narrowoop = UseCompressedOops; } else { - assert(this->isa_instptr(), "must be an instance ptr."); + assert(this->is_instptr(), "must be an instance ptr."); if (klass() == ciEnv::current()->Class_klass() && (this->offset() == java_lang_Class::klass_offset() || this->offset() == java_lang_Class::array_klass_offset())) { // Special hidden fields from the Class. - assert(this->isa_instptr(), "must be an instance ptr."); + assert(this->is_instptr(), "must be an instance ptr."); _is_ptr_to_narrowoop = false; } else if (klass() == ciEnv::current()->Class_klass() && this->offset() >= InstanceMirrorKlass::offset_of_static_fields()) { @@ -3868,7 +3868,7 @@ const Type* TypeOopPtr::xmeet_helper(const Type *t) const { switch (t->base()) { // switch on original type case AnyPtr: { // Found an AnyPtr type vs self-OopPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); const TypePtr* speculative = xmeet_speculative(tp); @@ -3889,7 +3889,7 @@ const Type* TypeOopPtr::xmeet_helper(const Type *t) const { } case OopPtr: { // Meeting to other OopPtrs - const TypeOopPtr *tp = t->is_oopptr(); + const TypeOopPtr* tp = t->as_oopptr(); int instance_id = meet_instance_id(tp->instance_id()); const TypePtr* speculative = xmeet_speculative(tp); int depth = meet_inline_depth(tp->inline_depth()); @@ -3898,7 +3898,7 @@ const Type* TypeOopPtr::xmeet_helper(const Type *t) const { case InstPtr: // For these, flip the call around to cut down case AryPtr: - return t->is_oopptr()->xmeet_helper(this); // Call in reverse direction + return t->as_oopptr()->xmeet_helper(this); // Call in reverse direction default: typerr(t); @@ -3912,7 +3912,7 @@ const Type* TypeOopPtr::xjoin_helper(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -3934,7 +3934,7 @@ const Type* TypeOopPtr::xjoin_helper(const Type* t) const { } case OopPtr: { - const TypeOopPtr* tp = t->is_oopptr(); + const TypeOopPtr* tp = t->as_oopptr(); const TypePtr* speculative = xjoin_speculative(tp); int depth = join_inline_depth(tp->inline_depth()); @@ -3949,7 +3949,7 @@ const Type* TypeOopPtr::xjoin_helper(const Type* t) const { case InstPtr: case AryPtr: - return t->is_oopptr()->xjoin_helper(this); + return t->as_oopptr()->xjoin_helper(this); default: typerr(t); @@ -4008,7 +4008,7 @@ const TypeOopPtr* TypeOopPtr::make_from_klass_common(ciKlass *klass, bool klass_ atomic = array_klass->is_elem_atomic(); if (null_free) { - etype = etype->join_speculative(NOTNULL)->is_oopptr(); + etype = etype->join_speculative(NOTNULL)->as_oopptr(); } } else { const TypeOopPtr* exact_etype = etype; @@ -4067,7 +4067,7 @@ const TypeOopPtr* TypeOopPtr::make_from_constant(ciObject* o, bool require_const bool is_flat = o->as_array()->is_flat(); bool is_null_free = o->as_array()->is_null_free(); if (is_null_free) { - etype = etype->join_speculative(TypePtr::NOTNULL)->is_oopptr(); + etype = etype->join_speculative(TypePtr::NOTNULL)->as_oopptr(); } bool is_atomic = o->as_array()->is_atomic(); const TypeAry* arr0 = TypeAry::make(etype, TypeInt::make(o->as_array()->length()), /* stable= */ false, /* flat= */ is_flat, @@ -4445,7 +4445,7 @@ const Type* TypeInstPtr::xmeet_helper(const Type* t) const { case OopPtr: { // Meeting to OopPtrs // Found a OopPtr type vs self-InstPtr type - const TypeOopPtr *tp = t->is_oopptr(); + const TypeOopPtr* tp = t->as_oopptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); switch (tp->ptr()) { @@ -4462,7 +4462,7 @@ const Type* TypeInstPtr::xmeet_helper(const Type* t) const { case AnyPtr: { // Meeting to AnyPtrs // Found an AnyPtr type vs self-InstPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); int instance_id = meet_instance_id(InstanceTop); @@ -4487,7 +4487,7 @@ const Type* TypeInstPtr::xmeet_helper(const Type* t) const { case InstPtr: case AryPtr: - return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->is_oopptr()); + return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->as_oopptr()); } // End of switch } @@ -4499,7 +4499,7 @@ const Type* TypeInstPtr::xjoin_helper(const Type* t) const { switch (t->base()) { case AnyPtr: case OopPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -4522,7 +4522,7 @@ const Type* TypeInstPtr::xjoin_helper(const Type* t) const { case InstPtr: case AryPtr: - return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->is_oopptr()); + return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->as_oopptr()); default: typerr(t); @@ -4542,7 +4542,7 @@ ciType* TypeInstPtr::java_mirror_type() const { //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeInstPtr::eq( const Type *t ) const { - const TypeInstPtr *p = t->is_instptr(); + const TypeInstPtr* p = t->as_instptr(); return klass()->equals(p->klass()) && _flat_in_array == p->_flat_in_array && @@ -4694,7 +4694,7 @@ const TypeAryPtr* TypeAryPtr::NULLABLES; //------------------------------make------------------------------------------- const TypeAryPtr* TypeAryPtr::make(PTR ptr, const TypeAry *ary, ciKlass* k, bool xk, Offset offset, Offset field_offset, int instance_id, const TypePtr* speculative, int inline_depth) { - assert(!(k == nullptr && ary->_elem->isa_int()), + assert(!(k == nullptr && ary->_elem->is_int()), "integral arrays must be pre-equipped with a class"); if (!xk) xk = ary->ary_must_be_exact(); assert(instance_id <= 0 || xk, "instances are always exactly typed"); @@ -4709,7 +4709,7 @@ const TypeAryPtr* TypeAryPtr::make(PTR ptr, const TypeAry *ary, ciKlass* k, bool const TypeAryPtr* TypeAryPtr::make(PTR ptr, ciObject* o, const TypeAry *ary, ciKlass* k, bool xk, Offset offset, Offset field_offset, int instance_id, const TypePtr* speculative, int inline_depth, bool is_autobox_cache) { - assert(!(k == nullptr && ary->_elem->isa_int()), + assert(!(k == nullptr && ary->_elem->is_int()), "integral arrays must be pre-equipped with a class"); assert( (ptr==Constant && o) || (ptr!=Constant && !o), "" ); if (!xk) xk = (o != nullptr) || ary->ary_must_be_exact(); @@ -4813,7 +4813,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_flat() const { } assert(!is_not_flat(), "inconsistency"); - return join_speculative(TypeAryPtr::INLINES)->is_aryptr(); + return join_speculative(TypeAryPtr::INLINES)->as_aryptr(); } const TypeAryPtr* TypeAryPtr::cast_to_not_flat() const { @@ -4822,7 +4822,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_not_flat() const { } assert(!is_flat(), "inconsistency"); - return join_speculative(TypeAryPtr::REFERENCES)->is_aryptr(); + return join_speculative(TypeAryPtr::REFERENCES)->as_aryptr(); } const TypeAryPtr* TypeAryPtr::cast_to_null_free() const { @@ -4831,7 +4831,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_null_free() const { } assert(!is_not_null_free(), "inconsistency"); - return join_speculative(TypeAryPtr::NULL_FREES)->is_aryptr(); + return join_speculative(TypeAryPtr::NULL_FREES)->as_aryptr(); } //-------------------------------cast_to_not_null_free------------------------- @@ -4841,7 +4841,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_not_null_free() const { } assert(!is_null_free(), "inconsistency"); - return join_speculative(TypeAryPtr::NULLABLES)->is_aryptr(); + return join_speculative(TypeAryPtr::NULLABLES)->as_aryptr(); } //---------------------------------update_properties--------------------------- @@ -4886,9 +4886,9 @@ const TypeAryPtr* TypeAryPtr::cast_to_stable(bool stable, int stable_dimension) const Type* elem = this->elem(); const TypePtr* elem_ptr = elem->make_ptr(); - if (stable_dimension > 1 && elem_ptr != nullptr && elem_ptr->isa_aryptr()) { + if (stable_dimension > 1 && elem_ptr != nullptr && elem_ptr->is_aryptr()) { // If this is widened from a narrow oop, TypeAry::make will re-narrow it. - elem = elem_ptr = elem_ptr->is_aryptr()->cast_to_stable(stable, stable_dimension - 1); + elem = elem_ptr = elem_ptr->as_aryptr()->cast_to_stable(stable, stable_dimension - 1); } const TypeAry* new_ary = TypeAry::make(elem, size(), stable, is_flat(), is_not_flat(), is_null_free(), is_not_null_free(), is_atomic()); @@ -4901,8 +4901,8 @@ int TypeAryPtr::stable_dimension() const { if (!is_stable()) return 0; int dim = 1; const TypePtr* elem_ptr = elem()->make_ptr(); - if (elem_ptr != nullptr && elem_ptr->isa_aryptr()) - dim += elem_ptr->is_aryptr()->stable_dimension(); + if (elem_ptr != nullptr && elem_ptr->is_aryptr()) + dim += elem_ptr->as_aryptr()->stable_dimension(); return dim; } @@ -4912,7 +4912,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_autobox_cache() const { const TypeOopPtr* etype = elem()->make_oopptr(); if (etype == nullptr) return this; // The pointers in the autobox arrays are always non-null. - etype = etype->cast_to_ptr_type(TypePtr::NotNull)->is_oopptr(); + etype = etype->cast_to_ptr_type(TypePtr::NotNull)->as_oopptr(); const TypeAry* new_ary = TypeAry::make(etype, size(), is_stable(), is_flat(), is_not_flat(), is_null_free(), is_not_null_free(), is_atomic()); return make(ptr(), const_oop(), new_ary, klass(), klass_is_exact(), _offset, _field_offset, _instance_id, _speculative, _inline_depth, /*is_autobox_cache=*/true); } @@ -4920,7 +4920,7 @@ const TypeAryPtr* TypeAryPtr::cast_to_autobox_cache() const { //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeAryPtr::eq( const Type *t ) const { - const TypeAryPtr *p = t->is_aryptr(); + const TypeAryPtr* p = t->as_aryptr(); return _ary == p->_ary && // Check array TypeOopPtr::eq(p) &&// Check sub-parts @@ -4958,7 +4958,7 @@ const Type* TypeAryPtr::xmeet_helper(const Type* t) const { case OopPtr: { // Meeting to OopPtrs // Found a OopPtr type vs self-AryPtr type - const TypeOopPtr *tp = t->is_oopptr(); + const TypeOopPtr* tp = t->as_oopptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); int depth = meet_inline_depth(tp->inline_depth()); @@ -4975,7 +4975,7 @@ const Type* TypeAryPtr::xmeet_helper(const Type* t) const { case AnyPtr: { // Meeting two AnyPtrs // Found an AnyPtr type vs self-AryPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); const TypePtr* speculative = xmeet_speculative(tp); @@ -5000,7 +5000,7 @@ const Type* TypeAryPtr::xmeet_helper(const Type* t) const { case AryPtr: case InstPtr: - return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->is_oopptr()); + return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->as_oopptr()); } } @@ -5012,7 +5012,7 @@ const Type* TypeAryPtr::xjoin_helper(const Type* t) const { switch (t->base()) { case AnyPtr: case OopPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -5035,7 +5035,7 @@ const Type* TypeAryPtr::xjoin_helper(const Type* t) const { case InstPtr: case AryPtr: - return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->is_oopptr()); + return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->as_oopptr()); default: typerr(t); @@ -5171,7 +5171,7 @@ const TypeAryPtr* TypeAryPtr::remove_speculative() const { return this; } assert(_inline_depth == InlineDepthTop || _inline_depth == InlineDepthBottom, "non speculative type shouldn't have inline depth"); - return make(_ptr, _const_oop, _ary->remove_speculative()->is_ary(), _klass, _klass_is_exact, _offset, _field_offset, _instance_id, nullptr, _inline_depth, _is_autobox_cache); + return make(_ptr, _const_oop, _ary->remove_speculative()->as_ary(), _klass, _klass_is_exact, _offset, _field_offset, _instance_id, nullptr, _inline_depth, _is_autobox_cache); } const Type* TypeAryPtr::cleanup_speculative() const { @@ -5191,11 +5191,11 @@ const TypePtr* TypeAryPtr::with_inline_depth(int depth) const { if (!UseInlineDepthForSpeculativeTypes) { return this; } - return make(_ptr, _const_oop, _ary->remove_speculative()->is_ary(), _klass, _klass_is_exact, _offset, _field_offset, _instance_id, _speculative, depth, _is_autobox_cache); + return make(_ptr, _const_oop, _ary->remove_speculative()->as_ary(), _klass, _klass_is_exact, _offset, _field_offset, _instance_id, _speculative, depth, _is_autobox_cache); } const TypeAryPtr* TypeAryPtr::with_field_offset(int offset) const { - return make(_ptr, _const_oop, _ary->remove_speculative()->is_ary(), _klass, _klass_is_exact, _offset, Offset(offset), _instance_id, _speculative, _inline_depth, _is_autobox_cache); + return make(_ptr, _const_oop, _ary->remove_speculative()->as_ary(), _klass, _klass_is_exact, _offset, Offset(offset), _instance_id, _speculative, _inline_depth, _is_autobox_cache); } const TypePtr* TypeAryPtr::add_field_offset_and_offset(intptr_t offset) const { @@ -5242,7 +5242,7 @@ int TypeAryPtr::flat_offset() const { const TypePtr* TypeAryPtr::with_instance_id(int instance_id) const { assert(is_known_instance(), "should be known"); - return make(_ptr, _const_oop, _ary->remove_speculative()->is_ary(), _klass, _klass_is_exact, _offset, _field_offset, instance_id, _speculative, _inline_depth); + return make(_ptr, _const_oop, _ary->remove_speculative()->as_ary(), _klass, _klass_is_exact, _offset, _field_offset, instance_id, _speculative, _inline_depth); } //============================================================================= @@ -5278,15 +5278,15 @@ bool TypeNarrowPtr::eq( const Type *t ) const { } const Type *TypeNarrowPtr::filter_helper(const Type *kills, bool include_speculative) const { - if (isa_same_narrowptr(kills)) { - const Type* ft =_ptrtype->filter_helper(is_same_narrowptr(kills)->_ptrtype, include_speculative); + if (is_same_narrowptr(kills)) { + const Type* ft = _ptrtype->filter_helper(as_same_narrowptr(kills)->_ptrtype, include_speculative); if (ft->empty()) return Type::TOP; // Canonical empty value - if (ft->isa_ptr()) { - return make_hash_same_narrowptr(ft->isa_ptr()); + if (ft->is_ptr()) { + return make_hash_same_narrowptr(ft->as_ptr()); } return ft; - } else if (kills->isa_ptr()) { + } else if (kills->is_ptr()) { const Type* ft = _ptrtype->join_helper(kills, include_speculative); if (ft->empty()) return Type::TOP; // Canonical empty value @@ -5311,11 +5311,11 @@ const TypeNarrowOop* TypeNarrowOop::make(const TypePtr* type) { } const TypeNarrowOop* TypeNarrowOop::remove_speculative() const { - return make(_ptrtype->remove_speculative()->is_ptr()); + return make(_ptrtype->remove_speculative()->as_ptr()); } const Type* TypeNarrowOop::cleanup_speculative() const { - return make(_ptrtype->cleanup_speculative()->is_ptr()); + return make(_ptrtype->cleanup_speculative()->as_ptr()); } #ifndef PRODUCT @@ -5422,7 +5422,7 @@ const Type *TypeMetadataPtr::xmeet( const Type *t ) const { case AnyPtr: { // Found an AnyPtr type vs self-OopPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); switch (tp->ptr()) { @@ -5440,7 +5440,7 @@ const Type *TypeMetadataPtr::xmeet( const Type *t ) const { } case MetadataPtr: { - const TypeMetadataPtr *tp = t->is_metadataptr(); + const TypeMetadataPtr* tp = t->as_metadataptr(); Offset offset = meet_offset(tp->offset()); PTR tptr = tp->ptr(); PTR ptr = meet_ptr(tptr); @@ -5468,7 +5468,7 @@ const Type* TypeMetadataPtr::xjoin(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -5485,7 +5485,7 @@ const Type* TypeMetadataPtr::xjoin(const Type* t) const { } case MetadataPtr: { - const TypeMetadataPtr* tp = t->is_metadataptr(); + const TypeMetadataPtr* tp = t->as_metadataptr(); PTR ptr = join_ptr(tp->ptr()); Offset offset = join_offset(tp->offset()); if (offset == Offset::top) { @@ -5551,13 +5551,13 @@ const TypeKlassPtr* TypeAryPtr::as_klass_type(bool try_for_exact) const { if (elem->make_oopptr() != nullptr) { is_refined = true; elem = elem->make_oopptr()->as_klass_type(try_for_exact); - if (elem->isa_aryklassptr()) { - const TypeAryKlassPtr* elem_klass = elem->is_aryklassptr(); + if (elem->is_aryklassptr()) { + const TypeAryKlassPtr* elem_klass = elem->as_aryklassptr(); if (elem_klass->is_refined_type()) { elem = elem_klass->cast_to_non_refined(); } } else { - const TypeInstKlassPtr* elem_klass = elem->is_instklassptr(); + const TypeInstKlassPtr* elem_klass = elem->as_instklassptr(); if (try_for_exact && !xk && elem_klass->klass_is_exact() && !elem_klass->exact_klass()->as_instance_klass()->can_be_value_klass()) { xk = true; @@ -5598,7 +5598,7 @@ ciKlass* TypeKlassPtr::exact_klass_helper() const { //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeKlassPtr::eq(const Type *t) const { - const TypeKlassPtr *p = t->is_klassptr(); + const TypeKlassPtr* p = t->as_klassptr(); return _interfaces->eq(p->_interfaces) && TypePtr::eq(p); @@ -5676,7 +5676,7 @@ const TypeInstKlassPtr *TypeInstKlassPtr::OBJECT; const TypeInstKlassPtr *TypeInstKlassPtr::OBJECT_OR_NULL; bool TypeInstKlassPtr::eq(const Type *t) const { - const TypeInstKlassPtr* p = t->is_instklassptr(); + const TypeInstKlassPtr* p = t->as_instklassptr(); return klass()->equals(p->klass()) && _flat_in_array == p->_flat_in_array && @@ -5790,7 +5790,7 @@ const Type* TypeInstKlassPtr::xmeet(const Type* t) const { case AnyPtr: { // Meeting to AnyPtrs // Found an AnyPtr type vs self-KlassPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); switch (tp->ptr()) { @@ -5810,7 +5810,7 @@ const Type* TypeInstKlassPtr::xmeet(const Type* t) const { case InstKlassPtr: case AryKlassPtr: - return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->is_klassptr()); + return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->as_klassptr()); } // End of switch return this; // Return the double constant @@ -5823,7 +5823,7 @@ const Type* TypeInstKlassPtr::xjoin(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -5841,7 +5841,7 @@ const Type* TypeInstKlassPtr::xjoin(const Type* t) const { case InstKlassPtr: case AryKlassPtr: - return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->is_klassptr()); + return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->as_klassptr()); default: typerr(t); @@ -5853,7 +5853,7 @@ template bool TypePtr::is_java_subtype_of_helper_for_instan if (!this_one->is_loaded() || !other->is_loaded()) { return false; } - if (!this_one->is_instance_type(other)) { + if (!T1::is_instance_type(other)) { return false; } @@ -5890,7 +5890,7 @@ template bool TypePtr::is_same_java_type_as_helper_for_inst if (!this_one->is_loaded() || !other->is_loaded()) { return false; } - if (!this_one->is_instance_type(other)) { + if (!T1::is_instance_type(other)) { return false; } return this_one->klass()->equals(other->klass()) && this_one->_interfaces->eq(other->_interfaces); @@ -5906,11 +5906,11 @@ template bool TypePtr::maybe_java_subtype_of_helper_for_ins return true; } - if (this_one->is_array_type(other)) { + if (T1::is_array_type(other)) { return !this_exact && this_one->klass()->equals(ciEnv::current()->Object_klass()) && other->_interfaces->contains(this_one->_interfaces); } - assert(this_one->is_instance_type(other), "unsupported"); + assert(T1::is_instance_type(other), "unsupported"); if (this_exact && other_exact) { return this_one->is_java_subtype_of(other); @@ -5978,7 +5978,7 @@ const TypeAryKlassPtr* TypeAryKlassPtr::OBJECT_ARRAY; // Not-null object const TypeAryKlassPtr* TypeAryKlassPtr::OBJECT_ARRAY_OR_NULL; // Maybe-null object array klass bool TypeAryKlassPtr::can_be_value_array() const { - return _elem->isa_instklassptr() && _elem->is_instklassptr()->_klass->can_be_value_klass(); + return _elem->is_instklassptr() && _elem->as_instklassptr()->_klass->can_be_value_klass(); } bool TypeInstPtr::can_be_value_array() const { @@ -5986,13 +5986,53 @@ bool TypeInstPtr::can_be_value_array() const { } bool TypeAryPtr::can_be_value_array() const { - return elem()->make_ptr() && elem()->make_ptr()->isa_instptr() && elem()->make_ptr()->is_instptr()->_klass->can_be_value_klass(); + return elem()->make_ptr() && elem()->make_ptr()->is_instptr() && elem()->make_ptr()->as_instptr()->_klass->can_be_value_klass(); +} + +// Does 'this' array and 'other' array have compatible layouts for applying arraycopy? +// - Return true : We know that the layouts are compatible. +// - Return false: We either don't know or have shown that they are not compatible. +bool TypeAryPtr::has_compatible_arraycopy_layout(const TypeAryPtr* other) const { + BasicType src_elem_bt = elem()->array_element_basic_type(); + BasicType dest_elem_bt = other->elem()->array_element_basic_type(); + if (::is_reference_type(src_elem_bt, true)) { src_elem_bt = T_OBJECT; } + if (::is_reference_type(dest_elem_bt, true)) { dest_elem_bt = T_OBJECT; } + if (src_elem_bt != dest_elem_bt) { + // Different element types and thus not the same array -> incompatible + return false; + } + if (!is_java_primitive(src_elem_bt) && src_elem_bt != T_OBJECT) { + // Unsupported or unknown element type -> we don't know if they have compatible layouts + return false; + } + + if (is_not_flat() && other->is_not_flat()) { + // Both are type arrays or have reference layouts -> compatible + return true; + } + + // 'this' and 'other' could both be exact, but we might still not know all of their array properties. In this case, + // exact_klass() could return the same refined array klass even though we have different layouts at runtime. We can + // therefore not assume compatibility if the array properties are unknown to be matching. + // Note that we do not need to care about atomicity for flat arrays. Atomic flat layouts can only have an element size + // of 1, 2, 4, or 8 bytes. We can use the corresponding primitive arraycopy stubs which copy the elements atomically. + // Flat arrays with elements larger than 8 bytes cannot have an atomic layout. + bool same_known_nullness = (is_null_free() && other->is_null_free()) || + (is_not_null_free() && other->is_not_null_free()); + if (is_flat() && other->is_flat() && + same_known_nullness && + klass_is_exact() && other->klass_is_exact() && exact_klass() == other->exact_klass()) { + // Same refined array klass and same flatness and nullness -> same physical layout -> compatible + return true; + } + // Otherwise, we don't have more information and must assume incompatibility. + return false; } const TypeAryKlassPtr *TypeAryKlassPtr::make(PTR ptr, const Type* elem, ciKlass* k, Offset offset, bool not_flat, bool not_null_free, bool flat, bool null_free, bool atomic, bool refined_type) { - if (ptr == TypePtr::Constant && elem->isa_klassptr() != nullptr) { + if (ptr == TypePtr::Constant && elem->is_klassptr()) { // If an array klass ptr is a constant, its element is also a constant - elem = elem->is_klassptr()->cast_to_exactness(true); + elem = elem->as_klassptr()->cast_to_exactness(true); } return (TypeAryKlassPtr*)(new TypeAryKlassPtr(ptr, elem, k, offset, not_flat, not_null_free, flat, null_free, atomic, refined_type))->hashcons(); } @@ -6029,7 +6069,7 @@ const TypeAryKlassPtr* TypeAryKlassPtr::cast_to_non_refined() const { assert(is_refined_type(), "must be a refined type"); PTR ptr = _ptr; // There can be multiple refined array types corresponding to a single unrefined type - if (ptr == NotNull && elem()->is_klassptr()->klass_is_exact()) { + if (ptr == NotNull && elem()->as_klassptr()->klass_is_exact()) { ptr = Constant; } return make(ptr, elem(), nullptr, _offset, true, true, false, false, true, false); @@ -6048,7 +6088,7 @@ const TypeAryKlassPtr* TypeAryKlassPtr::cast_to_refined_array_klass_ptr(bool ref //------------------------------eq--------------------------------------------- // Structural equality check for Type representations bool TypeAryKlassPtr::eq(const Type *t) const { - const TypeAryKlassPtr *p = t->is_aryklassptr(); + const TypeAryKlassPtr* p = t->as_aryklassptr(); return _elem == p->_elem && // Check array _flat == p->_flat && @@ -6072,17 +6112,13 @@ uint TypeAryKlassPtr::hash(void) const { ciKlass* TypeAryPtr::compute_klass() const { // Compute _klass based on element type. ciKlass* k_ary = nullptr; - const TypeInstPtr *tinst; - const TypeAryPtr *tary; const Type* el = elem(); - if (el->isa_narrowoop()) { + if (el->is_narrowoop()) { el = el->make_ptr(); } // Get element klass - if ((tinst = el->isa_instptr()) != nullptr) { - // Leave k_ary at nullptr. - } else if ((tary = el->isa_aryptr()) != nullptr) { + if (el->is_instptr() || el->is_aryptr()) { // Leave k_ary at nullptr. } else if ((el->base() == Type::Top) || (el->base() == Type::Bottom)) { @@ -6090,7 +6126,7 @@ ciKlass* TypeAryPtr::compute_klass() const { // and object; Top occurs when doing join on Bottom. // Leave k_ary at null. } else { - assert(!el->isa_int(), "integral arrays must be pre-equipped with a class"); + assert(!el->is_int(), "integral arrays must be pre-equipped with a class"); // Compute array klass directly from basic type k_ary = ciTypeArrayKlass::make(el->basic_type()); } @@ -6126,8 +6162,8 @@ ciKlass* TypeAryPtr::klass() const { // Is there a single ciKlass* that can represent that type? ciKlass* TypeAryPtr::exact_klass_helper() const { - if (_ary->_elem->make_ptr() && _ary->_elem->make_ptr()->isa_oopptr()) { - ciKlass* k = _ary->_elem->make_ptr()->is_oopptr()->exact_klass_helper(); + if (const TypePtr* ary_ptr = _ary->_elem->make_ptr(); ary_ptr != nullptr && ary_ptr->is_oopptr()) { + ciKlass* k = ary_ptr->as_oopptr()->exact_klass_helper(); if (k == nullptr) { return nullptr; } @@ -6136,7 +6172,7 @@ ciKlass* TypeAryPtr::exact_klass_helper() const { k = ciObjArrayKlass::make(k->as_array_klass()->element_klass(), false); } if (klass_is_exact()) { - return ciObjArrayKlass::make(k, true, is_null_free(), is_atomic()); + return ciObjArrayKlass::make(k, true, is_null_free(), is_atomic(), is_not_flat()); } else { // We may reach here if called recursively, must be an unrefined type then return ciObjArrayKlass::make(k, false); @@ -6149,8 +6185,8 @@ ciKlass* TypeAryPtr::exact_klass_helper() const { const Type* TypeAryPtr::base_element_type(int& dims) const { const Type* elem = this->elem(); dims = 1; - while (elem->make_ptr() && elem->make_ptr()->isa_aryptr()) { - elem = elem->make_ptr()->is_aryptr()->elem(); + while (elem->make_ptr() && elem->make_ptr()->is_aryptr()) { + elem = elem->make_ptr()->as_aryptr()->elem(); dims++; } return elem; @@ -6178,8 +6214,7 @@ bool TypeAryKlassPtr::must_be_exact() const { if (_elem == Type::BOTTOM || _elem == Type::TOP) { return false; } - const TypeKlassPtr* elem = _elem->isa_klassptr(); - if (elem == nullptr) { + if (!_elem->is_klassptr()) { // primitive arrays return true; } @@ -6197,8 +6232,8 @@ const TypeAryKlassPtr* TypeAryKlassPtr::cast_to_exactness(bool klass_is_exact) c return this; } const Type* elem = this->elem(); - if (elem->isa_klassptr() && !klass_is_exact) { - elem = elem->is_klassptr()->cast_to_exactness(klass_is_exact); + if (elem->is_klassptr() && !klass_is_exact) { + elem = elem->as_klassptr()->cast_to_exactness(klass_is_exact); } if (klass_is_exact) { @@ -6208,9 +6243,10 @@ const TypeAryKlassPtr* TypeAryKlassPtr::cast_to_exactness(bool klass_is_exact) c } else { // cast_to_exactness(false) means get the TypeAryKlassPtr representing all values that subtype // this value - bool not_value = !_elem->isa_instklassptr() || !_elem->is_instklassptr()->instance_klass()->can_be_value_klass(); + const TypeInstKlassPtr* elem_inst_klass_ptr = _elem->isa_instklassptr(); + bool not_value = elem_inst_klass_ptr == nullptr || !elem_inst_klass_ptr->instance_klass()->can_be_value_klass(); bool not_flat = !UseArrayFlattening || not_value || - (_elem->isa_instklassptr() && _elem->is_instklassptr()->instance_klass()->is_value_klass() && !_elem->is_instklassptr()->instance_klass()->maybe_flat_in_array()); + (elem_inst_klass_ptr != nullptr && elem_inst_klass_ptr->instance_klass()->is_value_klass() && !elem_inst_klass_ptr->instance_klass()->maybe_flat_in_array()); bool not_null_free = not_value; bool atomic = not_flat; return make(NotNull, elem, nullptr, _offset, not_flat, not_null_free, false, false, atomic, false); @@ -6224,16 +6260,16 @@ const TypeAryPtr* TypeAryKlassPtr::as_exact_instance_type(bool klass_change) con ciKlass* k = klass(); bool xk = klass_is_exact(); const Type* el = nullptr; - if (elem()->isa_klassptr()) { - el = elem()->is_klassptr()->as_subtype_instance_type(false); + if (elem()->is_klassptr()) { + el = elem()->as_klassptr()->as_subtype_instance_type(false); k = nullptr; } else { el = elem(); } bool flat, not_flat, null_free, not_null_free, atomic; if (_refined_type) { - if (_null_free && el->isa_ptr()) { - el = el->is_ptr()->join_speculative(TypePtr::NOTNULL); + if (_null_free && el->is_ptr()) { + el = el->as_ptr()->join_speculative(TypePtr::NOTNULL); } flat = is_flat(); not_flat = is_not_flat(); @@ -6248,11 +6284,11 @@ const TypeAryPtr* TypeAryKlassPtr::as_exact_instance_type(bool klass_change) con // Only arrays of value classes can be null free. Otherwise, not_null_free == true. That is if the element type // is not an instance class, or this instance class cannot be a value type, it's surely not null-restricted. not_null_free = is_java_primitive(elem()->basic_type()) || - elem()->isa_aryklassptr() != nullptr || - (elem()->isa_instklassptr() != nullptr && !elem()->is_instklassptr()->can_be_value_type()); + elem()->is_aryklassptr() || + (elem()->is_instklassptr() && !elem()->as_instklassptr()->can_be_value_type()); bool array_can_be_flat; - if (elem()->isa_instklassptr()) { - FlatInArray elem_flat_in_array = elem()->is_instklassptr()->flat_in_array(); + if (elem()->is_instklassptr()) { + FlatInArray elem_flat_in_array = elem()->as_instklassptr()->flat_in_array(); array_can_be_flat = elem_flat_in_array == MaybeFlat || elem_flat_in_array == Flat; } else { array_can_be_flat = elem() == Type::BOTTOM; @@ -6281,7 +6317,7 @@ const Type* TypeAryKlassPtr::xmeet(const Type* t) const { case AnyPtr: { // Meeting to AnyPtrs // Found an AnyPtr type vs self-KlassPtr type - const TypePtr *tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = meet_offset(tp->offset()); PTR ptr = meet_ptr(tp->ptr()); switch (tp->ptr()) { @@ -6301,7 +6337,7 @@ const Type* TypeAryKlassPtr::xmeet(const Type* t) const { case AryKlassPtr: case InstKlassPtr: - return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->is_klassptr()); + return TypeJavaPtrMeetHelper::javaptr_type_xmeet(this, t->as_klassptr()); } // End of switch return this; // Return the double constant @@ -6314,7 +6350,7 @@ const Type* TypeAryKlassPtr::xjoin(const Type* t) const { switch (t->base()) { case AnyPtr: { - const TypePtr* tp = t->is_ptr(); + const TypePtr* tp = t->as_ptr(); Offset offset = join_offset(tp->offset()); PTR other_ptr = offset == Offset::top ? TopPTR : tp->ptr(); PTR ptr = join_ptr(other_ptr); @@ -6332,7 +6368,7 @@ const Type* TypeAryKlassPtr::xjoin(const Type* t) const { case InstKlassPtr: case AryKlassPtr: - return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->is_klassptr()); + return TypeJavaPtrJoinHelper::javaptr_type_xjoin(this, t->as_klassptr()); default: typerr(t); @@ -6353,13 +6389,13 @@ template bool TypePtr::is_java_subtype_of_helper_for_array( return false; } - if (this_one->is_instance_type(other)) { + if (T1::is_instance_type(other)) { return other->klass() == ciEnv::current()->Object_klass() && this_one->_interfaces->contains(other->_interfaces) && other_exact; } - assert(this_one->is_array_type(other), ""); - const T1* other_ary = this_one->is_array_type(other); + assert(T1::is_array_type(other), ""); + const T1* other_ary = T1::as_array_type(other); bool other_top_or_bottom = (other_ary->base_element_type(dummy) == Type::TOP || other_ary->base_element_type(dummy) == Type::BOTTOM); if (other_top_or_bottom) { return false; @@ -6371,7 +6407,7 @@ template bool TypePtr::is_java_subtype_of_helper_for_array( if (other->is_null_free() && !this_one->is_null_free()) { return false; // A nullable array can't be a subtype of a null-free array } - return this_one->is_reference_type(this_elem)->is_java_subtype_of_helper(this_one->is_reference_type(other_elem), this_exact, other_exact); + return T1::as_reference_type(this_elem)->is_java_subtype_of_helper(T1::as_reference_type(other_elem), this_exact, other_exact); } if (this_elem == nullptr && other_elem == nullptr) { return this_one->klass()->is_subtype_of(other->klass()); @@ -6389,11 +6425,11 @@ template bool TypePtr::is_same_java_type_as_helper_for_arra int dummy; bool this_top_or_bottom = (this_one->base_element_type(dummy) == Type::TOP || this_one->base_element_type(dummy) == Type::BOTTOM); - if (!this_one->is_array_type(other) || + if (!T1::is_array_type(other) || !this_one->is_loaded() || !other->is_loaded() || this_top_or_bottom) { return false; } - const T1* other_ary = this_one->is_array_type(other); + const T1* other_ary = T1::as_array_type(other); bool other_top_or_bottom = (other_ary->base_element_type(dummy) == Type::TOP || other_ary->base_element_type(dummy) == Type::BOTTOM); if (other_top_or_bottom) { @@ -6403,7 +6439,7 @@ template bool TypePtr::is_same_java_type_as_helper_for_arra const TypePtr* other_elem = other_ary->elem()->make_ptr(); const TypePtr* this_elem = this_one->elem()->make_ptr(); if (other_elem != nullptr && this_elem != nullptr) { - return this_one->is_reference_type(this_elem)->is_same_java_type_as(this_one->is_reference_type(other_elem)); + return T1::as_reference_type(this_elem)->is_same_java_type_as(T1::as_reference_type(other_elem)); } if (other_elem == nullptr && this_elem == nullptr) { return this_one->klass()->equals(other->klass()); @@ -6423,7 +6459,7 @@ template bool TypePtr::maybe_java_subtype_of_helper_for_arr if (!this_one->is_loaded() || !other->is_loaded()) { return true; } - if (this_one->is_instance_type(other)) { + if (T1::is_instance_type(other)) { return other->klass()->equals(ciEnv::current()->Object_klass()) && this_one->_interfaces->contains(other->_interfaces); } @@ -6434,9 +6470,9 @@ template bool TypePtr::maybe_java_subtype_of_helper_for_arr return true; } - assert(this_one->is_array_type(other), ""); + assert(T1::is_array_type(other), ""); - const T1* other_ary = this_one->is_array_type(other); + const T1* other_ary = T1::as_array_type(other); bool other_top_or_bottom = (other_ary->base_element_type(dummy) == Type::TOP || other_ary->base_element_type(dummy) == Type::BOTTOM); if (other_top_or_bottom) { return true; @@ -6448,7 +6484,7 @@ template bool TypePtr::maybe_java_subtype_of_helper_for_arr const TypePtr* this_elem = this_one->elem()->make_ptr(); const TypePtr* other_elem = other_ary->elem()->make_ptr(); if (other_elem != nullptr && this_elem != nullptr) { - return this_one->is_reference_type(this_elem)->maybe_java_subtype_of_helper(this_one->is_reference_type(other_elem), this_exact, other_exact); + return T1::as_reference_type(this_elem)->maybe_java_subtype_of_helper(T1::as_reference_type(other_elem), this_exact, other_exact); } if (other_elem == nullptr && this_elem == nullptr) { return this_one->klass()->is_subtype_of(other->klass()); @@ -6462,8 +6498,8 @@ bool TypeAryKlassPtr::maybe_java_subtype_of_helper(const TypeKlassPtr* other, bo // Is there a single ciKlass* that can represent that type? ciKlass* TypeAryKlassPtr::exact_klass_helper() const { - if (elem()->isa_klassptr()) { - ciKlass* k = elem()->is_klassptr()->exact_klass_helper(); + if (elem()->is_klassptr()) { + ciKlass* k = elem()->as_klassptr()->exact_klass_helper(); if (k == nullptr) { return nullptr; } @@ -6480,7 +6516,7 @@ ciKlass* TypeAryKlassPtr::klass() const { return _klass; } ciKlass* k = nullptr; - if (elem()->isa_klassptr()) { + if (elem()->is_klassptr()) { // leave null } else if ((elem()->base() == Type::Top) || (elem()->base() == Type::Bottom)) { @@ -6514,8 +6550,8 @@ void TypeAryKlassPtr::dump2( Dict & d, uint depth, outputStream *st ) const { const Type* TypeAryKlassPtr::base_element_type(int& dims) const { const Type* elem = this->elem(); dims = 1; - while (elem->isa_aryklassptr()) { - elem = elem->is_aryklassptr()->elem(); + while (elem->is_aryklassptr()) { + elem = elem->as_aryklassptr()->elem(); dims++; } return elem; diff --git a/src/hotspot/share/opto/type.hpp b/src/hotspot/share/opto/type.hpp index ce4bf5bb38a6..1d6d7c836ce8 100644 --- a/src/hotspot/share/opto/type.hpp +++ b/src/hotspot/share/opto/type.hpp @@ -26,6 +26,7 @@ #define SHARE_OPTO_TYPE_HPP #include "ci/ciValueKlass.hpp" +#include "metaprogramming/dependentAlwaysFalse.hpp" #include "opto/adlcVMDeps.hpp" #include "opto/compile.hpp" #include "opto/rangeinference.hpp" @@ -180,7 +181,6 @@ class Type { typedef struct { BasicType basic_type; const char* msg; - bool isa_oop; uint ideal_reg; } TypeInfo; @@ -303,59 +303,108 @@ class Type { virtual float getf() const; double getd() const; - // This has the same semantics as std::dynamic_cast(this) - template - const TypeClass* try_cast() const; - - const TypeInt *is_int() const; - const TypeInt *isa_int() const; // Returns null if not an Int - const TypeInteger* is_integer(BasicType bt) const; - const TypeInteger* isa_integer(BasicType bt) const; - const TypeLong *is_long() const; - const TypeLong *isa_long() const; // Returns null if not a Long - const TypeD *isa_double() const; // Returns null if not a Double{Top,Con,Bot} - const TypeD *is_double_constant() const; // Asserts it is a DoubleCon - const TypeD *isa_double_constant() const; // Returns null if not a DoubleCon - const TypeH *isa_half_float() const; // Returns null if not a HalfFloat{Top,Con,Bot} - const TypeH *is_half_float_constant() const; // Asserts it is a HalfFloatCon - const TypeH *isa_half_float_constant() const; // Returns null if not a HalfFloatCon - const TypeF *isa_float() const; // Returns null if not a Float{Top,Con,Bot} - const TypeF *is_float_constant() const; // Asserts it is a FloatCon - const TypeF *isa_float_constant() const; // Returns null if not a FloatCon - const TypeTuple *is_tuple() const; // Collection of fields, NOT a pointer - const TypeAry *is_ary() const; // Array, NOT array pointer - const TypeAry *isa_ary() const; // Returns null of not ary - const TypeVect *is_vect() const; // Vector - const TypeVect *isa_vect() const; // Returns null if not a Vector - const TypePVectMask *is_pvectmask() const; // Predicate/Mask Vector - const TypePVectMask *isa_pvectmask() const; // Returns null if not a Vector Predicate/Mask - const TypePtr *is_ptr() const; // Asserts it is a ptr type - const TypePtr *isa_ptr() const; // Returns null if not ptr type - const TypeRawPtr *isa_rawptr() const; // NOT Java oop - const TypeRawPtr *is_rawptr() const; // Asserts is rawptr - const TypeNarrowOop *is_narrowoop() const; // Java-style GC'd pointer - const TypeNarrowOop *isa_narrowoop() const; // Returns null if not oop ptr type - const TypeNarrowKlass *is_narrowklass() const; // compressed klass pointer - const TypeNarrowKlass *isa_narrowklass() const;// Returns null if not oop ptr type - const TypeOopPtr *isa_oopptr() const; // Returns null if not oop ptr type - const TypeOopPtr *is_oopptr() const; // Java-style GC'd pointer - const TypeInstPtr *isa_instptr() const; // Returns null if not InstPtr - const TypeInstPtr *is_instptr() const; // Instance - const TypeAryPtr *isa_aryptr() const; // Returns null if not AryPtr - const TypeAryPtr *is_aryptr() const; // Array oop +private: + // Boilerplate to get nice error messages in as_XXX + template const T* as(bool (Type::*is_xxx)() const, const char* expected) const; +public: + // Testing and casting: + // - is_* checks whether `this` is of the given kind. + // - isa_* checks whether `this` is of the given kind and casts. Returns nullptr in case of failure. + // - as_* asserts `this` is of the given kind and casts. Never returns nullptr. + + [[nodiscard]] bool is_int() const; + [[nodiscard]] const TypeInt* isa_int() const; + [[nodiscard]] const TypeInt* as_int() const; + + [[nodiscard]] bool is_long() const; + [[nodiscard]] const TypeLong* isa_long() const; + [[nodiscard]] const TypeLong* as_long() const; + + // Either int or long. To use only with bt == T_INT || bt == T_LONG + [[nodiscard]] bool is_integer(BasicType bt) const; + [[nodiscard]] const TypeInteger* isa_integer(BasicType bt) const; + [[nodiscard]] const TypeInteger* as_integer(BasicType bt) const; + + [[nodiscard]] bool is_double() const; + + [[nodiscard]] bool is_double_constant() const; + [[nodiscard]] const TypeD* isa_double_constant() const; + [[nodiscard]] const TypeD* as_double_constant() const; + + [[nodiscard]] bool is_half_float() const; + + [[nodiscard]] bool is_half_float_constant() const; + [[nodiscard]] const TypeH* isa_half_float_constant() const; + [[nodiscard]] const TypeH* as_half_float_constant() const; + + [[nodiscard]] bool is_float() const; + + [[nodiscard]] bool is_float_constant() const; + [[nodiscard]] const TypeF* isa_float_constant() const; + [[nodiscard]] const TypeF* as_float_constant() const; + + [[nodiscard]] bool is_tuple() const; + [[nodiscard]] const TypeTuple* as_tuple() const; + + [[nodiscard]] bool is_ary() const; + [[nodiscard]] const TypeAry* isa_ary() const; + [[nodiscard]] const TypeAry* as_ary() const; + + [[nodiscard]] bool is_vect() const; + [[nodiscard]] const TypeVect* isa_vect() const; + [[nodiscard]] const TypeVect* as_vect() const; + + [[nodiscard]] bool is_pvectmask() const; + [[nodiscard]] const TypePVectMask* isa_pvectmask() const; + [[nodiscard]] const TypePVectMask* as_pvectmask() const; + + [[nodiscard]] bool is_ptr() const; + [[nodiscard]] const TypePtr* isa_ptr() const; + [[nodiscard]] const TypePtr* as_ptr() const; + + [[nodiscard]] bool is_rawptr() const; + [[nodiscard]] const TypeRawPtr* isa_rawptr() const; + [[nodiscard]] const TypeRawPtr* as_rawptr() const; + + [[nodiscard]] bool is_narrowoop() const; + [[nodiscard]] const TypeNarrowOop* isa_narrowoop() const; + [[nodiscard]] const TypeNarrowOop* as_narrowoop() const; + + [[nodiscard]] bool is_narrowklass() const; + [[nodiscard]] const TypeNarrowKlass* isa_narrowklass() const; + [[nodiscard]] const TypeNarrowKlass* as_narrowklass() const; + + [[nodiscard]] bool is_oopptr() const; + [[nodiscard]] const TypeOopPtr* isa_oopptr() const; + [[nodiscard]] const TypeOopPtr* as_oopptr() const; + + [[nodiscard]] bool is_instptr() const; + [[nodiscard]] const TypeInstPtr* isa_instptr() const; + [[nodiscard]] const TypeInstPtr* as_instptr() const; + + [[nodiscard]] bool is_aryptr() const; + [[nodiscard]] const TypeAryPtr* isa_aryptr() const; + [[nodiscard]] const TypeAryPtr* as_aryptr() const; + + [[nodiscard]] bool is_metadataptr() const; + [[nodiscard]] const TypeMetadataPtr* isa_metadataptr() const; + [[nodiscard]] const TypeMetadataPtr* as_metadataptr() const; + + [[nodiscard]] bool is_klassptr() const; + [[nodiscard]] const TypeKlassPtr* isa_klassptr() const; + [[nodiscard]] const TypeKlassPtr* as_klassptr() const; + + [[nodiscard]] bool is_instklassptr() const; + [[nodiscard]] const TypeInstKlassPtr* isa_instklassptr() const; + [[nodiscard]] const TypeInstKlassPtr* as_instklassptr() const; + + [[nodiscard]] bool is_aryklassptr() const; + [[nodiscard]] const TypeAryKlassPtr* isa_aryklassptr() const; + [[nodiscard]] const TypeAryKlassPtr* as_aryklassptr() const; template const TypeClass* cast() const; - const TypeMetadataPtr *isa_metadataptr() const; // Returns null if not oop ptr type - const TypeMetadataPtr *is_metadataptr() const; // Java-style GC'd pointer - const TypeKlassPtr *isa_klassptr() const; // Returns null if not KlassPtr - const TypeKlassPtr *is_klassptr() const; // assert if not KlassPtr - const TypeInstKlassPtr *isa_instklassptr() const; // Returns null if not IntKlassPtr - const TypeInstKlassPtr *is_instklassptr() const; // assert if not IntKlassPtr - const TypeAryKlassPtr *isa_aryklassptr() const; // Returns null if not AryKlassPtr - const TypeAryKlassPtr *is_aryklassptr() const; // assert if not AryKlassPtr - virtual bool is_finite() const; // Has a finite value virtual bool is_nan() const; // Is not a number (NaN) @@ -471,7 +520,6 @@ class Type { BasicType basic_type() const { return _type_info[_base].basic_type; } uint ideal_reg() const { return _type_info[_base].ideal_reg; } const char* msg() const { return _type_info[_base].msg; } - bool isa_oop_ptr() const { return _type_info[_base].isa_oop; } // Mapping from CI type system to compiler type: static const Type* get_typeflow_type(ciType* type); @@ -804,9 +852,9 @@ class TypeInt : public TypeInteger { static const TypeInt* make(jint lo, jint hi, int widen); static const TypeInt* make_unsigned(juint ulo, juint uhi, int widen); static const Type* make_or_top(const TypeIntPrototype& t, int widen); - static const TypeInt* make(const TypeIntPrototype& t, int widen) { return make_or_top(t, widen)->is_int(); } + static const TypeInt* make(const TypeIntPrototype& t, int widen) { return make_or_top(t, widen)->as_int(); } static const TypeInt* make(const TypeIntMirror& t, int widen) { - return (new TypeInt(TypeIntPrototype{{t._lo, t._hi}, {t._ulo, t._uhi}, t._bits}, widen))->hashcons()->is_int(); + return (new TypeInt(TypeIntPrototype{{t._lo, t._hi}, {t._ulo, t._uhi}, t._bits}, widen))->hashcons()->as_int(); } // Check for single integer @@ -859,7 +907,7 @@ class TypeInt : public TypeInteger { static const TypeInt* SYMINT; // symmetric range [-max_jint..max_jint] static const TypeInt* TYPE_DOMAIN; // alias for TypeInt::INT - static const TypeInt* as_self(const Type* t) { return t->is_int(); } + static const TypeInt* as_self(const Type* t) { return t->as_int(); } #ifndef PRODUCT virtual void dump2(Dict& d, uint depth, outputStream* st) const; void dump_verbose() const; @@ -895,9 +943,9 @@ class TypeLong : public TypeInteger { static const TypeLong* make(jlong lo, jlong hi, int widen); static const TypeLong* make_unsigned(julong ulo, julong uhi, int widen); static const Type* make_or_top(const TypeIntPrototype& t, int widen); - static const TypeLong* make(const TypeIntPrototype& t, int widen) { return make_or_top(t, widen)->is_long(); } + static const TypeLong* make(const TypeIntPrototype& t, int widen) { return make_or_top(t, widen)->as_long(); } static const TypeLong* make(const TypeIntMirror& t, int widen) { - return (new TypeLong(TypeIntPrototype{{t._lo, t._hi}, {t._ulo, t._uhi}, t._bits}, widen))->hashcons()->is_long(); + return (new TypeLong(TypeIntPrototype{{t._lo, t._hi}, {t._ulo, t._uhi}, t._bits}, widen))->hashcons()->as_long(); } // Check for single integer @@ -939,7 +987,7 @@ class TypeLong : public TypeInteger { static const TypeLong* TYPE_DOMAIN; // alias for TypeLong::LONG // static convenience methods. - static const TypeLong* as_self(const Type* t) { return t->is_long(); } + static const TypeLong* as_self(const Type* t) { return t->as_long(); } #ifndef PRODUCT virtual void dump2(Dict& d, uint, outputStream* st) const;// Specialized per-Type dumping @@ -1435,7 +1483,7 @@ class TypeOopPtr : public TypePtr { } bool is_same_java_type_as(const TypePtr* other) const { - return is_same_java_type_as_helper(other->is_oopptr()); + return is_same_java_type_as_helper(other->as_oopptr()); } virtual bool is_same_java_type_as_helper(const TypeOopPtr* other) const { @@ -1540,16 +1588,20 @@ class TypeOopPtr : public TypePtr { virtual void dump2( Dict &d, uint depth, outputStream *st ) const; #endif private: - const TypeOopPtr* is_reference_type(const Type* other) const { - return other->isa_oopptr(); + static const TypeOopPtr* as_reference_type(const Type* other) { + return other->as_oopptr(); } - const TypeAryPtr* is_array_type(const TypeOopPtr* other) const { - return other->isa_aryptr(); + static bool is_array_type(const TypeOopPtr* other) { + return other->is_aryptr(); } - const TypeInstPtr* is_instance_type(const TypeOopPtr* other) const { - return other->isa_instptr(); + static const TypeAryPtr* as_array_type(const TypeOopPtr* other) { + return other->as_aryptr(); + } + + static bool is_instance_type(const TypeOopPtr* other) { + return other->is_instptr(); } }; @@ -1668,7 +1720,7 @@ class TypeInstPtr : public TypeOopPtr { private: virtual bool is_meet_same_type_as(const TypePtr* other) const { - return _klass->equals(other->is_instptr()->_klass) && _interfaces->eq(other->is_instptr()->_interfaces); + return _klass->equals(other->as_instptr()->_klass) && _interfaces->eq(other->as_instptr()->_interfaces); } }; @@ -1810,6 +1862,7 @@ class TypeAryPtr : public TypeOopPtr { virtual const TypeKlassPtr* as_klass_type(bool try_for_exact = false) const; virtual bool can_be_value_array() const; + bool has_compatible_arraycopy_layout(const TypeAryPtr* other) const; // Convenience common pre-built types. static const TypeAryPtr* BOTTOM; @@ -1918,7 +1971,7 @@ class TypeKlassPtr : public TypePtr { return is_java_subtype_of_helper(other, klass_is_exact(), other->klass_is_exact()); } bool is_same_java_type_as(const TypePtr* other) const { - return is_same_java_type_as_helper(other->is_klassptr()); + return is_same_java_type_as_helper(other->as_klassptr()); } bool maybe_java_subtype_of(const TypeKlassPtr* other) const { @@ -1962,16 +2015,20 @@ class TypeKlassPtr : public TypePtr { }; private: - const TypeKlassPtr* is_reference_type(const Type* other) const { - return other->isa_klassptr(); + static const TypeKlassPtr* as_reference_type(const Type* other) { + return other->as_klassptr(); + } + + static bool is_array_type(const TypeKlassPtr* other) { + return other->is_aryklassptr(); } - const TypeAryKlassPtr* is_array_type(const TypeKlassPtr* other) const { - return other->isa_aryklassptr(); + static const TypeAryKlassPtr* as_array_type(const TypeKlassPtr* other) { + return other->as_aryklassptr(); } - const TypeInstKlassPtr* is_instance_type(const TypeKlassPtr* other) const { - return other->isa_instklassptr(); + static bool is_instance_type(const TypeKlassPtr* other) { + return other->is_instklassptr(); } }; @@ -2087,7 +2144,7 @@ class TypeAryKlassPtr : public TypeKlassPtr { bool is_java_subtype_of_helper(const TypeKlassPtr* other, bool this_exact, bool other_exact) const; bool maybe_java_subtype_of_helper(const TypeKlassPtr* other, bool this_exact, bool other_exact) const; - bool is_loaded() const { return (_elem->isa_klassptr() ? _elem->is_klassptr()->is_loaded() : true); } + bool is_loaded() const { return (_elem->is_klassptr() ? _elem->as_klassptr()->is_loaded() : true); } static const TypeAryKlassPtr* make(PTR ptr, const Type* elem, ciKlass* k, Offset offset, bool not_flat, bool not_null_free, bool flat, bool null_free, bool atomic, bool refined_type); static const TypeAryKlassPtr* make(ciKlass* klass, InterfaceHandling interface_handling); @@ -2146,10 +2203,11 @@ class TypeNarrowPtr : public Type { ptrtype->offset() == OffsetTop, "no real offsets"); } - virtual const TypeNarrowPtr *isa_same_narrowptr(const Type *t) const = 0; - virtual const TypeNarrowPtr *is_same_narrowptr(const Type *t) const = 0; - virtual const TypeNarrowPtr *make_same_narrowptr(const TypePtr *t) const = 0; - virtual const TypeNarrowPtr *make_hash_same_narrowptr(const TypePtr *t) const = 0; + virtual bool is_same_narrowptr(const Type* t) const = 0; + virtual const TypeNarrowPtr* isa_same_narrowptr(const Type* t) const = 0; + virtual const TypeNarrowPtr* as_same_narrowptr(const Type* t) const = 0; + virtual const TypeNarrowPtr* make_same_narrowptr(const TypePtr* t) const = 0; + virtual const TypeNarrowPtr* make_hash_same_narrowptr(const TypePtr* t) const = 0; // Do not allow interface-vs.-noninterface joins to collapse to top. virtual const Type *filter_helper(const Type *kills, bool include_speculative) const; public: @@ -2190,19 +2248,23 @@ class TypeNarrowOop : public TypeNarrowPtr { TypeNarrowOop( const TypePtr* ptrtype): TypeNarrowPtr(NarrowOop, ptrtype) { } - virtual const TypeNarrowPtr *isa_same_narrowptr(const Type *t) const { + bool is_same_narrowptr(const Type* t) const override { + return t->is_narrowoop(); + } + + const TypeNarrowPtr* isa_same_narrowptr(const Type* t) const override { return t->isa_narrowoop(); } - virtual const TypeNarrowPtr *is_same_narrowptr(const Type *t) const { - return t->is_narrowoop(); + const TypeNarrowPtr* as_same_narrowptr(const Type* t) const override { + return t->as_narrowoop(); } - virtual const TypeNarrowPtr *make_same_narrowptr(const TypePtr *t) const { + const TypeNarrowPtr* make_same_narrowptr(const TypePtr* t) const override { return new TypeNarrowOop(t); } - virtual const TypeNarrowPtr *make_hash_same_narrowptr(const TypePtr *t) const { + const TypeNarrowPtr* make_hash_same_narrowptr(const TypePtr* t) const override { return (const TypeNarrowPtr*)((new TypeNarrowOop(t))->hashcons()); } @@ -2217,11 +2279,11 @@ class TypeNarrowOop : public TypeNarrowPtr { static const TypeNarrowOop *BOTTOM; static const TypeNarrowOop *NULL_PTR; - virtual const TypeNarrowOop* remove_speculative() const; - virtual const Type* cleanup_speculative() const; + const TypeNarrowOop* remove_speculative() const override; + const Type* cleanup_speculative() const override; #ifndef PRODUCT - virtual void dump2( Dict &d, uint depth, outputStream *st ) const; + void dump2(Dict& d, uint depth, outputStream* st) const override; #endif }; @@ -2234,19 +2296,23 @@ class TypeNarrowKlass : public TypeNarrowPtr { TypeNarrowKlass( const TypePtr* ptrtype): TypeNarrowPtr(NarrowKlass, ptrtype) { } - virtual const TypeNarrowPtr *isa_same_narrowptr(const Type *t) const { + bool is_same_narrowptr(const Type* t) const override { + return t->is_narrowklass(); + } + + const TypeNarrowPtr* isa_same_narrowptr(const Type* t) const override { return t->isa_narrowklass(); } - virtual const TypeNarrowPtr *is_same_narrowptr(const Type *t) const { - return t->is_narrowklass(); + const TypeNarrowPtr* as_same_narrowptr(const Type* t) const override { + return t->as_narrowklass(); } - virtual const TypeNarrowPtr *make_same_narrowptr(const TypePtr *t) const { + const TypeNarrowPtr* make_same_narrowptr(const TypePtr* t) const override { return new TypeNarrowKlass(t); } - virtual const TypeNarrowPtr *make_hash_same_narrowptr(const TypePtr *t) const { + const TypeNarrowPtr* make_hash_same_narrowptr(const TypePtr* t) const override { return (const TypeNarrowPtr*)((new TypeNarrowKlass(t))->hashcons()); } @@ -2257,7 +2323,7 @@ class TypeNarrowKlass : public TypeNarrowPtr { static const TypeNarrowKlass *NULL_PTR; #ifndef PRODUCT - virtual void dump2( Dict &d, uint depth, outputStream *st ) const; + void dump2(Dict& d, uint depth, outputStream* st) const override; #endif }; @@ -2323,10 +2389,9 @@ class TypeFunc : public Type { // Convenience common pre-built types. }; -//------------------------------accessors-------------------------------------- inline bool Type::is_ptr_to_narrowoop() const { #ifdef _LP64 - return (isa_oopptr() != nullptr && is_oopptr()->is_ptr_to_narrowoop_nv()); + return is_oopptr() && as_oopptr()->is_ptr_to_narrowoop_nv(); #else return false; #endif @@ -2334,7 +2399,7 @@ inline bool Type::is_ptr_to_narrowoop() const { inline bool Type::is_ptr_to_narrowklass() const { #ifdef _LP64 - return (isa_oopptr() != nullptr && is_oopptr()->is_ptr_to_narrowklass_nv()); + return is_oopptr() && as_oopptr()->is_ptr_to_narrowklass_nv(); #else return false; #endif @@ -2355,270 +2420,335 @@ inline double Type::getd() const { return ((TypeD*)this)->_d; } -inline const TypeInteger *Type::is_integer(BasicType bt) const { - assert((bt == T_INT && _base == Int) || (bt == T_LONG && _base == Long), "Not an Int"); - return (TypeInteger*)this; +template +const T* Type::as(bool (Type::*is_xxx)() const, const char* expected) const { +#ifdef ASSERT + if (!(this->*is_xxx)()) { + stringStream ss; + dump_on(&ss); + assert((this->*is_xxx)(), "Not %s, got %s", expected, ss.as_string()); + } +#endif + return static_cast(this); +} + +inline bool Type::is_int() const { + return _base == Int; } -inline const TypeInteger *Type::isa_integer(BasicType bt) const { - return (((bt == T_INT && _base == Int) || (bt == T_LONG && _base == Long)) ? (TypeInteger*)this : nullptr); +inline const TypeInt* Type::isa_int() const { + return is_int() ? static_cast(this) : nullptr; } -inline const TypeInt *Type::is_int() const { - assert( _base == Int, "Not an Int" ); - return (TypeInt*)this; +inline const TypeInt* Type::as_int() const { + return as(&Type::is_int, "an Int"); } -inline const TypeInt *Type::isa_int() const { - return ( _base == Int ? (TypeInt*)this : nullptr); +inline bool Type::is_long() const { + return _base == Long; } -inline const TypeLong *Type::is_long() const { - assert( _base == Long, "Not a Long" ); - return (TypeLong*)this; +inline const TypeLong* Type::isa_long() const { + return is_long() ? static_cast(this) : nullptr; } -inline const TypeLong *Type::isa_long() const { - return ( _base == Long ? (TypeLong*)this : nullptr); +inline const TypeLong* Type::as_long() const { + return as(&Type::is_long, "a Long"); } -inline const TypeH* Type::isa_half_float() const { - return ((_base == HalfFloatTop || - _base == HalfFloatCon || - _base == HalfFloatBot) ? (TypeH*)this : nullptr); +inline bool Type::is_integer(BasicType bt) const { + return (bt == T_INT && _base == Int) || (bt == T_LONG && _base == Long); } -inline const TypeH* Type::is_half_float_constant() const { - assert( _base == HalfFloatCon, "Not a HalfFloat" ); - return (TypeH*)this; +inline const TypeInteger* Type::isa_integer(BasicType bt) const { + return is_integer(bt) ? static_cast(this) : nullptr; +} + +inline const TypeInteger* Type::as_integer(BasicType bt) const { + if (bt == T_INT) { + return as(&Type::is_int, "an Int"); + } + return as(&Type::is_long, "a Long"); +} + +inline bool Type::is_half_float() const { + return _base == HalfFloatTop || + _base == HalfFloatCon || + _base == HalfFloatBot; +} + +inline bool Type::is_half_float_constant() const { + return _base == HalfFloatCon; } inline const TypeH* Type::isa_half_float_constant() const { - return (_base == HalfFloatCon ? (TypeH*)this : nullptr); + return is_half_float_constant() ? static_cast(this) : nullptr; +} + +inline const TypeH* Type::as_half_float_constant() const { + return as(&Type::is_half_float_constant, "a HalfFloatCon"); +} + +inline bool Type::is_float() const { + return _base == FloatTop || + _base == FloatCon || + _base == FloatBot; +} + +inline bool Type::is_float_constant() const { + return _base == FloatCon; +} + +inline const TypeF* Type::isa_float_constant() const { + return is_float_constant() ? static_cast(this) : nullptr; +} + +inline const TypeF* Type::as_float_constant() const { + return as(&Type::is_float_constant, "a FloatCon"); +} + +inline bool Type::is_double() const { + return _base == DoubleTop || + _base == DoubleCon || + _base == DoubleBot; +} + +inline bool Type::is_double_constant() const { + return _base == DoubleCon; +} + +inline const TypeD* Type::isa_double_constant() const { + return is_double_constant() ? static_cast(this) : nullptr; +} + +inline const TypeD* Type::as_double_constant() const { + return as(&Type::is_double_constant, "a DoubleCon"); +} + +inline bool Type::is_tuple() const { + return _base == Tuple; } -inline const TypeF *Type::isa_float() const { - return ((_base == FloatTop || - _base == FloatCon || - _base == FloatBot) ? (TypeF*)this : nullptr); +inline const TypeTuple* Type::as_tuple() const { + return as(&Type::is_tuple, "a Tuple"); } -inline const TypeF *Type::is_float_constant() const { - assert( _base == FloatCon, "Not a Float" ); - return (TypeF*)this; +inline bool Type::is_ary() const { + return _base == Array; } -inline const TypeF *Type::isa_float_constant() const { - return ( _base == FloatCon ? (TypeF*)this : nullptr); +inline const TypeAry* Type::isa_ary() const { + return is_ary() ? static_cast(this) : nullptr; } -inline const TypeD *Type::isa_double() const { - return ((_base == DoubleTop || - _base == DoubleCon || - _base == DoubleBot) ? (TypeD*)this : nullptr); +inline const TypeAry* Type::as_ary() const { + return as(&Type::is_ary, "an Array"); } -inline const TypeD *Type::is_double_constant() const { - assert( _base == DoubleCon, "Not a Double" ); - return (TypeD*)this; +inline bool Type::is_vect() const { + return _base >= VectorMask && _base <= VectorZ; } -inline const TypeD *Type::isa_double_constant() const { - return ( _base == DoubleCon ? (TypeD*)this : nullptr); +inline const TypeVect* Type::isa_vect() const { + return is_vect() ? static_cast(this) : nullptr; } -inline const TypeTuple *Type::is_tuple() const { - assert( _base == Tuple, "Not a Tuple" ); - return (TypeTuple*)this; +inline const TypeVect* Type::as_vect() const { + return as(&Type::is_vect, "a Vector"); } -inline const TypeAry *Type::is_ary() const { - assert( _base == Array , "Not an Array" ); - return (TypeAry*)this; +inline bool Type::is_pvectmask() const { + return _base == VectorMask; } -inline const TypeAry *Type::isa_ary() const { - return ((_base == Array) ? (TypeAry*)this : nullptr); +inline const TypePVectMask* Type::isa_pvectmask() const { + return is_pvectmask() ? static_cast(this) : nullptr; } -inline const TypePVectMask *Type::is_pvectmask() const { - assert( _base == VectorMask, "Not a Vector Mask" ); - return (TypePVectMask*)this; +inline const TypePVectMask* Type::as_pvectmask() const { + return as(&Type::is_pvectmask, "a Vector Mask"); } -inline const TypePVectMask *Type::isa_pvectmask() const { - return (_base == VectorMask) ? (TypePVectMask*)this : nullptr; +inline bool Type::is_ptr() const { + // AnyPtr is the first Ptr and AryKlassPtr the last, with no non-ptrs between. + return _base >= AnyPtr && _base <= AryKlassPtr; } -inline const TypeVect *Type::is_vect() const { - assert( _base >= VectorMask && _base <= VectorZ, "Not a Vector" ); - return (TypeVect*)this; +inline const TypePtr* Type::isa_ptr() const { + return is_ptr() ? static_cast(this) : nullptr; } -inline const TypeVect *Type::isa_vect() const { - return (_base >= VectorMask && _base <= VectorZ) ? (TypeVect*)this : nullptr; +inline const TypePtr* Type::as_ptr() const { + return as(&Type::is_ptr, "a pointer"); } -inline const TypePtr *Type::is_ptr() const { - // AnyPtr is the first Ptr and KlassPtr the last, with no non-ptrs between. - assert(_base >= AnyPtr && _base <= AryKlassPtr, "Not a pointer"); - return (TypePtr*)this; +inline bool Type::is_rawptr() const { + return _base == RawPtr; } -inline const TypePtr *Type::isa_ptr() const { - // AnyPtr is the first Ptr and KlassPtr the last, with no non-ptrs between. - return (_base >= AnyPtr && _base <= AryKlassPtr) ? (TypePtr*)this : nullptr; +inline const TypeRawPtr* Type::isa_rawptr() const { + return is_rawptr() ? static_cast(this) : nullptr; } -inline const TypeOopPtr *Type::is_oopptr() const { - // OopPtr is the first and KlassPtr the last, with no non-oops between. - assert(_base >= OopPtr && _base <= AryPtr, "Not a Java pointer" ) ; - return (TypeOopPtr*)this; +inline const TypeRawPtr* Type::as_rawptr() const { + return as(&Type::is_rawptr, "a raw pointer"); } -inline const TypeOopPtr *Type::isa_oopptr() const { - // OopPtr is the first and KlassPtr the last, with no non-oops between. - return (_base >= OopPtr && _base <= AryPtr) ? (TypeOopPtr*)this : nullptr; +inline bool Type::is_narrowoop() const { + return _base == NarrowOop; } -inline const TypeRawPtr *Type::isa_rawptr() const { - return (_base == RawPtr) ? (TypeRawPtr*)this : nullptr; +inline const TypeNarrowOop* Type::isa_narrowoop() const { + return is_narrowoop() ? static_cast(this) : nullptr; } -inline const TypeRawPtr *Type::is_rawptr() const { - assert( _base == RawPtr, "Not a raw pointer" ); - return (TypeRawPtr*)this; +inline const TypeNarrowOop* Type::as_narrowoop() const { + return as(&Type::is_narrowoop, "a narrow oop"); } -inline const TypeInstPtr *Type::isa_instptr() const { - return (_base == InstPtr) ? (TypeInstPtr*)this : nullptr; +inline bool Type::is_narrowklass() const { + return _base == NarrowKlass; } -inline const TypeInstPtr *Type::is_instptr() const { - assert( _base == InstPtr, "Not an object pointer" ); - return (TypeInstPtr*)this; +inline const TypeNarrowKlass* Type::isa_narrowklass() const { + return is_narrowklass() ? static_cast(this) : nullptr; } -inline const TypeAryPtr *Type::isa_aryptr() const { - return (_base == AryPtr) ? (TypeAryPtr*)this : nullptr; +inline const TypeNarrowKlass* Type::as_narrowklass() const { + return as(&Type::is_narrowklass, "a narrow klass"); } -inline const TypeAryPtr *Type::is_aryptr() const { - assert( _base == AryPtr, "Not an array pointer" ); - return (TypeAryPtr*)this; +inline bool Type::is_oopptr() const { + // OopPtr is the first and AryPtr the last, with no non-oops between. + return _base >= OopPtr && _base <= AryPtr; } -inline const TypeNarrowOop *Type::is_narrowoop() const { - // OopPtr is the first and KlassPtr the last, with no non-oops between. - assert(_base == NarrowOop, "Not a narrow oop" ) ; - return (TypeNarrowOop*)this; +inline const TypeOopPtr* Type::isa_oopptr() const { + return is_oopptr() ? static_cast(this) : nullptr; } -inline const TypeNarrowOop *Type::isa_narrowoop() const { - // OopPtr is the first and KlassPtr the last, with no non-oops between. - return (_base == NarrowOop) ? (TypeNarrowOop*)this : nullptr; +inline const TypeOopPtr* Type::as_oopptr() const { + return as(&Type::is_oopptr, "a Java pointer"); } -inline const TypeNarrowKlass *Type::is_narrowklass() const { - assert(_base == NarrowKlass, "Not a narrow oop" ) ; - return (TypeNarrowKlass*)this; +inline bool Type::is_instptr() const { + return _base == InstPtr; } -inline const TypeNarrowKlass *Type::isa_narrowklass() const { - return (_base == NarrowKlass) ? (TypeNarrowKlass*)this : nullptr; +inline const TypeInstPtr* Type::isa_instptr() const { + return is_instptr() ? static_cast(this) : nullptr; } -inline const TypeMetadataPtr *Type::is_metadataptr() const { - // MetadataPtr is the first and CPCachePtr the last - assert(_base == MetadataPtr, "Not a metadata pointer" ) ; - return (TypeMetadataPtr*)this; +inline const TypeInstPtr* Type::as_instptr() const { + return as(&Type::is_instptr, "an object pointer"); } -inline const TypeMetadataPtr *Type::isa_metadataptr() const { - return (_base == MetadataPtr) ? (TypeMetadataPtr*)this : nullptr; +inline bool Type::is_aryptr() const { + return _base == AryPtr; } -inline const TypeKlassPtr *Type::isa_klassptr() const { - return (_base >= KlassPtr && _base <= AryKlassPtr ) ? (TypeKlassPtr*)this : nullptr; +inline const TypeAryPtr* Type::isa_aryptr() const { + return is_aryptr() ? static_cast(this) : nullptr; } -inline const TypeKlassPtr *Type::is_klassptr() const { - assert(_base >= KlassPtr && _base <= AryKlassPtr, "Not a klass pointer"); - return (TypeKlassPtr*)this; +inline const TypeAryPtr* Type::as_aryptr() const { + return as(&Type::is_aryptr, "an array pointer"); } -inline const TypeInstKlassPtr *Type::isa_instklassptr() const { - return (_base == InstKlassPtr) ? (TypeInstKlassPtr*)this : nullptr; +inline bool Type::is_metadataptr() const { + return _base == MetadataPtr; } -inline const TypeInstKlassPtr *Type::is_instklassptr() const { - assert(_base == InstKlassPtr, "Not a klass pointer"); - return (TypeInstKlassPtr*)this; +inline const TypeMetadataPtr* Type::isa_metadataptr() const { + return is_metadataptr() ? static_cast(this) : nullptr; } -inline const TypeAryKlassPtr *Type::isa_aryklassptr() const { - return (_base == AryKlassPtr) ? (TypeAryKlassPtr*)this : nullptr; +inline const TypeMetadataPtr* Type::as_metadataptr() const { + return as(&Type::is_metadataptr, "a metadata pointer"); } -inline const TypeAryKlassPtr *Type::is_aryklassptr() const { - assert(_base == AryKlassPtr, "Not a klass pointer"); - return (TypeAryKlassPtr*)this; +inline bool Type::is_klassptr() const { + return _base >= KlassPtr && _base <= AryKlassPtr; +} + +inline const TypeKlassPtr* Type::isa_klassptr() const { + return is_klassptr() ? static_cast(this) : nullptr; +} + +inline const TypeKlassPtr* Type::as_klassptr() const { + return as(&Type::is_klassptr, "a klass pointer"); +} + +inline bool Type::is_instklassptr() const { + return _base == InstKlassPtr; +} + +inline const TypeInstKlassPtr* Type::isa_instklassptr() const { + return is_instklassptr() ? static_cast(this) : nullptr; +} + +inline const TypeInstKlassPtr* Type::as_instklassptr() const { + return as(&Type::is_instklassptr, "an instance klass pointer"); +} + +inline bool Type::is_aryklassptr() const { + return _base == AryKlassPtr; +} + +inline const TypeAryKlassPtr* Type::isa_aryklassptr() const { + return is_aryklassptr() ? static_cast(this) : nullptr; +} + +inline const TypeAryKlassPtr* Type::as_aryklassptr() const { + return as(&Type::is_aryklassptr, "an array klass pointer"); } inline const TypePtr* Type::make_ptr() const { - return (_base == NarrowOop) ? is_narrowoop()->get_ptrtype() : - ((_base == NarrowKlass) ? is_narrowklass()->get_ptrtype() : - isa_ptr()); + return is_narrowoop() + ? as_narrowoop()->get_ptrtype() + : (is_narrowklass() + ? as_narrowklass()->get_ptrtype() + : isa_ptr()); } inline const TypeOopPtr* Type::make_oopptr() const { - return (_base == NarrowOop) ? is_narrowoop()->get_ptrtype()->isa_oopptr() : isa_oopptr(); + return is_narrowoop() ? as_narrowoop()->get_ptrtype()->isa_oopptr() : isa_oopptr(); } inline const TypeNarrowOop* Type::make_narrowoop() const { - return (_base == NarrowOop) ? is_narrowoop() : - (isa_ptr() ? TypeNarrowOop::make(is_ptr()) : nullptr); + return is_narrowoop() + ? as_narrowoop() + : (is_ptr() ? TypeNarrowOop::make(as_ptr()) : nullptr); } inline const TypeNarrowKlass* Type::make_narrowklass() const { - return (_base == NarrowKlass) ? is_narrowklass() : - (isa_ptr() ? TypeNarrowKlass::make(is_ptr()) : nullptr); + return is_narrowklass() + ? as_narrowklass() + : (is_ptr() ? TypeNarrowKlass::make(as_ptr()) : nullptr); } inline bool Type::is_floatingpoint() const { - if( (_base == HalfFloatCon) || (_base == HalfFloatBot) || - (_base == FloatCon) || (_base == FloatBot) || - (_base == DoubleCon) || (_base == DoubleBot) ) - return true; - return false; + return _base == HalfFloatCon || _base == HalfFloatBot || + _base == FloatCon || _base == FloatBot || + _base == DoubleCon || _base == DoubleBot; } inline bool Type::is_valueklassptr() const { - return isa_instptr() != nullptr && is_instptr()->instance_klass()->is_value_klass(); + return is_instptr() && as_instptr()->instance_klass()->is_value_klass(); } inline ciValueKlass* Type::value_klass() const { - return make_ptr()->is_instptr()->instance_klass()->as_value_klass(); -} - -template <> -inline const TypeInt* Type::cast() const { - return is_int(); -} - -template <> -inline const TypeLong* Type::cast() const { - return is_long(); + return make_ptr()->as_instptr()->instance_klass()->as_value_klass(); } -template <> -inline const TypeInt* Type::try_cast() const { - return isa_int(); -} - -template <> -inline const TypeLong* Type::try_cast() const { - return isa_long(); +template +const T* Type::cast() const { + static_assert(std::is_same_v || std::is_same_v); + if constexpr (std::is_same_v) { + return as_int(); + } else { + return as_long(); + } } // =============================================================== @@ -2630,6 +2760,7 @@ inline const TypeLong* Type::try_cast() const { // For type queries and asserts #define is_intptr_t is_long #define isa_intptr_t isa_long +#define as_intptr_t as_long #define find_intptr_t_type find_long_type #define find_intptr_t_con find_long_con #define TypeX TypeLong @@ -2678,6 +2809,7 @@ inline const TypeLong* Type::try_cast() const { // For type queries and asserts #define is_intptr_t is_int #define isa_intptr_t isa_int +#define as_intptr_t as_int #define find_intptr_t_type find_int_type #define find_intptr_t_con find_int_con #define TypeX TypeInt diff --git a/src/hotspot/share/opto/typejavaptr.hpp b/src/hotspot/share/opto/typejavaptr.hpp index 752c4324cae2..1d0048eaccf9 100644 --- a/src/hotspot/share/opto/typejavaptr.hpp +++ b/src/hotspot/share/opto/typejavaptr.hpp @@ -77,9 +77,9 @@ class TypeJavaPtrMeetHelper { return OopType::InstType::make(ptr, OopType::ciEnv::current()->Object_klass(), interfaces, false, nullptr, offset, flat_in_array, TypeOopPtr::InstanceBot, speculative, inline_depth); } else if (base1 == Type::InstPtr) { - return instptr_type_xmeet(t1->is_instptr(), t2->is_instptr(), offset, interfaces, flat_in_array, instance_id, speculative, inline_depth); + return instptr_type_xmeet(t1->as_instptr(), t2->as_instptr(), offset, interfaces, flat_in_array, instance_id, speculative, inline_depth); } else { - return aryptr_type_xmeet(t1->is_aryptr(), t2->is_aryptr(), offset, instance_id, speculative, inline_depth); + return aryptr_type_xmeet(t1->as_aryptr(), t2->as_aryptr(), offset, instance_id, speculative, inline_depth); } } @@ -128,7 +128,7 @@ class TypeJavaPtrMeetHelper { KlassType klass = nullptr; meet_ary_elem(elem, klass, t1, t2); - auto size = t1->size()->meet(t2->size())->is_int(); + auto size = t1->size()->meet(t2->size())->as_int(); bool stable = t1->is_stable() && t2->is_stable(); bool flat = t1->is_flat() && t2->is_flat(); bool not_flat = t1->is_not_flat() && t2->is_not_flat(); @@ -163,9 +163,9 @@ class TypeJavaPtrMeetHelper { TypePtr::PTR ptr = t1->ptr() == TypePtr::BotPTR || t2->ptr() == TypePtr::BotPTR ? TypePtr::BotPTR : TypePtr::NotNull; return KlassType::InstType::make(ptr, KlassType::ciEnv::current()->Object_klass(), interfaces, offset, flat_in_array); } else if (base1 == Type::InstKlassPtr) { - return instklassptr_type_xmeet(t1->is_instklassptr(), t2->is_instklassptr(), offset, interfaces, flat_in_array); + return instklassptr_type_xmeet(t1->as_instklassptr(), t2->as_instklassptr(), offset, interfaces, flat_in_array); } else { - return aryklassptr_type_xmeet(t1->is_aryklassptr(), t2->is_aryklassptr(), offset); + return aryklassptr_type_xmeet(t1->as_aryklassptr(), t2->as_aryklassptr(), offset); } } @@ -226,7 +226,7 @@ class TypeJavaPtrMeetHelper { } else if (s2 == nullptr) { s2 = t2; } - return s1->meet(s2)->is_ptr(); + return s1->meet(s2)->as_ptr(); } template @@ -328,8 +328,8 @@ class TypeJavaPtrMeetHelper { return false; } - decltype(t1->is_oopptr()) exact_type; - decltype(t1->is_oopptr()) other_type; + decltype(t1->as_oopptr()) exact_type; + decltype(t1->as_oopptr()) other_type; bool both_are_exact; if (t1->klass_is_exact()) { exact_type = t1; @@ -350,8 +350,8 @@ class TypeJavaPtrMeetHelper { return true; } - auto exact_klass = exact_type->is_instptr()->instance_klass(); - auto other_klass = other_type->is_instptr()->instance_klass(); + auto exact_klass = exact_type->as_instptr()->instance_klass(); + auto other_klass = other_type->as_instptr()->instance_klass(); if (both_are_exact) { return exact_klass != other_klass || exact_type->interfaces() != other_type->interfaces(); } else { @@ -361,13 +361,13 @@ class TypeJavaPtrMeetHelper { } if (other_type->base() == Type::InstPtr) { - auto other_inst_type = other_type->is_instptr(); + auto other_inst_type = other_type->as_instptr(); return both_are_exact || !other_inst_type->instance_klass()->is_java_lang_Object() || !AryOopType::_array_interfaces->contains(other_inst_type->interfaces()); } - auto exact_ary_type = exact_type->is_aryptr(); - auto other_ary_type = other_type->is_aryptr(); + auto exact_ary_type = exact_type->as_aryptr(); + auto other_ary_type = other_type->as_aryptr(); if (both_are_exact) { if (exact_ary_type->is_flat() != other_ary_type->is_flat() || exact_ary_type->is_not_flat() != other_ary_type->is_not_flat() || exact_ary_type->is_not_null_free() != other_ary_type->is_not_null_free() || exact_ary_type->is_atomic() != other_ary_type->is_atomic()) { @@ -388,8 +388,8 @@ class TypeJavaPtrMeetHelper { } if (exact_elem->make_ptr() != nullptr && other_elem->make_ptr() != nullptr) { - exact_type = exact_elem->make_ptr()->is_oopptr(); - other_type = other_elem->make_ptr()->is_oopptr(); + exact_type = exact_elem->make_ptr()->as_oopptr(); + other_type = other_elem->make_ptr()->as_oopptr(); continue; } @@ -453,11 +453,11 @@ class TypeJavaPtrJoinHelper { const typename OopType::InstType* inst_type; const typename OopType::AryType* ary_type; if (base1 == Type::InstPtr) { - inst_type = t1->is_instptr(); - ary_type = t2->is_aryptr(); + inst_type = t1->as_instptr(); + ary_type = t2->as_aryptr(); } else { - inst_type = t2->is_instptr(); - ary_type = t1->is_aryptr(); + inst_type = t2->as_instptr(); + ary_type = t1->as_aryptr(); } TypePtr::PTR ptr = join_ptr(t1, t2); @@ -470,9 +470,9 @@ class TypeJavaPtrJoinHelper { return OopType::PtrType::make(Type::AnyPtr, join_ptr_with_null(ptr), offset, speculative, inline_depth); } } else if (base1 == Type::InstPtr) { - return instptr_type_xjoin(t1->is_instptr(), t2->is_instptr(), offset, interfaces, flat_in_array, instance_id, speculative, inline_depth); + return instptr_type_xjoin(t1->as_instptr(), t2->as_instptr(), offset, interfaces, flat_in_array, instance_id, speculative, inline_depth); } else { - return aryptr_type_xjoin(t1->is_aryptr(), t2->is_aryptr(), offset, instance_id, speculative, inline_depth); + return aryptr_type_xjoin(t1->as_aryptr(), t2->as_aryptr(), offset, instance_id, speculative, inline_depth); } } @@ -612,11 +612,11 @@ class TypeJavaPtrJoinHelper { const typename KlassType::InstType* inst_type; const typename KlassType::AryType* ary_type; if (base1 == Type::InstKlassPtr) { - inst_type = t1->is_instklassptr(); - ary_type = t2->is_aryklassptr(); + inst_type = t1->as_instklassptr(); + ary_type = t2->as_aryklassptr(); } else { - inst_type = t2->is_instklassptr(); - ary_type = t1->is_aryklassptr(); + inst_type = t2->as_instklassptr(); + ary_type = t1->as_aryklassptr(); } TypePtr::PTR ptr = join_ptr(t1, t2); @@ -629,9 +629,9 @@ class TypeJavaPtrJoinHelper { return KlassType::PtrType::make(Type::AnyPtr, join_ptr_with_null(ptr), offset); } } else if (base1 == Type::InstKlassPtr) { - return instklassptr_type_xjoin(t1->is_instklassptr(), t2->is_instklassptr(), offset, interfaces, flat_in_array); + return instklassptr_type_xjoin(t1->as_instklassptr(), t2->as_instklassptr(), offset, interfaces, flat_in_array); } else { - return aryklassptr_type_xjoin(t1->is_aryklassptr(), t2->is_aryklassptr(), offset); + return aryklassptr_type_xjoin(t1->as_aryklassptr(), t2->as_aryklassptr(), offset); } } @@ -761,7 +761,7 @@ class TypeJavaPtrJoinHelper { } else if (s2 == nullptr) { s2 = t2; } - return s1->join(s2)->is_ptr(); + return s1->join(s2)->as_ptr(); } template diff --git a/src/hotspot/share/opto/valuetypenode.cpp b/src/hotspot/share/opto/valuetypenode.cpp index e8503aa505ce..7f92bf3c5752 100644 --- a/src/hotspot/share/opto/valuetypenode.cpp +++ b/src/hotspot/share/opto/valuetypenode.cpp @@ -335,7 +335,7 @@ void ValueTypeNode::make_scalar_in_safepoint(PhaseIterGVN* igvn, Unique_Node_Lis uint nfields = add_fields_to_safepoint(worklist, sfpt); jvms->set_endoff(sfpt->req()); // Replace safepoint edge by SafePointScalarObjectNode - SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(type()->isa_instptr(), + SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(type()->as_instptr(), nullptr, first_ind, sfpt->jvms()->depth(), @@ -380,7 +380,7 @@ bool ValueTypeNode::make_scalar_in_safepoints(PhaseIterGVN* igvn, bool allow_oop } } else { use_oop = allow_oop && is_allocated(igvn) && - (oop->is_Con() || oop->is_Parm() || oop->is_Load() || (oop->isa_DecodeN() && oop->in(1)->is_Load())); + (oop->is_Con() || oop->is_Parm() || oop->is_Load() || (oop->is_DecodeN() && oop->in(1)->is_Load())); } ResourceMark rm; @@ -465,7 +465,7 @@ void ValueTypeNode::load(GraphKit* kit, Node* base, Node* ptr, bool immutable_me if (trust_null_free_oop && field_null_free) { val_type = val_type->join_speculative(TypePtr::NOTNULL); } - const TypePtr* field_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(field_ptr)->is_ptr() : TypeRawPtr::BOTTOM; + const TypePtr* field_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(field_ptr)->as_ptr() : TypeRawPtr::BOTTOM; value = kit->access_load_at(base, field_ptr, field_ptr_type, val_type, bt, decorators); } set_field_value(i, value); @@ -488,7 +488,7 @@ void ValueTypeNode::store_flat(GraphKit* kit, Node* base, Node* ptr, bool atomic if (!null_free) { int nm_offset = vk->null_marker_offset_in_payload(); Node* nm_ptr = kit->basic_plus_adr(base, ptr, nm_offset); - const TypePtr* nm_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(nm_ptr)->is_ptr() : TypeRawPtr::BOTTOM; + const TypePtr* nm_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(nm_ptr)->as_ptr() : TypeRawPtr::BOTTOM; kit->access_store_at(base, nm_ptr, nm_ptr_type, get_null_marker(), TypeInt::BOOL, T_BOOLEAN, decorators); } store(kit, base, ptr, immutable_memory, decorators); @@ -634,7 +634,7 @@ void ValueTypeNode::store(GraphKit* kit, Node* base, Node* ptr, bool immutable_m } else { // Store field value to memory BasicType bt = type2field[ft->basic_type()]; - const TypePtr* field_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(field_ptr)->is_ptr() : TypeRawPtr::BOTTOM; + const TypePtr* field_ptr_type = (decorators & C2_MISMATCHED) == 0 ? kit->gvn().type(field_ptr)->as_ptr() : TypeRawPtr::BOTTOM; const Type* val_type = Type::get_const_type(ft); kit->access_store_at(base, field_ptr, field_ptr_type, field_val, val_type, bt, decorators); } @@ -690,8 +690,8 @@ bool ValueTypeNode::can_emit_substitutability_check(PhaseGVN* phase, Node* lhs, return false; } - if (!lhs->bottom_type()->isa_ptr() || - (rhs != nullptr && !rhs->bottom_type()->isa_ptr())) { + if (!lhs->bottom_type()->is_ptr() || + (rhs != nullptr && !rhs->bottom_type()->is_ptr())) { return false; } @@ -699,12 +699,12 @@ bool ValueTypeNode::can_emit_substitutability_check(PhaseGVN* phase, Node* lhs, return true; } - if (!lhs->bottom_type()->is_ptr()->can_be_value_type() || - (rhs != nullptr && !rhs->bottom_type()->is_ptr()->can_be_value_type())) { + if (!lhs->bottom_type()->as_ptr()->can_be_value_type() || + (rhs != nullptr && !rhs->bottom_type()->as_ptr()->can_be_value_type())) { return true; } - if (!lhs->is_ValueType() && (rhs == nullptr || !rhs->is_ValueType())) { + if (!lhs->is_ValueType() && !is(rhs)) { return false; } @@ -713,7 +713,7 @@ bool ValueTypeNode::can_emit_substitutability_check(PhaseGVN* phase, Node* lhs, } ValueTypeNode* lhs_value = lhs->as_ValueType(); - ValueTypeNode* rhs_value = rhs != nullptr ? rhs->isa_ValueType() : nullptr; + ValueTypeNode* rhs_value = isa(rhs); if (rhs_value != nullptr && lhs_value->type()->value_klass() != rhs_value->type()->value_klass()) { // Dead code, can skip the substitutability check return true; @@ -788,10 +788,10 @@ static Node* emit_substitutability_check_pointer(GraphKit* kit, PhiNode* result, Node* cmp = nullptr; if (same_oop(&gvn, lhs, rhs)) { cmp = kit->intcon(0); - } else if (!lhs_type->is_ptr()->can_be_value_type() || !rhs_type->is_ptr()->can_be_value_type()) { + } else if (!lhs_type->as_ptr()->can_be_value_type() || !rhs_type->as_ptr()->can_be_value_type()) { // If one of the sides is not a value object, can only be substitutable if they are the same cmp = kit->CmpP(lhs, rhs); - } else if (lhs_type->is_instptr()->as_klass_type()->join(rhs_type->is_instptr()->as_klass_type())->empty()) { + } else if (lhs_type->as_instptr()->as_klass_type()->join(rhs_type->as_instptr()->as_klass_type())->empty()) { // Both belongs to provably different types, must be different unless both are null. Cannot // rely on the pointer independence alone because different pointers may still be // substitutable. @@ -850,7 +850,7 @@ Node* ValueTypeNode::emit_substitutability_check(GraphKit* kit, Node* lhs, Node* const Type* rhs_type = igvn.type(rhs); assert(!lhs_type->maybe_null() && !rhs_type->maybe_null(), "must check null beforehand"); ciValueKlass* vk = lhs_type->is_valueklassptr() ? lhs_type->value_klass() : rhs_type->value_klass(); - const TypeInstPtr* vk_type = TypeOopPtr::make_from_klass(vk)->join(TypePtr::NOTNULL)->is_instptr(); + const TypeInstPtr* vk_type = TypeOopPtr::make_from_klass(vk)->join(TypePtr::NOTNULL)->as_instptr(); if (!lhs->is_ValueType()) { if (!lhs_type->higher_equal(vk_type)) { @@ -1405,8 +1405,7 @@ static void replace_allocation(PhaseIterGVN* igvn, Node* res, Node* dom) { Node* ValueTypeNode::Ideal(PhaseGVN* phase, bool can_reshape) { Node* oop = get_oop(); - if (oop->isa_ValueType() && !phase->type(oop)->maybe_null()) { - ValueTypeNode* vtptr = oop->as_ValueType(); + if (ValueTypeNode* vtptr = oop->isa_ValueType(); vtptr != nullptr && !phase->type(oop)->maybe_null()) { assert(value_klass() == vtptr->value_klass(), "inconsistent types"); set_oop(*phase, vtptr->get_oop()); set_is_buffered(*phase); @@ -1449,7 +1448,7 @@ Node* ValueTypeNode::Ideal(PhaseGVN* phase, bool can_reshape) { if (alloc != nullptr && alloc->in(AllocateNode::ValueType) == this && !alloc->_is_scalar_replaceable) { // Found a re-allocation Node* res = alloc->result_cast(); - if (res != nullptr && res->is_CheckCastPP()) { + if (is(res)) { // Replace allocation by oop and unlink AllocateNode replace_allocation(igvn, res, oop); igvn->replace_input_of(alloc, AllocateNode::ValueType, igvn->C->top()); @@ -1613,7 +1612,7 @@ ValueTypeNode* ValueTypeNode::make_from_flat_impl(GraphKit* kit, ciValueKlass* v if (!null_free) { int nm_offset = vk->null_marker_offset_in_payload(); Node* nm_ptr = kit->basic_plus_adr(base, ptr, nm_offset); - const TypePtr* nm_ptr_type = (decorators & C2_MISMATCHED) == 0 ? gvn.type(nm_ptr)->is_ptr() : TypeRawPtr::BOTTOM; + const TypePtr* nm_ptr_type = (decorators & C2_MISMATCHED) == 0 ? gvn.type(nm_ptr)->as_ptr() : TypeRawPtr::BOTTOM; Node* nm_value = kit->access_load_at(base, nm_ptr, nm_ptr_type, TypeInt::BOOL, T_BOOLEAN, decorators); vt->set_req(NullMarker, nm_value); } @@ -1777,11 +1776,11 @@ Node* ValueTypeNode::is_loaded(PhaseGVN* phase, ciValueKlass* vk, Node* base, in } } } - if (value->isa_DecodeN()) { + if (value->is_DecodeN()) { // Skip DecodeN value = value->in(1); } - if (value->isa_Load()) { + if (value->is_Load()) { // Check if base and offset of field load matches value type layout intptr_t loffset = 0; Node* lbase = AddPNode::Ideal_base_and_offset(value->in(MemNode::Address), phase, loffset); @@ -1951,7 +1950,7 @@ void ValueTypeNode::remove_redundant_allocations(PhaseIdealLoop* phase) const { AllocateNode* alloc = fast_out(i)->isa_Allocate(); if (alloc != nullptr && alloc->in(AllocateNode::ValueType) == this && !alloc->_is_scalar_replaceable) { Node* res = alloc->result_cast(); - if (res == nullptr || !res->is_CheckCastPP()) { + if (!is(res)) { break; // No unique CheckCastPP } // Search for a dominating allocation of the same value type @@ -1960,7 +1959,7 @@ void ValueTypeNode::remove_redundant_allocations(PhaseIdealLoop* phase) const { AllocateNode* alloc_other = fast_out(j)->isa_Allocate(); if (alloc_other != nullptr && alloc_other->in(AllocateNode::ValueType) == this && !alloc_other->_is_scalar_replaceable) { Node* res_other = alloc_other->result_cast(); - if (res_other != nullptr && res_other->is_CheckCastPP() && res_other != res_dom && + if (is(res_other) && res_other != res_dom && phase->is_dominator(res_other->in(0), res_dom->in(0))) { res_dom = res_other; } @@ -2016,7 +2015,7 @@ const Type* ValueTypeNode::Value(PhaseGVN* phase) const { Node* oop = get_oop(); const Type* toop = phase->type(oop); #ifdef ASSERT - if (oop->is_Con() && toop->is_zero_type() && _type->isa_oopptr()->is_known_instance()) { + if (oop->is_Con() && toop->is_zero_type() && _type->as_oopptr()->is_known_instance()) { // We are not allocated (anymore) and should therefore not have an instance id dump(1); assert(false, "Unbuffered value type should not have known instance id"); @@ -2040,7 +2039,7 @@ const Type* ValueTypeNode::Value(PhaseGVN* phase) const { if (tinit == Type::TOP) { return Type::TOP; } - if (tinit->isa_int() && tinit->is_int()->is_con(1)) { + if (tinit->is_int() && tinit->as_int()->is_con(1)) { t = t->join_speculative(TypePtr::NOTNULL); } return t; @@ -2135,7 +2134,7 @@ bool LoadFlatNode::expand_non_atomic(PhaseIterGVN& igvn) const { ciField* field = _vk->nonstatic_field_at(i); Node* field_ptr = kit.basic_plus_adr(base, ptr, field->offset_in_bytes() - _vk->payload_offset()); - const TypePtr* field_ptr_type = field_ptr->Value(&igvn)->is_ptr(); + const TypePtr* field_ptr_type = field_ptr->Value(&igvn)->as_ptr(); igvn.set_type(field_ptr, field_ptr_type); Node* field_value = kit.access_load_at(base, field_ptr, field_ptr_type, igvn.type(proj_out), field->type()->basic_type(), _decorators); @@ -2146,7 +2145,7 @@ bool LoadFlatNode::expand_non_atomic(PhaseIterGVN& igvn) const { ProjNode* proj_out = proj_out_or_null(TypeFunc::Parms + _vk->nof_nonstatic_fields()); if (proj_out != nullptr) { Node* null_marker_ptr = kit.basic_plus_adr(base, ptr, _vk->null_marker_offset_in_payload()); - const TypePtr* null_marker_ptr_type = null_marker_ptr->Value(&igvn)->is_ptr(); + const TypePtr* null_marker_ptr_type = null_marker_ptr->Value(&igvn)->as_ptr(); igvn.set_type(null_marker_ptr, null_marker_ptr_type); Node* null_marker_value = kit.access_load_at(base, null_marker_ptr, null_marker_ptr_type, TypeInt::BOOL, T_BOOLEAN, _decorators); igvn.replace_node(proj_out, null_marker_value); @@ -2343,7 +2342,7 @@ bool StoreFlatNode::expand_non_atomic(PhaseIterGVN& igvn) const { for (int i = 0; i < vk->nof_nonstatic_fields(); i++) { ciField* field = vk->nonstatic_field_at(i); Node* field_ptr = kit.basic_plus_adr(base, ptr, field->offset_in_bytes() - vk->payload_offset()); - const TypePtr* field_ptr_type = field_ptr->Value(&igvn)->is_ptr(); + const TypePtr* field_ptr_type = field_ptr->Value(&igvn)->as_ptr(); igvn.set_type(field_ptr, field_ptr_type); Node* field_value = value->field_value_by_offset(field->offset_in_bytes(), true); kit.access_store_at(base, field_ptr, field_ptr_type, field_value, igvn.type(field_value), field->type()->basic_type(), _decorators); @@ -2351,7 +2350,7 @@ bool StoreFlatNode::expand_non_atomic(PhaseIterGVN& igvn) const { if (!_null_free) { Node* null_marker_ptr = kit.basic_plus_adr(base, ptr, vk->null_marker_offset_in_payload()); - const TypePtr* null_marker_ptr_type = null_marker_ptr->Value(&igvn)->is_ptr(); + const TypePtr* null_marker_ptr_type = null_marker_ptr->Value(&igvn)->as_ptr(); igvn.set_type(null_marker_ptr, null_marker_ptr_type); Node* null_marker_value = value->get_null_marker(); kit.access_store_at(base, null_marker_ptr, null_marker_ptr_type, null_marker_value, TypeInt::BOOL, T_BOOLEAN, _decorators); @@ -2383,17 +2382,22 @@ void StoreFlatNode::expand_atomic(PhaseIterGVN& igvn) const { int oop_off_1 = -1; int oop_off_2 = -1; - Node* payload = convert_to_payload(igvn, kit.control(), value, _null_free, oop_off_1, oop_off_2); + Node* oop_1 = igvn.C->top(); + Node* oop_2 = igvn.C->top(); + Node* payload = convert_to_payload(igvn, kit.control(), value, _null_free, oop_off_1, oop_1, oop_off_2, oop_2); ciValueKlass* vk = igvn.type(value)->value_klass(); // convert_to_payload should give us the offsets of up to 2 oops of vk in oop_off_1 and oop_off_2. The following holds: // - they must be valid offsets for oops (0 or 4) or -1 (no oop) // - if there is at least one oop, oop_off_1 != oop_off_2, i.e. oop_off_1 == oop_off_2 only if they are both -1, i.e. offsets are distincts // - in case there is only one oop, its offset is stored in oop_off_1, and oop_off_2 == -1 + // - oop_off_{i} == -1 <=> oop_{i} == nullptr; assert(oop_off_1 == -1 || oop_off_1 == 0 || oop_off_1 == 4, "invalid layout for %s, first oop at offset %d", vk->name()->as_utf8(), oop_off_1); assert(oop_off_2 == -1 || oop_off_2 == 0 || oop_off_2 == 4, "invalid layout for %s, second oop at offset %d", vk->name()->as_utf8(), oop_off_2); assert(oop_off_1 != oop_off_2 || oop_off_1 == -1, "we should have: oop_off_1 == oop_off_2 => oop_off_1 == -1. But oop_off_1=oop_off_2=%d", oop_off_1); assert(oop_off_1 != -1 || oop_off_2 == -1, "we should have: oop_off_1 == -1 => oop_off_2 == -1. But oop_off_1=%d, oop_off_2=%d", oop_off_1, oop_off_2); + assert((oop_off_1 == -1) == oop_1->is_top(), "oop_off_1 == -1 iff. oop_1 is top, but oop_off_1=%d, is oop_1 top=%d", oop_off_1, oop_1->is_top()); + assert((oop_off_2 == -1) == oop_2->is_top(), "oop_off_2 == -1 iff. oop_2 is top, but oop_off_2=%d, is oop_2 top=%d", oop_off_2, oop_2->is_top()); BasicType payload_bt = vk->atomic_size_to_basic_type(_null_free); kit.insert_mem_bar(Op_MemBarCPUOrder); if (!UseG1GC || oop_off_1 == -1) { @@ -2406,12 +2410,15 @@ void StoreFlatNode::expand_atomic(PhaseIterGVN& igvn) const { // Contains oops and requires late barrier expansion. Emit a special store node that allows to emit GC barriers in the backend. assert(UseG1GC, "Unexpected GC"); assert(payload_bt == T_LONG, "Unexpected payload type"); + Node* store_special = kit.access_store_at(base, ptr, TypeRawPtr::BOTTOM, payload, TypeLong::LONG, T_LONG, _decorators | C2_MISMATCHED | C2_SPECIAL_ACCESS, true, value); + assert(store_special->Opcode() == Op_StoreLSpecial, "must be special"); + // If one oop, set the offset (if no offset is set, two oops are assumed by the backend) - Node* oop_offset = (oop_off_2 == -1) ? igvn.intcon(oop_off_1) : nullptr; - Node* mem = kit.reset_memory(); - kit.set_all_memory(mem); - Node* store = igvn.transform(new StoreLSpecialNode(kit.control(), mem, ptr, TypeRawPtr::BOTTOM, payload, oop_offset, MemNode::unordered)); - kit.set_memory(store, TypeRawPtr::BOTTOM); + Node* oop_offset = (oop_off_2 == -1) ? igvn.intcon(oop_off_1) : igvn.C->top(); + store_special->add_req(oop_offset); + assert(!oop_1->is_top(), "if no oop, the store shouldn't be special"); + store_special->add_req(oop_1); + store_special->add_req(oop_2); } kit.insert_mem_bar(Op_MemBarCPUOrder); @@ -2427,9 +2434,11 @@ void StoreFlatNode::expand_atomic(PhaseIterGVN& igvn) const { } // Convert the field values to a payload value of type 'bt' -Node* StoreFlatNode::convert_to_payload(PhaseIterGVN& igvn, Node* ctrl, ValueTypeNode* value, bool null_free, int& oop_off_1, int& oop_off_2) { +Node* StoreFlatNode::convert_to_payload(PhaseIterGVN& igvn, Node* ctrl, ValueTypeNode* value, bool null_free, int& oop_off_1, Node*& oop_1, int& oop_off_2, Node*& oop_2) { oop_off_1 = -1; + oop_1 = igvn.C->top(); oop_off_2 = -1; + oop_2 = igvn.C->top(); ciValueKlass* vk = igvn.type(value)->value_klass(); BasicType payload_bt = vk->atomic_size_to_basic_type(null_free); Node* payload = igvn.zerocon(payload_bt); @@ -2463,6 +2472,12 @@ Node* StoreFlatNode::convert_to_payload(PhaseIterGVN& igvn, Node* ctrl, ValueTyp } field_value = igvn.transform(new EncodePNode(field_value, val_type)); + if (oop_1->is_top()) { + oop_1 = field_value; + } else { + assert(oop_2->is_top(), "already set"); + oop_2 = field_value; + } field_value = igvn.transform(new CastP2XNode(ctrl, field_value)); field_value = igvn.transform(new ConvL2INode(field_value)); field_bt = T_INT; diff --git a/src/hotspot/share/opto/valuetypenode.hpp b/src/hotspot/share/opto/valuetypenode.hpp index 2f3d6278a3c7..9bfabbb657f2 100644 --- a/src/hotspot/share/opto/valuetypenode.hpp +++ b/src/hotspot/share/opto/valuetypenode.hpp @@ -259,7 +259,7 @@ class StoreFlatNode final : public SafePointNode { Compile::current()->add_flat_access(this); } - static Node* convert_to_payload(PhaseIterGVN& igvn, Node* ctrl, ValueTypeNode* value, bool null_free, int& oop_off_1, int& oop_off_2); + static Node* convert_to_payload(PhaseIterGVN& igvn, Node* ctrl, ValueTypeNode* value, bool null_free, int& oop_off_1, Node*& oop_1, int& oop_off_2, Node*& oop_2); static Node* set_payload_value(PhaseIterGVN& igvn, BasicType payload_bt, Node* payload, BasicType val_bt, Node* value, int offset); }; diff --git a/src/hotspot/share/opto/vector.cpp b/src/hotspot/share/opto/vector.cpp index 1df70a236f4d..bcf86c11888d 100644 --- a/src/hotspot/share/opto/vector.cpp +++ b/src/hotspot/share/opto/vector.cpp @@ -282,7 +282,7 @@ void PhaseVector::scalarize_vbox_node(VectorBoxNode* vec_box) const { // targets. bool is_mask = is_vector_mask(iklass); if (is_mask && vec_value->Opcode() != Op_VectorStoreMask) { - const TypeVect* vt = vec_value->bottom_type()->is_vect(); + const TypeVect* vt = vec_value->bottom_type()->as_vect(); BasicType bt = vt->element_basic_type(); vec_value = gvn.transform(VectorStoreMaskNode::make(gvn, vec_value, bt, vt->length())); } @@ -382,11 +382,11 @@ Node* PhaseVector::expand_vbox_alloc_node(VectorBoxAllocateNode* vbox_alloc, // If boxed mask value is present in a predicate register, it must be // spilled to a vector though a VectorStoreMaskOperation before actual StoreVector // operation to vector payload field. - if (is_mask && (value->bottom_type()->isa_pvectmask() || bt != T_BOOLEAN)) { + if (is_mask && (value->bottom_type()->is_pvectmask() || bt != T_BOOLEAN)) { value = gvn.transform(VectorStoreMaskNode::make(gvn, value, bt, num_elem)); // Although type of mask depends on its definition, in terms of storage everything is stored in boolean array. bt = T_BOOLEAN; - assert(value->bottom_type()->is_vect()->element_basic_type() == bt, + assert(value->bottom_type()->as_vect()->element_basic_type() == bt, "must be consistent with mask representation"); } @@ -397,7 +397,7 @@ Node* PhaseVector::expand_vbox_alloc_node(VectorBoxAllocateNode* vbox_alloc, // Store the vector value into the array. // (The store should be captured by InitializeNode and turned into initialized store later.) Node* arr_adr = kit.array_element_address(arr, kit.intcon(0), bt); - const TypePtr* arr_adr_type = arr_adr->bottom_type()->is_ptr(); + const TypePtr* arr_adr_type = arr_adr->bottom_type()->as_ptr(); Node* arr_mem = kit.memory(arr_adr); Node* vstore = gvn.transform(StoreVectorNode::make(0, kit.control(), @@ -421,7 +421,7 @@ Node* PhaseVector::expand_vbox_alloc_node(VectorBoxAllocateNode* vbox_alloc, false); assert(field != nullptr, ""); Node* vec_field = kit.basic_plus_adr(vec_obj, field->offset_in_bytes()); - const TypePtr* vec_adr_type = vec_field->bottom_type()->is_ptr(); + const TypePtr* vec_adr_type = vec_field->bottom_type()->as_ptr(); // The store should be captured by InitializeNode and turned into initialized store later. Node* field_store = gvn.transform(kit.access_store_at(vec_obj, @@ -445,9 +445,9 @@ void PhaseVector::expand_vunbox_node(VectorUnboxNode* vec_unbox) { PhaseGVN& gvn = kit.gvn(); Node* obj = vec_unbox->obj(); - const TypeInstPtr* tinst = gvn.type(obj)->isa_instptr(); + const TypeInstPtr* tinst = gvn.type(obj)->as_instptr(); ciInstanceKlass* from_kls = tinst->instance_klass(); - const TypeVect* vt = vec_unbox->bottom_type()->is_vect(); + const TypeVect* vt = vec_unbox->bottom_type()->as_vect(); BasicType bt = vt->element_basic_type(); BasicType masktype = bt; @@ -467,7 +467,7 @@ void PhaseVector::expand_vunbox_node(VectorUnboxNode* vec_unbox) { Node* vec_field_ld; { DecoratorSet decorators = MO_UNORDERED | IN_HEAP; - C2AccessValuePtr addr(vec_adr, vec_adr->bottom_type()->is_ptr()); + C2AccessValuePtr addr(vec_adr, vec_adr->bottom_type()->as_ptr()); MergeMemNode* local_mem = MergeMemNode::make(mem); gvn.record_for_igvn(local_mem); BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); @@ -481,7 +481,7 @@ void PhaseVector::expand_vunbox_node(VectorUnboxNode* vec_unbox) { } Node* adr = kit.array_element_address(vec_field_ld, gvn.intcon(0), bt); - const TypePtr* adr_type = adr->bottom_type()->is_ptr(); + const TypePtr* adr_type = adr->bottom_type()->as_ptr(); int num_elem = vt->length(); Node* vec_val_load = LoadVectorNode::make(0, ctrl, diff --git a/src/hotspot/share/opto/vectorIntrinsics.cpp b/src/hotspot/share/opto/vectorIntrinsics.cpp index 3d413500ea73..0da22c6a1332 100644 --- a/src/hotspot/share/opto/vectorIntrinsics.cpp +++ b/src/hotspot/share/opto/vectorIntrinsics.cpp @@ -178,7 +178,7 @@ Node* GraphKit::unbox_vector(Node* v, const TypeInstPtr* vbox_type, BasicType el Node* mem = reset_memory(); set_all_memory(mem); Node* unbox = gvn().transform(new VectorUnboxNode(C, vt, ctrl, v, mem)); - if (gvn().type(unbox)->isa_vect() == nullptr) { + if (!gvn().type(unbox)->is_vect()) { assert(gvn().type(unbox) == Type::TOP, "sanity"); return nullptr; // not a vector } @@ -686,7 +686,7 @@ bool LibraryCallKit::inline_vector_mask_operation() { return false; } - if (!Matcher::mask_op_prefers_predicate(mopc, mask_vec->bottom_type()->is_vect())) { + if (!Matcher::mask_op_prefers_predicate(mopc, mask_vec->bottom_type()->as_vect())) { mask_vec = gvn().transform(VectorStoreMaskNode::make(gvn(), mask_vec, elem_bt, num_elem)); } const Type* maskoper_ty = mopc == Op_VectorMaskToLong ? (const Type*)TypeLong::LONG : (const Type*)TypeInt::INT; @@ -914,7 +914,7 @@ bool LibraryCallKit::inline_vector_mem_operation(bool is_store) { // This is not 1-1 implementation. const Type *const base_type = gvn().type(base); - const TypePtr *addr_type = gvn().type(addr)->isa_ptr(); + const TypePtr* addr_type = gvn().type(addr)->as_ptr(); const TypeAryPtr* arr_type = addr_type->isa_aryptr(); const bool in_native = TypePtr::NULL_PTR == base_type; // base always null @@ -922,7 +922,7 @@ bool LibraryCallKit::inline_vector_mem_operation(bool is_store) { const bool is_mixed_access = !in_heap && !in_native; - const bool is_mismatched_access = in_heap && (addr_type->isa_aryptr() == nullptr); + const bool is_mismatched_access = in_heap && !addr_type->is_aryptr(); const bool needs_cpu_membar = is_mixed_access || is_mismatched_access; @@ -996,7 +996,7 @@ bool LibraryCallKit::inline_vector_mem_operation(bool is_store) { if (mismatched_ms) { store_num_elem = mem_num_elem; const TypeVect* to_vect_type = TypeVect::make(mem_elem_bt, store_num_elem); - val = gvn().transform(new VectorReinterpretNode(val, val->bottom_type()->is_vect(), to_vect_type)); + val = gvn().transform(new VectorReinterpretNode(val, val->bottom_type()->as_vect(), to_vect_type)); } if (is_mask) { val = gvn().transform(VectorStoreMaskNode::make(gvn(), val, elem_bt, num_elem)); @@ -1009,7 +1009,7 @@ bool LibraryCallKit::inline_vector_mem_operation(bool is_store) { if (mismatched_ms) { vload = gvn().transform(trace_vector(LoadVectorNode::make(0, control(), memory(addr), addr, addr_type, mem_num_elem, mem_elem_bt))); const TypeVect* to_vect_type = TypeVect::make(elem_bt, num_elem); - vload = gvn().transform(new VectorReinterpretNode(vload, vload->bottom_type()->is_vect(), to_vect_type)); + vload = gvn().transform(new VectorReinterpretNode(vload, vload->bottom_type()->as_vect(), to_vect_type)); } else { // Special handle for masks if (is_mask) { @@ -1103,7 +1103,7 @@ bool LibraryCallKit::inline_vector_mem_masked_operation(bool is_store) { SavedState old_state(this); Node* addr = make_unsafe_address(base, offset, elem_bt, true); - const TypePtr *addr_type = gvn().type(addr)->isa_ptr(); + const TypePtr* addr_type = gvn().type(addr)->as_ptr(); const TypeAryPtr* arr_type = addr_type->isa_aryptr(); bool mismatched_ms = from_ms->get_con() && arr_type != nullptr && arr_type->elem()->array_element_basic_type() != elem_bt; @@ -1130,7 +1130,7 @@ bool LibraryCallKit::inline_vector_mem_masked_operation(bool is_store) { needs_predicate = true; } else { // Masked vector load with IOOBE always uses the predicated load. - const TypeInt* offset_in_range = gvn().type(argument(9))->isa_int(); + const TypeInt* offset_in_range = gvn().type(argument(9))->as_int(); if (!offset_in_range->is_con()) { log_if_needed(" ** missing constant: offsetInRange=%s", NodeClassNames[argument(8)->Opcode()]); @@ -1208,7 +1208,7 @@ bool LibraryCallKit::inline_vector_mem_masked_operation(bool is_store) { if (mismatched_ms) { // Reinterpret the incoming vector to byte vector. const TypeVect* to_vect_type = TypeVect::make(mem_elem_bt, mem_num_elem); - val = gvn().transform(new VectorReinterpretNode(val, val->bottom_type()->is_vect(), to_vect_type)); + val = gvn().transform(new VectorReinterpretNode(val, val->bottom_type()->as_vect(), to_vect_type)); // Reinterpret the vector mask to byte type. const TypeVect* from_mask_type = TypeVect::makemask(elem_bt, num_elem); const TypeVect* to_mask_type = TypeVect::makemask(mem_elem_bt, mem_num_elem); @@ -1240,7 +1240,7 @@ bool LibraryCallKit::inline_vector_mem_masked_operation(bool is_store) { if (mismatched_ms) { const TypeVect* to_vect_type = TypeVect::make(elem_bt, num_elem); - vload = gvn().transform(new VectorReinterpretNode(vload, vload->bottom_type()->is_vect(), to_vect_type)); + vload = gvn().transform(new VectorReinterpretNode(vload, vload->bottom_type()->as_vect(), to_vect_type)); } Node* box = box_vector(vload, vbox_type, elem_bt, num_elem); @@ -1711,7 +1711,7 @@ bool LibraryCallKit::inline_vector_test() { Node* opd2; if (Matcher::vectortest_needs_second_argument(booltest == BoolTest::overflow, - opd1->bottom_type()->isa_pvectmask())) { + opd1->bottom_type()->is_pvectmask())) { opd2 = unbox_vector(argument(5), vbox_type, elem_bt, num_elem); if (opd2 == nullptr) { log_if_needed(" ** unbox failed m2=%s", NodeClassNames[argument(5)->Opcode()]); @@ -1723,7 +1723,7 @@ bool LibraryCallKit::inline_vector_test() { Node* cmp = gvn().transform(trace_vector(new VectorTestNode(opd1, opd2, booltest))); BoolTest::mask test = Matcher::vectortest_mask(booltest == BoolTest::overflow, - opd1->bottom_type()->isa_pvectmask(), num_elem); + opd1->bottom_type()->is_pvectmask(), num_elem); Node* bol = gvn().transform(new BoolNode(cmp, test)); Node* res = gvn().transform(new CMoveINode(bol, gvn().intcon(0), gvn().intcon(1), TypeInt::BOOL)); @@ -2284,7 +2284,7 @@ bool LibraryCallKit::inline_vector_select_from() { rearrange->add_flag(Node::Flag_is_predicated_vector); } else { // masked rearrange is not supported so emulate usig blend - const TypeVect* vt = v1->bottom_type()->is_vect(); + const TypeVect* vt = v1->bottom_type()->as_vect(); rearrange = gvn().transform(rearrange); // create a zero vector with each lane element set as zero @@ -2587,8 +2587,8 @@ bool LibraryCallKit::inline_vector_convert() { // where certain masks (depending on the species) are either propagated // through a vector or predicate register. if (is_mask && - ((src_type->isa_pvectmask() == nullptr && dst_type->isa_pvectmask()) || - (dst_type->isa_pvectmask() == nullptr && src_type->isa_pvectmask()))) { + ((!src_type->is_pvectmask() && dst_type->is_pvectmask()) || + (!dst_type->is_pvectmask() && src_type->is_pvectmask()))) { return false; } @@ -2636,7 +2636,7 @@ bool LibraryCallKit::inline_vector_convert() { op = gvn().transform(trace_vector(VectorCastNode::make(cast_vopc, op, elem_bt_to, num_elem_for_cast))); // Now ensure that the destination gets properly resized to needed size. - op = gvn().transform(new VectorReinterpretNode(op, op->bottom_type()->is_vect(), dst_type)); + op = gvn().transform(new VectorReinterpretNode(op, op->bottom_type()->as_vect(), dst_type)); } else if (num_elem_from > num_elem_to) { // Since number of elements from input is larger than output, simply reduce size of input // (we are supposed to drop top elements anyway). @@ -2743,7 +2743,7 @@ bool LibraryCallKit::inline_vector_insert() { } Node* insert_val = argument(5); - assert(gvn().type(insert_val)->isa_long() != nullptr, "expected to be long"); + assert(gvn().type(insert_val)->is_long(), "expected to be long"); // Convert insert value back to its appropriate type. switch (elem_bt) { @@ -2845,7 +2845,7 @@ bool LibraryCallKit::inline_vector_extract() { return false; } // VectorMaskToLongNode requires the input is either a mask or a vector with BOOLEAN type. - if (!Matcher::mask_op_prefers_predicate(Op_VectorMaskToLong, opd->bottom_type()->is_vect())) { + if (!Matcher::mask_op_prefers_predicate(Op_VectorMaskToLong, opd->bottom_type()->as_vect())) { opd = gvn().transform(trace_vector(VectorStoreMaskNode::make(gvn(), opd, elem_bt, num_elem))); } // ((toLong() >>> pos) & 1L @@ -3089,7 +3089,7 @@ bool LibraryCallKit::inline_vector_select_from_two_vectors() { int indexRangeMask = 2 * num_elem - 1; Node* wrap_mask = gvn().makecon(TypeInteger::make(indexRangeMask, indexRangeMask, Type::WidenMin, index_elem_bt != T_LONG ? T_INT : index_elem_bt)); Node* wrap_mask_vec = gvn().transform(VectorNode::scalar2vector(wrap_mask, num_elem, index_elem_bt, false)); - opd1 = gvn().transform(VectorNode::make(Op_AndV, opd1, wrap_mask_vec, opd1->bottom_type()->is_vect())); + opd1 = gvn().transform(VectorNode::make(Op_AndV, opd1, wrap_mask_vec, opd1->bottom_type()->as_vect())); operation = gvn().transform(trace_vector(VectorNode::make(Op_SelectFromTwoVector, opd1, opd2, opd3, vt))); } diff --git a/src/hotspot/share/opto/vectorization.cpp b/src/hotspot/share/opto/vectorization.cpp index c8bfc3687af5..83f0549ffaa9 100644 --- a/src/hotspot/share/opto/vectorization.cpp +++ b/src/hotspot/share/opto/vectorization.cpp @@ -1337,7 +1337,7 @@ Node* VPointer::make_pointer_expression(Node* iv_value, Node* ctrl) const { assert(s.scaleI().is_one(), "must be long variable"); Node* scaleL = igvn.longcon(s.scaleL().value()); Node* variable = (s.variable() == iv) ? iv_value : s.variable(); - if (variable->bottom_type()->isa_ptr() != nullptr) { + if (variable->bottom_type()->is_ptr()) { // Use a ctrl that is late enough, so that we do not // evaluate the cast before a SafePoint. variable = new CastP2XNode(ctrl, variable); diff --git a/src/hotspot/share/opto/vectorization.hpp b/src/hotspot/share/opto/vectorization.hpp index d7c0abd9cc20..d59ca7101cc8 100644 --- a/src/hotspot/share/opto/vectorization.hpp +++ b/src/hotspot/share/opto/vectorization.hpp @@ -1576,8 +1576,7 @@ class AlignmentSolver { _are_speculative_checks_possible(are_speculative_checks_possible) DEBUG_ONLY( COMMA _is_trace(is_trace) ) { - assert(_mem_ref != nullptr && - (_mem_ref->is_Load() || _mem_ref->is_Store()), + assert(Node::is(_mem_ref) || Node::is(_mem_ref), "only load or store vectors allowed"); } diff --git a/src/hotspot/share/opto/vectornode.cpp b/src/hotspot/share/opto/vectornode.cpp index 7c3d7d70ef81..a4a014b1dbcc 100644 --- a/src/hotspot/share/opto/vectornode.cpp +++ b/src/hotspot/share/opto/vectornode.cpp @@ -491,6 +491,58 @@ bool VectorNode::is_muladds2i(const Node* n) { return n->Opcode() == Op_MulAddS2I; } +bool VectorNode::is_unpredicated_vector_long_multiply(const Node* n) { + return n->Opcode() == Op_MulVL && !n->is_predicated_vector(); +} + +bool VectorNode::is_vector_long_mul_or_muladdsub(const Node* n) { + return is_vector_long_multiply_addsub(n) || is_unpredicated_vector_long_multiply(n); +} + +bool VectorNode::phi_has_vector_long_mul_or_muladdsub_input(Node* n) { + if (!n->is_Phi()) { + return false; + } + + for (uint i = 1; i < n->req(); i++) { + if (VectorNode::is_vector_long_mul_or_muladdsub(n->in(i))) { + return true; + } + } + + return false; +} + +bool VectorNode::is_vector_long_multiply_addsub(const Node* n) { + if (n->Opcode() != Op_SubVL && n->Opcode() != Op_AddVL) { + return false; + } + + Node* in1 = nullptr; + Node* in2 = nullptr; + if (n->is_predicated_vector()) { + // Masked AD rules use (AddVL/SubVL (Binary src1 src2) pg). + assert(n->in(1)->Opcode() == Op_Binary, ""); + in1 = n->in(1)->in(1); + in2 = n->in(1)->in(2); + } else { + in1 = n->in(1); + in2 = n->in(2); + } + + if (is_unpredicated_vector_long_multiply(in2)) { + return true; + } + + // AddVL is commutative. + if (n->Opcode() == Op_AddVL && !n->is_predicated_vector() && + is_unpredicated_vector_long_multiply(in1)) { + return true; + } + + return false; +} + bool VectorNode::is_roundopD(Node* n) { return n->Opcode() == Op_RoundDoubleMode; } @@ -993,10 +1045,10 @@ bool VectorNode::is_vector_shift_count(int opc) { static bool is_con(Node* n, long con) { if (n->is_Con()) { const Type* t = n->bottom_type(); - if (t->isa_int() && t->is_int()->get_con() == (int)con) { + if (t->is_int() && t->as_int()->get_con() == (int)con) { return true; } - if (t->isa_long() && t->is_long()->get_con() == con) { + if (t->is_long() && t->as_long()->get_con() == con) { return true; } } @@ -1007,7 +1059,7 @@ static bool is_con(Node* n, long con) { bool VectorNode::is_all_ones_vector(Node* n) { switch (n->Opcode()) { case Op_Replicate: - return is_integral_type(n->bottom_type()->is_vect()->element_basic_type()) && + return is_integral_type(n->bottom_type()->as_vect()->element_basic_type()) && is_con(n->in(1), -1); case Op_MaskAll: return is_con(n->in(1), -1); @@ -1020,7 +1072,7 @@ bool VectorNode::is_all_ones_vector(Node* n) { bool VectorNode::is_all_zeros_vector(Node* n) { switch (n->Opcode()) { case Op_Replicate: - return is_integral_type(n->bottom_type()->is_vect()->element_basic_type()) && + return is_integral_type(n->bottom_type()->as_vect()->element_basic_type()) && is_con(n->in(1), 0); case Op_MaskAll: return is_con(n->in(1), 0); @@ -1916,7 +1968,7 @@ static Node* convertFromLongToMaskAll(PhaseGVN* phase, const TypeLong* bits_type } else { con = phase->intcon(con_value); } - Node* res = VectorNode::scalar2vector(con, vlen, maskall_bt, vt->isa_pvectmask() != nullptr); + Node* res = VectorNode::scalar2vector(con, vlen, maskall_bt, vt->is_pvectmask()); // Convert back to the original floating-point data type. if (is_floating_point_type(bt)) { res = new VectorMaskCastNode(phase->transform(res), vt); @@ -1929,8 +1981,8 @@ static Node* convertFromLongToMaskAll(PhaseGVN* phase, const TypeLong* bits_type Node* VectorLoadMaskNode::Ideal(PhaseGVN* phase, bool can_reshape) { // VectorLoadMask(VectorLongToMask(-1/0)) => Replicate(-1/0) if (in(1)->Opcode() == Op_VectorLongToMask) { - const TypeVect* vt = bottom_type()->is_vect(); - Node* res = convertFromLongToMaskAll(phase, in(1)->in(1)->bottom_type()->isa_long(), vt); + const TypeVect* vt = bottom_type()->as_vect(); + Node* res = convertFromLongToMaskAll(phase, in(1)->in(1)->bottom_type()->as_long(), vt); if (res != nullptr) { return res; } @@ -1940,7 +1992,7 @@ Node* VectorLoadMaskNode::Ideal(PhaseGVN* phase, bool can_reshape) { } Node* VectorLoadMaskNode::Identity(PhaseGVN* phase) { - BasicType out_bt = type()->is_vect()->element_basic_type(); + BasicType out_bt = type()->as_vect()->element_basic_type(); if (!Matcher::has_predicated_vectors() && out_bt == T_BOOLEAN) { return in(1); // redundant conversion } @@ -1961,7 +2013,7 @@ Node* VectorStoreMaskNode::Identity(PhaseGVN* phase) { } VectorStoreMaskNode* VectorStoreMaskNode::make(PhaseGVN& gvn, Node* in, BasicType in_type, uint num_elem) { - assert(in->bottom_type()->isa_vect(), "sanity"); + assert(in->bottom_type()->is_vect(), "sanity"); const TypeVect* vt = TypeVect::make(T_BOOLEAN, num_elem); int elem_size = type2aelembytes(in_type); return new VectorStoreMaskNode(in, gvn.intcon(elem_size), vt); @@ -2027,7 +2079,7 @@ bool VectorCastNode::is_supported_subword_cast(BasicType def_bt, BasicType use_b Node* VectorCastNode::Identity(PhaseGVN* phase) { if (!in(1)->is_top()) { - BasicType in_bt = in(1)->bottom_type()->is_vect()->element_basic_type(); + BasicType in_bt = in(1)->bottom_type()->as_vect()->element_basic_type(); BasicType out_bt = vect_type()->element_basic_type(); if (in_bt == out_bt) { return in(1); // redundant cast @@ -2180,10 +2232,10 @@ bool ReductionNode::auto_vectorization_requires_strict_order(int vopc) { MacroLogicVNode* MacroLogicVNode::make(PhaseGVN& gvn, Node* in1, Node* in2, Node* in3, Node* mask, uint truth_table, const TypeVect* vt) { assert(truth_table <= 0xFF, "invalid"); - assert(in1->bottom_type()->is_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); - assert(in2->bottom_type()->is_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); - assert(in3->bottom_type()->is_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); - assert(!mask || mask->bottom_type()->isa_pvectmask(), "predicated register type expected"); + assert(in1->bottom_type()->as_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); + assert(in2->bottom_type()->as_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); + assert(in3->bottom_type()->as_vect()->length_in_bytes() == vt->length_in_bytes(), "mismatch"); + assert(!mask || mask->bottom_type()->is_pvectmask(), "predicated register type expected"); Node* fn = gvn.intcon(truth_table); return new MacroLogicVNode(in1, in2, in3, fn, mask, vt); } @@ -2223,10 +2275,10 @@ Node* VectorNode::degenerate_vector_rotate(Node* src, Node* cnt, bool is_rotate_ if (bt == T_LONG) { // Shift count vector for Rotate vector has long elements too. if (cnt->Opcode() == Op_ConvI2L) { - cnt = cnt->in(1); + cnt = cnt->in(1); } else { - assert(cnt->bottom_type()->isa_long(), "long type shift count expected"); - cnt = phase->transform(new ConvL2INode(cnt)); + assert(cnt->bottom_type()->is_long(), "long type shift count expected"); + cnt = phase->transform(new ConvL2INode(cnt)); } } shiftRCnt = phase->transform(new AndINode(cnt, phase->intcon(shift_mask))); @@ -2241,7 +2293,7 @@ Node* VectorNode::degenerate_vector_rotate(Node* src, Node* cnt, bool is_rotate_ Node* shift_mask_node = nullptr; Node* const_one_node = nullptr; - assert(cnt->bottom_type()->isa_vect(), "Unexpected shift"); + assert(cnt->bottom_type()->is_vect(), "Unexpected shift"); if (bt == T_LONG) { shift_mask_node = phase->longcon(shift_mask); const_one_node = phase->longcon(1L); @@ -2311,7 +2363,7 @@ Node* VectorReinterpretNode::Identity(PhaseGVN *phase) { // 1) Types of 'node' and 'this' are identical // 2) Truncations are not introduced by the first VectorReinterpret if (Type::equals(bottom_type(), n->in(1)->bottom_type()) && - length_in_bytes() <= n->bottom_type()->is_vect()->length_in_bytes()) { + length_in_bytes() <= n->bottom_type()->as_vect()->length_in_bytes()) { return n->in(1); } } @@ -2319,9 +2371,9 @@ Node* VectorReinterpretNode::Identity(PhaseGVN *phase) { } Node* VectorInsertNode::make(Node* vec, Node* new_val, int position, PhaseGVN& gvn) { - assert(position < (int)vec->bottom_type()->is_vect()->length(), "pos in range"); + assert(position < (int)vec->bottom_type()->as_vect()->length(), "pos in range"); ConINode* pos = gvn.intcon(position); - return new VectorInsertNode(vec, new_val, pos, vec->bottom_type()->is_vect()); + return new VectorInsertNode(vec, new_val, pos, vec->bottom_type()->as_vect()); } Node* VectorUnboxNode::Ideal(PhaseGVN* phase, bool can_reshape) { @@ -2333,7 +2385,7 @@ Node* VectorUnboxNode::Ideal(PhaseGVN* phase, bool can_reshape) { VectorBoxNode* vbox = static_cast(n); ciKlass* vbox_klass = vbox->box_type()->instance_klass(); const TypeVect* in_vt = vbox->vec_type(); - const TypeVect* out_vt = type()->is_vect(); + const TypeVect* out_vt = type()->as_vect(); if (in_vt->length() == out_vt->length()) { Node* value = vbox->in(VectorBoxNode::Value); @@ -2345,11 +2397,11 @@ Node* VectorUnboxNode::Ideal(PhaseGVN* phase, bool can_reshape) { if (is_vector_mask) { // VectorUnbox (VectorBox vmask) ==> VectorMaskCast vmask const TypeVect* vmask_type = TypeVect::makemask(out_vt->element_basic_type(), out_vt->length()); - const TypeVect* value_type = value->bottom_type()->is_vect(); + const TypeVect* value_type = value->bottom_type()->as_vect(); // Very rarely, profiling can give us output types that are not // compatible with the input type, where one is PVectMask and // the other not. Such a path should be unreachable anyway. - if ((value_type->isa_pvectmask() == nullptr) == (vmask_type->isa_pvectmask() == nullptr)) { + if (value_type->is_pvectmask() == vmask_type->is_pvectmask()) { return new VectorMaskCastNode(value, vmask_type); } } else { @@ -2463,13 +2515,13 @@ Node* VectorMaskToLongNode::Ideal_MaskAll(PhaseGVN* phase) { // If the ideal graph is transformed correctly, the input mask should be a // vector type node. Following optimization can ignore the mismatched type // issue. But we still keep the sanity check for the mask type by using - // "is_vect()" in the assertion below, so that there can be less optimizations + // "as_vect()" in the assertion below, so that there can be less optimizations // evolved before the compiler finally runs into a problem. - assert(!Matcher::mask_op_prefers_predicate(Opcode(), mask->bottom_type()->is_vect()), "sanity"); + assert(!Matcher::mask_op_prefers_predicate(Opcode(), mask->bottom_type()->as_vect()), "sanity"); in1 = mask; } if (VectorNode::is_all_ones_vector(in1)) { - int vlen = in1->bottom_type()->is_vect()->length(); + int vlen = in1->bottom_type()->as_vect()->length(); return new ConLNode(TypeLong::make(-1ULL >> (64 - vlen))); } if (VectorNode::is_all_zeros_vector(in1)) { @@ -2494,9 +2546,9 @@ Node* VectorMaskToLongNode::Identity(PhaseGVN* phase) { } Node* VectorLongToMaskNode::Ideal(PhaseGVN* phase, bool can_reshape) { - const TypeVect* dst_type = bottom_type()->is_vect(); + const TypeVect* dst_type = bottom_type()->as_vect(); uint vlen = dst_type->length(); - const TypePVectMask* is_mask = dst_type->isa_pvectmask(); + bool is_mask = dst_type->is_pvectmask(); // Pattern: (VectorLongToMask (AndL (VectorMaskToLong src) mask)) // Replace with: (VectorMaskCast src) @@ -2504,13 +2556,12 @@ Node* VectorLongToMaskNode::Ideal(PhaseGVN* phase, bool can_reshape) { // The mask has exactly the vlen first bits on: mask = (2 << vlen - 1) if (in(1)->Opcode() == Op_AndL && in(1)->in(1)->Opcode() == Op_VectorMaskToLong && - in(1)->in(2)->bottom_type()->isa_long() && - in(1)->in(2)->bottom_type()->is_long()->is_con() && - in(1)->in(2)->bottom_type()->is_long()->get_con() == ((1LL << vlen) - 1)) { + in(1)->in(2)->bottom_type()->is_long() && + in(1)->in(2)->bottom_type()->as_long()->is_con() && + in(1)->in(2)->bottom_type()->as_long()->get_con() == ((1LL << vlen) - 1)) { Node* src = in(1)->in(1)->in(1); - const TypeVect* src_type = src->bottom_type()->is_vect(); - if (src_type->length() == vlen && - ((src_type->isa_pvectmask() == nullptr) == (is_mask == nullptr))) { + const TypeVect* src_type = src->bottom_type()->as_vect(); + if (src_type->length() == vlen && src_type->is_pvectmask() == is_mask) { return new VectorMaskCastNode(src, dst_type); } } @@ -2913,7 +2964,7 @@ Node* XorVNode::Ideal(PhaseGVN* phase, bool can_reshape) { if (!is_predicated_vector() && (in(1) == in(2))) { BasicType bt = vect_type()->element_basic_type(); Node* zero = phase->transform(phase->zerocon(bt)); - return VectorNode::scalar2vector(zero, length(), bt, bottom_type()->isa_pvectmask() != nullptr); + return VectorNode::scalar2vector(zero, length(), bt, bottom_type()->is_pvectmask()); } Node* res = Ideal_XorV_VectorMaskCmp(phase, can_reshape); @@ -2938,8 +2989,8 @@ Node* VectorBlendNode::Identity(PhaseGVN* phase) { static bool is_replicate_uint_constant(const Node* n) { return n->Opcode() == Op_Replicate && n->in(1)->is_Con() && - n->in(1)->bottom_type()->isa_long() && - (julong)n->in(1)->bottom_type()->is_long()->get_con() <= 0xFFFFFFFFUL; + n->in(1)->bottom_type()->is_long() && + (julong)n->in(1)->bottom_type()->as_long()->get_con() <= 0xFFFFFFFFUL; } static bool has_vector_elements_fit_uint(Node* n) { @@ -2954,8 +3005,8 @@ static bool has_vector_elements_fit_uint(Node* n) { return n->Opcode() == Op_URShiftVL && !n->is_predicated_vector() && n->in(2)->Opcode() == Op_RShiftCntV && n->in(2)->in(1)->is_Con() && - n->in(2)->in(1)->bottom_type()->isa_int() && - n->in(2)->in(1)->bottom_type()->is_int()->get_con() >= 32; + n->in(2)->in(1)->bottom_type()->is_int() && + n->in(2)->in(1)->bottom_type()->as_int()->get_con() >= 32; }; return is_lower_doubleword_mask_pattern(n) || // (AndV SRC (Replicate C)) where C <= 0xFFFFFFFF is_clear_upper_doubleword_uright_shift_pattern(n); // (URShiftV SRC S) where S >= 32 @@ -2970,8 +3021,8 @@ static bool has_vector_elements_fit_int(Node* n) { return n->Opcode() == Op_RShiftVL && !n->is_predicated_vector() && n->in(2)->Opcode() == Op_RShiftCntV && n->in(2)->in(1)->is_Con() && - n->in(2)->in(1)->bottom_type()->isa_int() && - n->in(2)->in(1)->bottom_type()->is_int()->get_con() >= 32; + n->in(2)->in(1)->bottom_type()->is_int() && + n->in(2)->in(1)->bottom_type()->as_int()->get_con() >= 32; }; return is_cast_integer_to_long_pattern(n) || // (VectorCastI2X SRC) @@ -3030,7 +3081,7 @@ static Node* MinMaxV_Common_Ideal(MinMaxVNode* n, PhaseGVN* phase, bool can_resh // Use n->in(1) inputs for the result to preserve correct merge-masking // passthrough: inactive lanes use in(1), so result->in(1) must equal // n->in(1)->in(1) to maintain the original passthrough semantics. - VectorNode* result = VectorNode::make(vopc, n->in(1)->in(1), n->in(1)->in(2), n->bottom_type()->is_vect()); + VectorNode* result = VectorNode::make(vopc, n->in(1)->in(1), n->in(1)->in(2), n->bottom_type()->as_vect()); if (n->is_predicated_vector()) { result->add_req(n->in(3)); result->add_flag(Node::Flag_is_predicated_vector); diff --git a/src/hotspot/share/opto/vectornode.hpp b/src/hotspot/share/opto/vectornode.hpp index 3e5bc776af54..b2472abd526d 100644 --- a/src/hotspot/share/opto/vectornode.hpp +++ b/src/hotspot/share/opto/vectornode.hpp @@ -120,7 +120,7 @@ class VectorNode : public TypeNode { init_req(4, n3); } - const TypeVect* vect_type() const { return type()->is_vect(); } + const TypeVect* vect_type() const { return type()->as_vect(); } uint length() const { return vect_type()->length(); } // Vector length uint length_in_bytes() const { return vect_type()->length_in_bytes(); } @@ -173,6 +173,10 @@ class VectorNode : public TypeNode { // are all 1s or all 0s, indicating a "mask all" or "mask none" pattern. static bool is_maskall_type(const TypeLong* type, int vlen); static bool is_muladds2i(const Node* n); + static bool is_unpredicated_vector_long_multiply(const Node* n); + static bool is_vector_long_mul_or_muladdsub(const Node* n); + static bool is_vector_long_multiply_addsub(const Node* n); + static bool phi_has_vector_long_mul_or_muladdsub_input(Node* n); static bool is_roundopD(Node* n); static bool is_scalar_rotate(Node* n); static bool is_vector_rotate_supported(int opc, uint vlen, BasicType bt); @@ -301,9 +305,9 @@ class ReductionNode : public Node { const Type* _bottom_type; const TypeVect* _vect_type; public: - ReductionNode(Node *ctrl, Node* in1, Node* in2) : Node(ctrl, in1, in2), + ReductionNode(Node* ctrl, Node* in1, Node* in2) : Node(ctrl, in1, in2), _bottom_type(Type::get_const_basic_type(in1->bottom_type()->basic_type())), - _vect_type(in2->bottom_type()->is_vect()) { + _vect_type(in2->bottom_type()->as_vect()) { init_class_id(Class_Reduction); } @@ -1185,7 +1189,7 @@ class LoadVectorNode : public LoadNode { set_mismatched_access(); } - const TypeVect* vect_type() const { return type()->is_vect(); } + const TypeVect* vect_type() const { return type()->as_vect(); } uint length() const { return vect_type()->length(); } // Vector length virtual int Opcode() const; @@ -1248,7 +1252,7 @@ class StoreVectorNode : public StoreNode { DEBUG_ONLY( bool _must_verify_alignment = false; ); public: StoreVectorNode(Node* c, Node* mem, Node* adr, const TypePtr* at, Node* val) - : StoreNode(c, mem, adr, at, val, MemNode::unordered), _vect_type(val->bottom_type()->is_vect()) { + : StoreNode(c, mem, adr, at, val, MemNode::unordered), _vect_type(val->bottom_type()->as_vect()) { init_class_id(Class_StoreVector); set_mismatched_access(); } @@ -1390,7 +1394,7 @@ class StoreVectorScatterMaskedNode : public StoreVectorNode { : StoreVectorNode(c, mem, adr, at, val) { init_class_id(Class_StoreVectorScatterMasked); assert(indices->bottom_type()->is_vect(), "indices must be in vector"); - assert(mask->bottom_type()->isa_pvectmask(), "sanity"); + assert(mask->bottom_type()->is_pvectmask(), "sanity"); add_req(indices); add_req(mask); assert(req() == MemNode::ValueIn + 3, "match_edge expects that last input is in MemNode::ValueIn+2"); @@ -1456,7 +1460,7 @@ class VectorMaskOpNode : public TypeNode { const TypeVect* _vect_type; public: VectorMaskOpNode(Node* mask, const Type* ty): - TypeNode(ty, 2), _vect_type(mask->bottom_type()->is_vect()) { + TypeNode(ty, 2), _vect_type(mask->bottom_type()->as_vect()) { assert(Matcher::has_predicated_vectors() || _vect_type->element_basic_type() == T_BOOLEAN, ""); init_req(1, mask); } @@ -1776,9 +1780,9 @@ class VectorMaskCmpNode : public VectorNode { VectorMaskCmpNode(BoolTest::mask predicate, Node* in1, Node* in2, ConINode* predicate_node, const TypeVect* vt) : VectorNode(in1, in2, predicate_node, vt), _predicate(predicate) { - assert(in1->bottom_type()->is_vect()->element_basic_type() == in2->bottom_type()->is_vect()->element_basic_type(), + assert(in1->bottom_type()->as_vect()->element_basic_type() == in2->bottom_type()->as_vect()->element_basic_type(), "VectorMaskCmp inputs must have same type for elements"); - assert(in1->bottom_type()->is_vect()->length() == in2->bottom_type()->is_vect()->length(), + assert(in1->bottom_type()->as_vect()->length() == in2->bottom_type()->as_vect()->length(), "VectorMaskCmp inputs must have same number of elements"); assert((BoolTest::mask)predicate_node->get_int() == predicate, "Unmatched predicates"); init_class_id(Class_VectorMaskCmp); @@ -1800,7 +1804,7 @@ class VectorMaskCmpNode : public VectorNode { class VectorMaskWrapperNode : public VectorNode { public: VectorMaskWrapperNode(Node* vector, Node* mask) - : VectorNode(vector, mask, vector->bottom_type()->is_vect()) { + : VectorNode(vector, mask, vector->bottom_type()->as_vect()) { assert(mask->is_VectorMaskCmp(), "VectorMaskWrapper requires that second argument be a mask"); } @@ -1820,7 +1824,7 @@ class VectorTestNode : public CmpNode { public: VectorTestNode(Node* in1, Node* in2, BoolTest::mask predicate) : CmpNode(in1, in2), _predicate(predicate) { - assert(in2->bottom_type()->is_vect() == in2->bottom_type()->is_vect(), "same vector type"); + assert(in2->bottom_type()->as_vect() == in2->bottom_type()->as_vect(), "same vector type"); } virtual int Opcode() const; virtual uint hash() const { return Node::hash() + _predicate; } @@ -1858,7 +1862,7 @@ class VectorSliceNode : public VectorNode { class VectorBlendNode : public VectorNode { public: VectorBlendNode(Node* vec1, Node* vec2, Node* mask) - : VectorNode(vec1, vec2, mask, vec1->bottom_type()->is_vect()) { + : VectorNode(vec1, vec2, mask, vec1->bottom_type()->as_vect()) { } virtual int Opcode() const; @@ -1873,14 +1877,14 @@ class VectorBitwiseBlendNode : public VectorNode { public: VectorBitwiseBlendNode(Node* vec_false, Node* vec_true, Node* sel, const TypeVect* vt) : VectorNode(vec_false, vec_true, sel, vt) { - assert(vec_false->bottom_type()->isa_vect() != nullptr && - vec_true->bottom_type()->isa_vect() != nullptr && - sel->bottom_type()->isa_vect() != nullptr, + assert(vec_false->bottom_type()->is_vect() && + vec_true->bottom_type()->is_vect() && + sel->bottom_type()->is_vect(), "inputs must all be vectors"); uint vlen = vt->length(); - assert(vec_false->bottom_type()->is_vect()->length() == vlen && - vec_true->bottom_type()->is_vect()->length() == vlen && - sel->bottom_type()->is_vect()->length() == vlen, + assert(vec_false->bottom_type()->as_vect()->length() == vlen && + vec_true->bottom_type()->as_vect()->length() == vlen && + sel->bottom_type()->as_vect()->length() == vlen, "mismatched vector length"); } virtual int Opcode() const; @@ -1893,7 +1897,7 @@ class VectorBitwiseBlendNode : public VectorNode { class VectorRearrangeNode : public VectorNode { public: VectorRearrangeNode(Node* vec1, Node* shuffle) - : VectorNode(vec1, shuffle, vec1->bottom_type()->is_vect()) { + : VectorNode(vec1, shuffle, vec1->bottom_type()->as_vect()) { } virtual int Opcode() const; @@ -1911,8 +1915,8 @@ class SelectFromTwoVectorNode : public VectorNode { public: SelectFromTwoVectorNode(Node* indexes, Node* src1, Node* src2, const TypeVect* vt) : VectorNode(indexes, src1, src2, vt) { - assert(is_integral_type(indexes->bottom_type()->is_vect()->element_basic_type()), - "indexes must be an integral vector"); + assert(is_integral_type(indexes->bottom_type()->as_vect()->element_basic_type()), + "indexes must be an integral vector"); } virtual int Opcode() const; @@ -1944,7 +1948,7 @@ class VectorLoadShuffleNode : public VectorNode { class VectorLoadMaskNode : public VectorNode { public: VectorLoadMaskNode(Node* in, const TypeVect* vt) : VectorNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_BOOLEAN, "must be boolean"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_BOOLEAN, "must be boolean"); } virtual int Opcode() const; @@ -1976,11 +1980,11 @@ class VectorStoreMaskNode : public VectorNode { class VectorMaskCastNode : public VectorNode { public: VectorMaskCastNode(Node* in, const TypeVect* vt) : VectorNode(in, vt) { - const TypeVect* in_vt = in->bottom_type()->is_vect(); + const TypeVect* in_vt = in->bottom_type()->as_vect(); assert(in_vt->length() == vt->length(), "vector length must match"); assert((in_vt->element_basic_type() == T_BOOLEAN) == (vt->element_basic_type() == T_BOOLEAN), "Cast from/to BVectMask not allowed, use VectorLoadMask/VectorStoreMask instead"); - assert((in_vt->isa_pvectmask() == nullptr) == (vt->isa_pvectmask() == nullptr), + assert(in_vt->is_pvectmask() == vt->is_pvectmask(), "Both BVectMask, or both NVectMask, or both PVectMask"); } Node* Identity(PhaseGVN* phase); @@ -1997,7 +2001,7 @@ class VectorReinterpretNode : public VectorNode { public: VectorReinterpretNode(Node* in, const TypeVect* src_vt, const TypeVect* dst_vt) : VectorNode(in, dst_vt), _src_vt(src_vt) { - assert((!dst_vt->isa_pvectmask() && !src_vt->isa_pvectmask()) || + assert((!dst_vt->is_pvectmask() && !src_vt->is_pvectmask()) || (type2aelembytes(src_vt->element_basic_type()) >= type2aelembytes(dst_vt->element_basic_type())), "unsupported mask widening reinterpretation"); init_class_id(Class_VectorReinterpret); @@ -2032,7 +2036,7 @@ class VectorCastNode : public VectorNode { class VectorCastB2XNode : public VectorCastNode { public: VectorCastB2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_BYTE, "must be byte"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_BYTE, "must be byte"); } virtual int Opcode() const; }; @@ -2041,7 +2045,7 @@ class VectorCastB2XNode : public VectorCastNode { class VectorCastS2XNode : public VectorCastNode { public: VectorCastS2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_SHORT, "must be short"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_SHORT, "must be short"); } virtual int Opcode() const; }; @@ -2050,7 +2054,7 @@ class VectorCastS2XNode : public VectorCastNode { class VectorCastI2XNode : public VectorCastNode { public: VectorCastI2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_INT, "must be int"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_INT, "must be int"); } virtual int Opcode() const; }; @@ -2059,7 +2063,7 @@ class VectorCastI2XNode : public VectorCastNode { class VectorCastL2XNode : public VectorCastNode { public: VectorCastL2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_LONG, "must be long"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_LONG, "must be long"); } virtual int Opcode() const; }; @@ -2068,7 +2072,7 @@ class VectorCastL2XNode : public VectorCastNode { class VectorCastF2XNode : public VectorCastNode { public: VectorCastF2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_FLOAT, "must be float"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_FLOAT, "must be float"); } virtual int Opcode() const; }; @@ -2077,7 +2081,7 @@ class VectorCastF2XNode : public VectorCastNode { class VectorCastD2XNode : public VectorCastNode { public: VectorCastD2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_DOUBLE, "must be double"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_DOUBLE, "must be double"); } virtual int Opcode() const; }; @@ -2086,7 +2090,7 @@ class VectorCastD2XNode : public VectorCastNode { class VectorCastHF2FNode : public VectorCastNode { public: VectorCastHF2FNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_SHORT, "must be short"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_SHORT, "must be short"); } virtual int Opcode() const; }; @@ -2095,7 +2099,7 @@ class VectorCastHF2FNode : public VectorCastNode { class VectorCastF2HFNode : public VectorCastNode { public: VectorCastF2HFNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_FLOAT, "must be float"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_FLOAT, "must be float"); } virtual int Opcode() const; }; @@ -2109,7 +2113,7 @@ class VectorCastF2HFNode : public VectorCastNode { class VectorUCastB2XNode : public VectorCastNode { public: VectorUCastB2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_BYTE, "must be byte"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_BYTE, "must be byte"); assert(vt->element_basic_type() == T_SHORT || vt->element_basic_type() == T_INT || vt->element_basic_type() == T_LONG, "must be"); @@ -2122,7 +2126,7 @@ class VectorUCastB2XNode : public VectorCastNode { class VectorUCastS2XNode : public VectorCastNode { public: VectorUCastS2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_SHORT, "must be short"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_SHORT, "must be short"); assert(vt->element_basic_type() == T_INT || vt->element_basic_type() == T_LONG, "must be"); } @@ -2133,7 +2137,7 @@ class VectorUCastS2XNode : public VectorCastNode { class VectorUCastI2XNode : public VectorCastNode { public: VectorUCastI2XNode(Node* in, const TypeVect* vt) : VectorCastNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_INT, "must be int"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_INT, "must be int"); assert(vt->element_basic_type() == T_LONG, "must be"); } virtual int Opcode() const; @@ -2143,7 +2147,7 @@ class VectorUCastI2XNode : public VectorCastNode { class RoundVFNode : public VectorNode { public: RoundVFNode(Node* in, const TypeVect* vt) :VectorNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_FLOAT, "must be float"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_FLOAT, "must be float"); } virtual int Opcode() const; }; @@ -2152,7 +2156,7 @@ class RoundVFNode : public VectorNode { class RoundVDNode : public VectorNode { public: RoundVDNode(Node* in, const TypeVect* vt) : VectorNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == T_DOUBLE, "must be double"); + assert(in->bottom_type()->as_vect()->element_basic_type() == T_DOUBLE, "must be double"); } virtual int Opcode() const; }; @@ -2264,7 +2268,7 @@ class CountLeadingZerosVNode : public VectorNode { public: CountLeadingZerosVNode(Node* in, const TypeVect* vt) : VectorNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == vt->element_basic_type(), + assert(in->bottom_type()->as_vect()->element_basic_type() == vt->element_basic_type(), "must be the same"); } @@ -2276,7 +2280,7 @@ class CountTrailingZerosVNode : public VectorNode { public: CountTrailingZerosVNode(Node* in, const TypeVect* vt) : VectorNode(in, vt) { - assert(in->bottom_type()->is_vect()->element_basic_type() == vt->element_basic_type(), + assert(in->bottom_type()->as_vect()->element_basic_type() == vt->element_basic_type(), "must be the same"); } diff --git a/src/hotspot/share/opto/vtransform.cpp b/src/hotspot/share/opto/vtransform.cpp index 161438565f93..1189d52e7085 100644 --- a/src/hotspot/share/opto/vtransform.cpp +++ b/src/hotspot/share/opto/vtransform.cpp @@ -1069,7 +1069,7 @@ float VTransformShiftCountNode::cost(const VLoopAnalyzer& vloop_analyzer) const VTransformApplyResult VTransformShiftCountNode::apply(VTransformApplyState& apply_state) const { PhaseIdealLoop* phase = apply_state.phase(); Node* shift_count_in = apply_state.transformed_node(in_req(1)); - assert(shift_count_in->bottom_type()->isa_int(), "int type only for shift count"); + assert(shift_count_in->bottom_type()->is_int(), "int type only for shift count"); // The shift_count_in would be automatically truncated to the lowest _mask // bits in a scalar shift operation. But vector shift does not truncate, so // we must apply the mask now. diff --git a/src/hotspot/share/prims/jvmtiTagMap.cpp b/src/hotspot/share/prims/jvmtiTagMap.cpp index efc64cc00464..47b7f0e70ddd 100644 --- a/src/hotspot/share/prims/jvmtiTagMap.cpp +++ b/src/hotspot/share/prims/jvmtiTagMap.cpp @@ -1097,7 +1097,7 @@ static jint invoke_primitive_field_callback_for_instance_fields( jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type; // get field value - address addr = cast_from_oop
(obj.obj()) + obj.offset() + field->field_offset(); + address addr = cast_from_oop
(obj.holder_or_obj()) + obj.offset() + field->field_offset(); jvalue value; copy_to_jvalue(&value, addr, value_type); @@ -1404,11 +1404,11 @@ void IterateThroughHeapObjectClosure::visit_flat_fields(const JvmtiHeapwalkObjec } // check for possible nulls if (field->is_nullable_flat()) { - if (field->value_klass()->is_payload_marked_as_null(obj.obj(), field_offset)) { + if (field->value_klass()->is_payload_marked_as_null(obj.holder_or_obj(), field_offset)) { continue; } } - JvmtiHeapwalkObject field_obj(obj.obj(), field_offset, field->value_klass(), field->flat_layout()); + JvmtiHeapwalkObject field_obj(obj.holder_or_obj(), field_offset, field->value_klass(), field->flat_layout()); visit_object(field_obj); @@ -3188,16 +3188,16 @@ inline bool VM_HeapWalkOperation::iterate_over_object(const JvmtiHeapwalkObject& if (field->is_flat()) { // check for possible nulls if (field->is_nullable_flat()) { - if (field->value_klass()->is_payload_marked_as_null(o.obj(), field_offset)) { + if (field->value_klass()->is_payload_marked_as_null(o.holder_or_obj(), field_offset)) { continue; } } - JvmtiHeapwalkObject field_obj(o.obj(), field_offset, field->value_klass(), field->flat_layout()); + JvmtiHeapwalkObject field_obj(o.holder_or_obj(), field_offset, field->value_klass(), field->flat_layout()); if (!CallbackInvoker::report_field_reference(o, field_obj, slot)) { return false; } } else { - oop fld_o = o.obj()->obj_field_access(field_offset); + oop fld_o = o.holder_or_obj()->obj_field_access(field_offset); // ignore any objects that aren't visible to profiler if (fld_o != nullptr) { assert(Universe::heap()->is_in(fld_o), "unsafe code should not have references to Klass* anymore"); @@ -3209,7 +3209,7 @@ inline bool VM_HeapWalkOperation::iterate_over_object(const JvmtiHeapwalkObject& } else { if (is_reporting_primitive_fields()) { // primitive instance field - address addr = cast_from_oop
(o.obj()) + field_offset; + address addr = cast_from_oop
(o.holder_or_obj()) + field_offset; if (!CallbackInvoker::report_primitive_instance_field(o, slot, addr, type)) { return false; } @@ -3402,7 +3402,7 @@ bool VM_HeapWalkOperation::visit(const JvmtiHeapwalkObject& o) { // a java.lang.Class return iterate_over_class(o); } - } else if (java_lang_ClassLoader::is_instance(o.obj())) { + } else if (java_lang_ClassLoader::is_subclass(klass)) { return iterate_over_class_loader(o); } else { // we report stack references only when initial object is not specified diff --git a/src/hotspot/share/prims/jvmtiTagMapTable.cpp b/src/hotspot/share/prims/jvmtiTagMapTable.cpp index a0782799a337..9a1587b17930 100644 --- a/src/hotspot/share/prims/jvmtiTagMapTable.cpp +++ b/src/hotspot/share/prims/jvmtiTagMapTable.cpp @@ -41,7 +41,7 @@ static unsigned get_value_object_hash(oop holder, int offset, Klass* klass) { static unsigned get_value_object_hash(const JvmtiHeapwalkObject & obj) { assert(obj.is_value(), "Must be value class"); - return get_value_object_hash(obj.obj(), obj.offset(), obj.value_klass()); + return get_value_object_hash(obj.holder_or_obj(), obj.offset(), obj.value_klass()); } static bool equal_oops(oop obj1, oop obj2); // forward declaration @@ -132,7 +132,7 @@ bool JvmtiHeapwalkObject::equals(const JvmtiHeapwalkObject& obj1, const JvmtiHea if (obj1.is_value() && obj1.value_klass() == obj2.value_klass()) { // instances of the same value class - return equal_value_objects(obj1.obj(), obj1.offset(), obj2.obj(), obj2.offset(), obj1.value_klass()); + return equal_value_objects(obj1.holder_or_obj(), obj1.offset(), obj2.holder_or_obj(), obj2.offset(), obj1.value_klass()); } return false; } @@ -178,7 +178,7 @@ void JvmtiTagMapKey::release_handle() { JvmtiHeapwalkObject JvmtiTagMapKey::heapwalk_object() const { if (_obj != nullptr) { - return JvmtiHeapwalkObject(_obj->obj(), _obj->offset(), _obj->value_klass(), _obj->optional_flat_layout()); + return JvmtiHeapwalkObject(_obj->holder_or_obj(), _obj->offset(), _obj->value_klass(), _obj->optional_flat_layout()); } oop obj = object_no_keepalive(); if (obj == nullptr) { @@ -312,7 +312,7 @@ void JvmtiTagMapTable::remove_dead_entries(GrowableArray* objects) { } JvmtiValueTagMapKey::JvmtiValueTagMapKey(const JvmtiHeapwalkObject& obj) - : _holder(obj.obj()), _offset(obj.offset()), _value_klass(obj.value_klass()), _optional_flat_layout(obj.optional_flat_layout()) {} + : _holder(obj.holder_or_obj()), _offset(obj.offset()), _value_klass(obj.value_klass()), _optional_flat_layout(obj.optional_flat_layout()) {} OopHandle JvmtiValueTagMapKey::create_holder_oop_handle() const { // move object into Handle when copying into the table diff --git a/src/hotspot/share/prims/jvmtiTagMapTable.hpp b/src/hotspot/share/prims/jvmtiTagMapTable.hpp index f4206f86718a..4f01da4eeab6 100644 --- a/src/hotspot/share/prims/jvmtiTagMapTable.hpp +++ b/src/hotspot/share/prims/jvmtiTagMapTable.hpp @@ -58,7 +58,11 @@ class JvmtiHeapwalkObject { inline bool is_value() const { return _value_klass != nullptr; } inline bool is_flat() const { return _offset != 0; } - inline oop obj() const { return _obj; } + inline oop holder_or_obj() const { return _obj; } + inline oop obj() const { + assert(!is_flat(), "flattened value does not have an oop"); + return _obj; + } inline int offset() const { return _offset; } inline ValueKlass* value_klass() const { return _value_klass; } inline OptionalFlatLayout optional_flat_layout() const { return _optional_flat_layout; } diff --git a/src/hotspot/share/runtime/arguments.cpp b/src/hotspot/share/runtime/arguments.cpp index 2e77d8fcd686..0594e946e36f 100644 --- a/src/hotspot/share/runtime/arguments.cpp +++ b/src/hotspot/share/runtime/arguments.cpp @@ -532,7 +532,6 @@ static SpecialFlag const special_jvm_flags[] = { { "CompilationMode", JDK_Version::jdk(28), JDK_Version::jdk(29), JDK_Version::jdk(30)}, // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in: { "CreateMinidumpOnCrash", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() }, - { "InitiatingHeapOccupancyPercent", JDK_Version::jdk(27), JDK_Version::jdk(28), JDK_Version::jdk(29) }, // -------------- Obsolete Flags - sorted by expired_in -------------- @@ -546,6 +545,7 @@ static SpecialFlag const special_jvm_flags[] = { #endif { "AlwaysCompileLoopMethods", JDK_Version::jdk(27), JDK_Version::jdk(28), JDK_Version::jdk(29) }, { "OptoBundling", JDK_Version::undefined(), JDK_Version::jdk(28), JDK_Version::jdk(29) }, + { "InitiatingHeapOccupancyPercent", JDK_Version::jdk(27), JDK_Version::jdk(28), JDK_Version::jdk(29) }, #ifdef ASSERT { "DummyObsoleteTestFlag", JDK_Version::undefined(), JDK_Version::jdk(18), JDK_Version::undefined() }, @@ -573,7 +573,6 @@ typedef struct { static AliasedFlag const aliased_jvm_flags[] = { { "CreateMinidumpOnCrash", "CreateCoredumpOnCrash" }, - G1GC_ONLY({"InitiatingHeapOccupancyPercent" COMMA "G1IHOP" } COMMA) { nullptr, nullptr} }; diff --git a/src/hotspot/share/runtime/continuationFreezeThaw.cpp b/src/hotspot/share/runtime/continuationFreezeThaw.cpp index 0899e50aca97..a9f89c64ff9d 100644 --- a/src/hotspot/share/runtime/continuationFreezeThaw.cpp +++ b/src/hotspot/share/runtime/continuationFreezeThaw.cpp @@ -2525,7 +2525,9 @@ NOINLINE intptr_t* Thaw::thaw_slow(stackChunkOop chunk, Continuation::t log_develop_trace(continuations, preempt)("Failed to acquire monitor, unmounting again"); return push_cleanup_continuation(); } - chunk = _cont.tail(); // reload oop in case of safepoint in resume_operation (if posting JVMTI events). + // Reload oop and _barriers in case of safepoint in resume_operation (if posting JVMTI events) + chunk = _cont.tail(); + _barriers = chunk->requires_barriers(); JVMTI_ONLY(assert(_thread->contended_entered_monitor() == nullptr || _thread->contended_entered_monitor() == mon, "")); } else { // Preemption cancelled on moniterenter or ObjectLocker case. We @@ -2536,8 +2538,10 @@ NOINLINE intptr_t* Thaw::thaw_slow(stackChunkOop chunk, Continuation::t preempt_kind = Continuation::monitorenter; } - // Call this first to avoid racing with GC threads later when modifying the chunk flags. - relativize_chunk_concurrently(chunk); + if (_barriers) { + // Call this first to avoid racing with GC threads later when modifying the chunk flags. + relativize_chunk_concurrently(chunk); + } if (chunk->at_klass_init()) { preempt_kind = Continuation::object_locker; @@ -2552,7 +2556,7 @@ NOINLINE intptr_t* Thaw::thaw_slow(stackChunkOop chunk, Continuation::t } chunk->set_preempted(false); retry_fast_path = true; - } else { + } else if (_barriers) { relativize_chunk_concurrently(chunk); } diff --git a/src/java.base/aix/classes/sun/nio/ch/PollsetPoller.java b/src/java.base/aix/classes/sun/nio/ch/PollsetPoller.java index 3eee39906ee9..5178b992109c 100644 --- a/src/java.base/aix/classes/sun/nio/ch/PollsetPoller.java +++ b/src/java.base/aix/classes/sun/nio/ch/PollsetPoller.java @@ -77,6 +77,11 @@ void implStopPoll(int fd, boolean polled) { assert ret == 0; } + @Override + void wakeupPoller() throws IOException { + // nothing to do, poll wakes periodically + } + /** * Main poll method. The AIX Pollset library does not appear to pick up changes to the pollset * (the set of fds being polled) while blocked on a call to this method. These changes happen @@ -91,11 +96,17 @@ int poll(int timeout) throws IOException { n = pollInner(0); break; case Pollset.PS_NO_TIMEOUT: - do { n = pollInner(100); } while (n == 0); + n = 0; + while (n == 0 && !isShutdown()) { + n = pollInner(100); + } break; default: Instant end = Instant.now().plusMillis(timeout); - do { n = pollInner(100); } while (n == 0 && Instant.now().isBefore(end)); + n = 0; + while (n == 0 && !isShutdown() && Instant.now().isBefore(end)) { + n = pollInner(100); + } break; } return n; diff --git a/src/java.base/linux/classes/sun/nio/ch/EPollPoller.java b/src/java.base/linux/classes/sun/nio/ch/EPollPoller.java index 5c45393bd623..cc423071e52d 100644 --- a/src/java.base/linux/classes/sun/nio/ch/EPollPoller.java +++ b/src/java.base/linux/classes/sun/nio/ch/EPollPoller.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,6 @@ class EPollPoller extends Poller { private final Cleanable cleaner; EPollPoller(Poller.Mode mode, boolean subPoller, boolean read) throws IOException { - boolean wakeable = (mode == Mode.POLLER_PER_CARRIER) && subPoller; int maxEvents = (subPoller) ? 16 : 64; int epfd = EPoll.create(); @@ -57,10 +56,11 @@ class EPollPoller extends Poller { address = EPoll.allocatePollArray(maxEvents); // register one end of the pipe with epoll to allow for wakeup - if (wakeable) { - eventfd = new EventFD(); - IOUtil.configureBlocking(eventfd.efd(), false); - EPoll.ctl(epfd, EPOLL_CTL_ADD, eventfd.efd(), EPOLLIN); + eventfd = new EventFD(); + IOUtil.configureBlocking(eventfd.efd(), false); + int err = EPoll.ctl(epfd, EPOLL_CTL_ADD, eventfd.efd(), EPOLLIN); + if (err != 0) { + throw new IOException("epoll_ctl failed: " + err); } } catch (Throwable e) { FileDispatcherImpl.closeIntFD(epfd); @@ -75,9 +75,9 @@ class EPollPoller extends Poller { this.address = address; this.eventfd = eventfd; - // create action to close epoll instance, register cleaner when wakeable + // create action to close epoll, register cleaner for per-carrier sub-pollers this.closer = closer(epfd, address, eventfd); - if (wakeable) { + if ((mode == Mode.POLLER_PER_CARRIER) && subPoller) { this.cleaner = CleanerFactory.cleaner().register(this, closer); } else { this.cleaner = null; @@ -131,9 +131,6 @@ void implStopPoll(int fdVal, boolean polled) { @Override void wakeupPoller() throws IOException { - if (eventfd == null) { - throw new UnsupportedOperationException(); - } eventfd.set(); } @@ -145,7 +142,7 @@ int poll(int timeout) throws IOException { while (i < n) { long eventAddress = EPoll.getEvent(address, i); int fd = EPoll.getDescriptor(eventAddress); - if (eventfd == null || fd != eventfd.efd()) { + if (fd != eventfd.efd()) { polled(fd); polled++; } diff --git a/src/java.base/macosx/classes/sun/nio/ch/KQueuePoller.java b/src/java.base/macosx/classes/sun/nio/ch/KQueuePoller.java index 69c191913a92..733226acf7f3 100644 --- a/src/java.base/macosx/classes/sun/nio/ch/KQueuePoller.java +++ b/src/java.base/macosx/classes/sun/nio/ch/KQueuePoller.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,6 @@ class KQueuePoller extends Poller { private final Cleanable cleaner; KQueuePoller(Poller.Mode mode, boolean subPoller, boolean read) throws IOException { - boolean wakeable = (mode == Mode.POLLER_PER_CARRIER) && subPoller; int maxEvents = (subPoller) ? 16 : 64; int kqfd = KQueue.create(); @@ -58,11 +57,12 @@ class KQueuePoller extends Poller { address = KQueue.allocatePollArray(maxEvents); // register one end of the pipe with kqueue to allow for wakeup - if (wakeable) { - long fds = IOUtil.makePipe(false); - fd0 = (int) (fds >>> 32); - fd1 = (int) fds; - KQueue.register(kqfd, fd0, EVFILT_READ, EV_ADD); + long fds = IOUtil.makePipe(false); + fd0 = (int) (fds >>> 32); + fd1 = (int) fds; + int err = KQueue.register(kqfd, fd0, EVFILT_READ, EV_ADD); + if (err != 0) { + throw new IOException("kevent failed: " + err); } } catch (Throwable e) { FileDispatcherImpl.closeIntFD(kqfd); @@ -79,9 +79,9 @@ class KQueuePoller extends Poller { this.fd0 = fd0; this.fd1 = fd1; - // create action to close kqueue, register cleaner when wakeable + // create action to close kqueue, register cleaner for per-carrier sub-pollers this.closer = closer(kqfd, address, fd0, fd1); - if (wakeable) { + if ((mode == Mode.POLLER_PER_CARRIER) && subPoller) { this.cleaner = CleanerFactory.cleaner().register(this, closer); } else { this.cleaner = null; @@ -133,9 +133,6 @@ void implStopPoll(int fdVal, boolean polled) { @Override void wakeupPoller() throws IOException { - if (fd1 < 0) { - throw new UnsupportedOperationException(); - } IOUtil.write1(fd1, (byte)0); } diff --git a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java index c9e7191df33d..6b8b3674e73a 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,14 @@ package com.sun.crypto.provider; import java.security.Provider; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.HashMap; import java.util.List; +import java.util.Map; import static sun.security.util.SecurityConstants.PROVIDER_VER; import static sun.security.util.SecurityProviderConstants.*; +import sun.security.ssl.Hybrid; /* * The "SunJCE" Cryptographic Service Provider. @@ -78,6 +81,9 @@ * * - ML-KEM * + * - TLS 1.3 hybrid KEMs for X25519MLKEM768, SecP256r1MLKEM768, + * and SecP384r1MLKEM1024 + * * - HKDF-SHA256, HKDF-SHA384, and HKDF-SHA512 */ @@ -88,7 +94,8 @@ public final class SunJCE extends Provider { private static final String info = "SunJCE Provider " + "(implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, " - + "Diffie-Hellman, HMAC, ChaCha20, DHKEM, ML-KEM, and HKDF)"; + + "Diffie-Hellman, HMAC, ChaCha20, DHKEM, ML-KEM, X25519MLKEM768, " + + "SecP256r1MLKEM768, SecP384r1MLKEM1024, and HKDF)"; /* Are we debugging? -- for developers */ static final boolean debug = false; @@ -122,6 +129,11 @@ private void psA(String type, String algo, String cn, attrs)); } + private void psHybrid(String type, String algo, String cn, + HashMap attrs) { + putService(new HybridService(this, type, algo, cn, attrs)); + } + public SunJCE() { /* We are the "SunJCE" provider */ super("SunJCE", PROVIDER_VER, info); @@ -777,6 +789,43 @@ void putEntries() { psA("KeyFactory", "ML-KEM-768", "com.sun.crypto.provider.ML_KEM_Impls$KF3", attrs); psA("KeyFactory", "ML-KEM-1024", "com.sun.crypto.provider.ML_KEM_Impls$KF5", attrs); + /* + * TLS 1.3 hybrid key exchange algorithms: X25519MLKEM768, + * SecP256r1MLKEM768, and SecP384r1MLKEM1024. + * + * These JCA services for hybrid key exchange algorithms exist for + * use by SunJSSE only. They are not general purpose KEM algorithms. + * Their public keys use the RAW TLS key_share encoding, not X.509 + * SubjectPublicKeyInfo encoding, and the algorithms do not have + * formal object identifiers. + */ + attrs = new HashMap<>(Map.of( + "ImplementedIn", "Software", + "left", "ML-KEM-768", + "right", "X25519")); + psHybrid("KeyPairGenerator", "X25519MLKEM768", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", attrs); + psHybrid("KEM", "X25519MLKEM768", + "sun.security.ssl.Hybrid$KEMImpl", attrs); + + attrs = new HashMap<>(Map.of( + "ImplementedIn", "Software", + "left", "secp256r1", + "right", "ML-KEM-768")); + psHybrid("KeyPairGenerator", "SecP256r1MLKEM768", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", attrs); + psHybrid("KEM", "SecP256r1MLKEM768", + "sun.security.ssl.Hybrid$KEMImpl", attrs); + + attrs = new HashMap<>(Map.of( + "ImplementedIn", "Software", + "left", "secp384r1", + "right", "ML-KEM-1024")); + psHybrid("KeyPairGenerator", "SecP384r1MLKEM1024", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", attrs); + psHybrid("KEM", "SecP384r1MLKEM1024", + "sun.security.ssl.Hybrid$KEMImpl", attrs); + /* * SSL/TLS mechanisms * @@ -811,4 +860,26 @@ static SunJCE getInstance() { } return instance; } + + private static final class HybridService extends Provider.Service { + HybridService(Provider p, String type, String algo, String cn, + HashMap attrs) { + super(p, type, algo, cn, null, attrs); + } + + @Override + public Object newInstance(Object ctrParamObj) + throws NoSuchAlgorithmException { + return switch (getType()) { + case "KeyPairGenerator" -> new Hybrid.KeyPairGeneratorImpl( + getAlgorithm(), getAttribute("left"), + getAttribute("right")); + case "KEM" -> new Hybrid.KEMImpl( + getAlgorithm(), getAttribute("left"), + getAttribute("right")); + default -> throw new NoSuchAlgorithmException( + "Unexpected value: " + getType()); + }; + } + } } diff --git a/src/java.base/share/classes/java/io/DeleteOnExitHook.java b/src/java.base/share/classes/java/io/DeleteOnExitHook.java index 5c0b9dd1666c..d50aafc369ed 100644 --- a/src/java.base/share/classes/java/io/DeleteOnExitHook.java +++ b/src/java.base/share/classes/java/io/DeleteOnExitHook.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ class DeleteOnExitHook { // registered during shutdown in progress. So set the // registerShutdownInProgress parameter to true. SharedSecrets.getJavaLangAccess() - .registerShutdownHook(2 /* Shutdown hook invocation order */, + .registerShutdownHook(3 /* Shutdown hook invocation order */, true /* register even if shutdown in progress */, new Runnable() { public void run() { diff --git a/src/java.base/share/classes/java/lang/AbstractStringBuilder.java b/src/java.base/share/classes/java/lang/AbstractStringBuilder.java index 05b395ebf83f..40b72e626daf 100644 --- a/src/java.base/share/classes/java/lang/AbstractStringBuilder.java +++ b/src/java.base/share/classes/java/lang/AbstractStringBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -267,6 +267,9 @@ private static boolean needsNewBuffer(byte[] value, byte coder, int newCapacity, private static byte[] ensureCapacityNewCoder(byte[] value, byte coder, int count, int minimumCapacity, byte newCoder) { assert coder == newCoder || newCoder == UTF16 : "bad new coder UTF16 -> LATIN1"; + if (minimumCapacity < 0) { + throwExcessiveLengthError(); + } // overflow-conscious code // Compute the new larger size if growth is requested, otherwise keep the capacity the same int oldCapacity = value.length >> coder; @@ -303,6 +306,9 @@ private static byte[] ensureCapacityNewCoder(byte[] value, byte coder, int count * @param minimumCapacity the new minimum capacity */ private static byte[] ensureCapacitySameCoder(byte[] value, byte coder, int minimumCapacity) { + if (minimumCapacity < 0) { + throwExcessiveLengthError(); + } // overflow-conscious code int oldCapacity = value.length >> coder; if (minimumCapacity - oldCapacity > 0) { @@ -334,17 +340,17 @@ private static byte[] inflateToUTF16(byte[] value, int count) { * @param value the current buffer * @param coder of the current buffer * @param minCapacity the desired minimum capacity - * @throws OutOfMemoryError if minCapacity is less than zero or - * greater than (Integer.MAX_VALUE >> coder) + * @throws OutOfMemoryError if {@code minCapacity} is out of bounds */ private static int newCapacity(byte[] value, byte coder, int minCapacity) { + assert minCapacity >= 0 : "Invalid minimum capacity: " + minCapacity; int oldLength = value.length; - int newLength = minCapacity << coder; - int growth = newLength - oldLength; - int length = ArraysSupport.newLength(oldLength, growth, oldLength + (2 << coder)); - if (length == Integer.MAX_VALUE) { - throw new OutOfMemoryError("Required length exceeds implementation limit"); + long newLength = (long) minCapacity << coder; + if (newLength < 0 || newLength >= Integer.MAX_VALUE) { + throwExcessiveLengthError(); } + int growth = (int) newLength - oldLength; + int length = ArraysSupport.newLength(oldLength, growth, oldLength + (2 << coder)); return length >> coder; } @@ -2049,9 +2055,9 @@ private static byte[] appendChars(byte[] value, byte coder, int count, CharSeque private AbstractStringBuilder repeat(char c, int count) { byte coder = this.coder; int prevCount = this.count; - int limit = prevCount + count; byte[] value = this.value; byte newCoder = (byte) (coder | StringLatin1.coderFromChar(c)); + int limit = repeatLimit(newCoder, prevCount, 1, count); if (needsNewBuffer(value, coder, limit, newCoder)) { this.value = value = ensureCapacityNewCoder(value, coder, prevCount, limit, newCoder); this.coder = coder = newCoder; @@ -2147,14 +2153,10 @@ public AbstractStringBuilder repeat(CharSequence cs, int count) { byte coder = this.coder; int offset = this.count; byte[] value = this.value; - int valueLength = length << coder; - if ((Integer.MAX_VALUE - offset) / count < valueLength) { - throw new OutOfMemoryError("Required length exceeds implementation limit"); - } - int total = count * length; - int limit = offset + total; + final int limit; if (cs instanceof String str) { byte newCoder = (byte)(coder | str.coder()); + limit = repeatLimit(newCoder, offset, length, count); if (needsNewBuffer(value, coder, limit, newCoder)) { this.value = value = ensureCapacityNewCoder(value, coder, offset, limit, newCoder); this.coder = coder = newCoder; @@ -2162,12 +2164,14 @@ public AbstractStringBuilder repeat(CharSequence cs, int count) { str.getBytes(value, offset, newCoder); } else if (cs instanceof AbstractStringBuilder asb) { byte newCoder = (byte)(coder | asb.coder); + limit = repeatLimit(newCoder, offset, length, count); if (needsNewBuffer(value, coder, limit, newCoder)) { this.value = value = ensureCapacityNewCoder(value, coder, offset, limit, newCoder); this.coder = coder = newCoder; } asb.getBytes(value, offset, newCoder); } else { + limit = repeatLimit(coder, offset, length, count); byte[] currValue = ensureCapacitySameCoder(value, coder, limit); value = appendChars(currValue, coder, offset, cs, 0, length); if (currValue != value) { @@ -2175,8 +2179,37 @@ public AbstractStringBuilder repeat(CharSequence cs, int count) { } this.value = value; } - String.repeatCopyRest(value, offset << coder, total << coder, length << coder); + String.repeatCopyRest(value, offset << coder, (count * length) << coder, length << coder); this.count = limit; return this; } + + /** + * {@return the new {@linkplain #count length} (in {@code char}s) after + * appending the given sequence with specified repetitions} + * + * @param coder the {@linkplain #coder coder} that will be used for encoding + * @param offset the {@linkplain #count offset} (in {@code char}s) to start appending at + * @param seqLength the length in {@code char}s of the sequence to be repeated + * @param seqRepetition the repetition count + * + * @throws OutOfMemoryError If the resultant length is out of bounds + */ + private static int repeatLimit(int coder, int offset, int seqLength, int seqRepetition) { + assert offset >= 0 : "Invalid offset: " + offset; + assert seqLength >= 0 : "Invalid sequence length: " + seqLength; + assert seqRepetition >= 0 : "Invalid sequence repetition count: " + seqRepetition; + long repeatedSeqLength = (long) seqLength * seqRepetition; + long limit = (long) offset + repeatedSeqLength; + long encodedLimit = limit << coder; + if (limit < 0 || encodedLimit < 0 || encodedLimit >= Integer.MAX_VALUE) { + throwExcessiveLengthError(); + } + return (int) limit; + } + + private static void throwExcessiveLengthError() { + throw new OutOfMemoryError("Required length exceeds implementation limit"); + } + } diff --git a/src/java.base/share/classes/java/lang/Error.java b/src/java.base/share/classes/java/lang/Error.java index 002129c7ce38..116b4e05b99a 100644 --- a/src/java.base/share/classes/java/lang/Error.java +++ b/src/java.base/share/classes/java/lang/Error.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -109,10 +109,11 @@ public Error(String message, Throwable cause) { * unknown.) * @since 1.4 */ + @SuppressWarnings("this-escape") public Error(Throwable cause) { super(cause); if (Throwable.jfrTracing) { - ThrowableTracer.traceError(getClass(), null); + ThrowableTracer.traceError(getClass(), super.getMessage()); } } diff --git a/src/java.base/share/classes/java/lang/Shutdown.java b/src/java.base/share/classes/java/lang/Shutdown.java index a9d4d6a28a92..67dfc7f304ed 100644 --- a/src/java.base/share/classes/java/lang/Shutdown.java +++ b/src/java.base/share/classes/java/lang/Shutdown.java @@ -47,7 +47,8 @@ class Shutdown { // (0) Console restore hook // (1) ApplicationShutdownHooks that invokes all registered application // shutdown hooks and waits until they finish - // (2) DeleteOnExit hook + // (2) I/O poller threads supporting virtual threads doing blocking I/O + // (3) DeleteOnExit hook private static final int MAX_SYSTEM_HOOKS = 10; private static final Runnable[] hooks = new Runnable[MAX_SYSTEM_HOOKS]; @@ -64,10 +65,10 @@ class Shutdown { * Add a new system shutdown hook. Checks the shutdown state and * the hook itself, but does not do any security checks. * - * The registerShutdownInProgress parameter should be false except - * registering the DeleteOnExitHook since the first file may - * be added to the delete on exit list by the application shutdown - * hooks. + * It is expected that registerShutdownInProgress is false for the hook + * that runs application shutdown hooks. It may be true for other hooks, + * e.g. DeleteOnExitHook, as the first invocation of File.deleteOnExit + * may occur in an application shutdown hook. * * @param slot the slot in the shutdown hook array, whose element * will be invoked in order during shutdown diff --git a/src/java.base/share/classes/java/lang/Throwable.java b/src/java.base/share/classes/java/lang/Throwable.java index ac3325fc5141..bc1a9e24ca6b 100644 --- a/src/java.base/share/classes/java/lang/Throwable.java +++ b/src/java.base/share/classes/java/lang/Throwable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -337,7 +337,7 @@ public Throwable(Throwable cause) { detailMessage = (cause==null ? null : cause.toString()); this.cause = cause; if (jfrTracing) { - ThrowableTracer.traceThrowable(getClass(), null); + ThrowableTracer.traceThrowable(getClass(), detailMessage); } } diff --git a/src/java.base/share/classes/java/security/cert/X509Certificate.java b/src/java.base/share/classes/java/security/cert/X509Certificate.java index bd19f3d33d05..74a069be7088 100644 --- a/src/java.base/share/classes/java/security/cert/X509Certificate.java +++ b/src/java.base/share/classes/java/security/cert/X509Certificate.java @@ -31,6 +31,7 @@ import javax.security.auth.x500.X500Principal; import java.math.BigInteger; import java.security.*; +import java.time.Instant; import java.util.Collection; import java.util.Date; import java.util.List; @@ -123,24 +124,23 @@ protected X509Certificate() { } /** - * Checks that the certificate is currently valid. It is if + * Checks that the certificate is currently valid. It is valid if * the current date and time are within the validity period given in the * certificate. *

- * The validity period consists of two date/time values: + * The validity period consists of two dates, defined as two time values: * the first and last dates (and times) on which the certificate - * is valid. It is defined in - * ASN.1 as: + * is valid. It is defined in ASN.1 as: *

      * validity             Validity
      *
      * Validity ::= SEQUENCE {
-     *     notBefore      CertificateValidityDate,
-     *     notAfter       CertificateValidityDate }
+     *      notBefore      Time,
+     *      notAfter       Time }
      *
-     * CertificateValidityDate ::= CHOICE {
-     *     utcTime        UTCTime,
-     *     generalTime    GeneralizedTime }
+     * Time ::= CHOICE {
+     *      utcTime        UTCTime,
+     *      generalTime    GeneralizedTime }
      * 
* * @throws CertificateExpiredException if the certificate has expired. @@ -168,6 +168,51 @@ public abstract void checkValidity() public abstract void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException; + /** + * Checks that the given date (represented as an {@code Instant}) is within + * the certificate's validity period. In other words, this determines + * whether the certificate would be valid at the given instant. + * + * @apiNote Subclasses should override this method to directly process an + * instant. + * + * @implSpec + * The default implementation converts the specified {@code Instant} to + * a {@code Date} using the {@link Date#from(Instant)} method and calls + * {@code checkValidity(Date)} on the result. Note that converting to a + * {@code Date} will cause any excess nanoseconds in the instant to be + * truncated. If {@code instant} falls outside the range representable by + * {@code Date}, the nearest {@code Date} is used. For instants too large + * to be represented as a {@code Date}, {@code new Date(Long.MAX_VALUE)} + * is used, and for instants too small to be represented as a {@code Date}, + * {@code new Date(Long.MIN_VALUE)} is used. + * + * @param instant the {@code Instant} to check against to see if this + * certificate is valid at that instant. + * + * @throws CertificateExpiredException if the certificate has expired + * with respect to the {@code instant} supplied. + * @throws CertificateNotYetValidException if the certificate is not + * yet valid with respect to the {@code instant} supplied. + * @throws NullPointerException if the supplied instant is {@code null}. + * + * @see #checkValidity() + * @since 28 + */ + public void checkValidity(Instant instant) + throws CertificateExpiredException, CertificateNotYetValidException { + + Date date; + if (instant.isBefore(Instant.ofEpochMilli(Long.MIN_VALUE))) { + date = new Date(Long.MIN_VALUE); + } else if (instant.isAfter(Instant.ofEpochMilli(Long.MAX_VALUE))) { + date = new Date(Long.MAX_VALUE); + } else { + date = Date.from(instant); + } + checkValidity(date); + } + /** * Gets the {@code version} (version number) value from the * certificate. @@ -302,34 +347,59 @@ public X500Principal getSubjectX500Principal() { /** * Gets the {@code notBefore} date from the validity period of * the certificate. - * The relevant ASN.1 definitions are: - *
-     * validity             Validity
      *
-     * Validity ::= SEQUENCE {
-     *     notBefore      CertificateValidityDate,
-     *     notAfter       CertificateValidityDate }
+     * @return the start date of the validity period.
+     * @see #checkValidity()
+     */
+    public abstract Date getNotBefore();
+
+    /**
+     * Gets the {@code notBefore} date as an {@code Instant} from the validity
+     * period of the certificate.
      *
-     * CertificateValidityDate ::= CHOICE {
-     *     utcTime        UTCTime,
-     *     generalTime    GeneralizedTime }
-     * 
+ * @apiNote Subclasses should override this method to directly return an + * instant. + * + * @implSpec + * The default implementation calls {@code getNotBefore()} + * and returns the output as an {@code Instant}. * * @return the start date of the validity period. - * @see #checkValidity + * @see #checkValidity() + * @since 28 */ - public abstract Date getNotBefore(); + public Instant getNotBeforeInstant() { + return getNotBefore().toInstant(); + } /** * Gets the {@code notAfter} date from the validity period of - * the certificate. See {@link #getNotBefore() getNotBefore} - * for relevant ASN.1 definitions. + * the certificate. * * @return the end date of the validity period. - * @see #checkValidity + * @see #checkValidity() */ public abstract Date getNotAfter(); + /** + * Gets the {@code notAfter} date as an {@code Instant} from the validity + * period of the certificate. + * + * @apiNote Subclasses should override this method to directly return an + * instant. + * + * @implSpec + * The default implementation calls {@code getNotAfter()} + * and returns the output as an {@code Instant}. + * + * @return the end date of the validity period. + * @see #checkValidity() + * @since 28 + */ + public Instant getNotAfterInstant() { + return getNotAfter().toInstant(); + } + /** * Gets the DER-encoded certificate information, the * {@code tbsCertificate} from this certificate. diff --git a/src/java.base/share/classes/java/util/zip/ZipOutputStream.java b/src/java.base/share/classes/java/util/zip/ZipOutputStream.java index d79b0a1bd9c2..9eb3b0d1011a 100644 --- a/src/java.base/share/classes/java/util/zip/ZipOutputStream.java +++ b/src/java.base/share/classes/java/util/zip/ZipOutputStream.java @@ -637,14 +637,6 @@ private void writeCEN(XEntry xentry) throws IOException { clen = commentBytes.length; } - // CEN header size + name length + comment length + extra length - // should not exceed 65,535 bytes per the PKWare APP.NOTE - // 4.4.10, 4.4.11, & 4.4.12. - long headerSize = (long)CENHDR + nlen + clen + elen; - if (headerSize > 0xFFFF ) { - throw new ZipException("invalid CEN header (bad header size)"); - } - // cen info-zip extended timestamp only outputs mtime // but set the flag for a/ctime, if present in loc int flagEXTT = 0; @@ -675,6 +667,15 @@ private void writeCEN(XEntry xentry) throws IOException { elen += 4; // + mtime (4) } } + + // CEN header size + name length + comment length + extra length + // should not exceed 65,535 bytes per the PKWare APP.NOTE + // 4.4.10, 4.4.11, & 4.4.12. + long headerSize = (long)CENHDR + nlen + clen + elen; + if (headerSize > 0xFFFF ) { + throw new ZipException("invalid CEN header (bad header size)"); + } + writeShort(elen); writeShort(clen); // file comment length writeShort(0); // starting disk number diff --git a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java index 7a643f55f5bc..e92410a053ed 100644 --- a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java +++ b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java @@ -132,10 +132,10 @@ public interface JavaLangAccess { /** * Registers a shutdown hook. * - * It is expected that this method with registerShutdownInProgress=true - * is only used to register DeleteOnExitHook since the first file - * may be added to the delete on exit list by the application shutdown - * hooks. + * It is expected that registerShutdownInProgress is false for the hook + * that runs application shutdown hooks. It may be true for other hooks, + * e.g. DeleteOnExitHook, as the first invocation of File.deleteOnExit + * may occur in an application shutdown hook. * * @param slot the slot in the shutdown hook array, whose element * will be invoked in order during shutdown diff --git a/src/java.base/share/classes/jdk/internal/event/ThrowableTracer.java b/src/java.base/share/classes/jdk/internal/event/ThrowableTracer.java index 6502cbc80020..f24225973699 100644 --- a/src/java.base/share/classes/jdk/internal/event/ThrowableTracer.java +++ b/src/java.base/share/classes/jdk/internal/event/ThrowableTracer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,21 +37,14 @@ public static void traceError(Class clazz, String message) { if (OutOfMemoryError.class.isAssignableFrom(clazz)) { return; } - if (ErrorThrownEvent.enabled() || ExceptionThrownEvent.enabled()) { - long timestamp = ErrorThrownEvent.timestamp(); - if (ErrorThrownEvent.enabled()) { - ErrorThrownEvent.commit(timestamp, message, clazz); - } - if (ExceptionThrownEvent.shouldThrottleCommit(timestamp)) { - ExceptionThrownEvent.commit(timestamp, message, clazz); - } + if (ErrorThrownEvent.enabled()) { + ErrorThrownEvent.commit(ErrorThrownEvent.timestamp(), message, clazz); } - numThrowables.incrementAndGet(); } public static void traceThrowable(Class clazz, String message) { if (ExceptionThrownEvent.enabled()) { - long timestamp = ErrorThrownEvent.timestamp(); + long timestamp = ExceptionThrownEvent.timestamp(); if (ExceptionThrownEvent.shouldThrottleCommit(timestamp)) { ExceptionThrownEvent.commit(timestamp, message, clazz); } diff --git a/src/java.base/share/classes/sun/nio/ch/Poller.java b/src/java.base/share/classes/sun/nio/ch/Poller.java index 0c43c2860b23..5ea0abef44bf 100644 --- a/src/java.base/share/classes/sun/nio/ch/Poller.java +++ b/src/java.base/share/classes/sun/nio/ch/Poller.java @@ -123,6 +123,10 @@ private static PollerGroup createPollerGroup() { case POLLER_PER_CARRIER -> new PollerPerCarrierPollerGroup(provider, writePollers); }; group.start(); + + // Register shutdown hook to initiate an orderly shutdown of the group + JLA.registerShutdownHook(2, true, group::shutdown); + return group; } catch (IOException ioe) { throw new UncheckedIOException(ioe); @@ -156,10 +160,11 @@ boolean isShutdown() { } /** - * Marks this poller for shutdown. + * Initiates an orderly shutdown of this poller. */ - private void setShutdown() { + void shutdown() { shutdown = true; + try { wakeupPoller(); } catch (IOException _) {} } /** @@ -196,11 +201,8 @@ int fdVal() { /** * Wakeup the poller thread if blocked in poll so it can shutdown. - * @throws UnsupportedOperationException if not supported */ - void wakeupPoller() throws IOException { - throw new UnsupportedOperationException(); - } + abstract void wakeupPoller() throws IOException; /** * Callback by the poll method when a file descriptor is polled. @@ -244,12 +246,20 @@ public static void stopPoll(Thread thread) { /** * Parks the current thread until a file descriptor is ready. + * + *

In POLLER_PER_CARRIER mode, does not park if the poller has shut down + * because its carrier terminated. This allows the caller to retry with another + * poller. + * + *

During VM termination, this method parks if the channel/socket is + * open, even if the poller has shut down, to prevent the caller from + * spinning as it retries the I/O operation. */ private void poll(Object blocker, int fdVal, long nanos, BooleanSupplier isOpen) throws IOException { startPoll(fdVal); try { - if (isOpen.getAsBoolean() && !isShutdown()) { + if (isOpen.getAsBoolean() && (!isShutdown() || POLLER_GROUP.isShutdown())) { if (nanos > 0) { LockSupport.parkNanos(blocker, nanos); } else { @@ -350,8 +360,9 @@ public String toString() { /** * A group of poller threads that support virtual threads polling file descriptors. */ - private static abstract class PollerGroup { + static abstract class PollerGroup { private final PollerProvider provider; + private volatile boolean shutdown; PollerGroup(PollerProvider provider) { this.provider = provider; @@ -366,6 +377,27 @@ final PollerProvider provider() { */ abstract void start(); + /** + * Prepares for VM termination by initiating an orderly shutdown of the + * system-wide pollers running in platform threads. + */ + abstract void prepareForTermination(); + + /** + * Marks the poller group as shutdown and prepares for VM termination. + */ + final void shutdown() { + shutdown = true; + prepareForTermination(); + } + + /** + * Returns true if the poller group has been shutdown (VM termination). + */ + final boolean isShutdown() { + return shutdown; + } + /** * Parks the current thread until a file descriptor is ready for the given op. */ @@ -463,6 +495,12 @@ void start() { }); } + @Override + void prepareForTermination() { + Arrays.stream(readPollers).forEach(Poller::shutdown); + Arrays.stream(writePollers).forEach(Poller::shutdown); + } + private Poller readPoller(int fdVal) { int index = provider().fdValToIndex(fdVal, readPollers.length); return readPollers[index]; @@ -569,6 +607,11 @@ void start() { }); } + @Override + void prepareForTermination() { + masterPoller.shutdown(); + } + private Poller readPoller(int fdVal) { int index = provider().fdValToIndex(fdVal, readPollers.length); return readPollers[index]; @@ -662,6 +705,12 @@ void start() { }); } + @Override + void prepareForTermination() { + Arrays.stream(writePollers).forEach(Poller::shutdown); + masterPoller.shutdown(); + } + private Poller writePoller(int fdVal) { int index = provider().fdValToIndex(fdVal, writePollers.length); return writePollers[index]; @@ -752,12 +801,7 @@ private void subPollerLoop(Poller readPoller) { * Invoked by the carrier thread before it terminates. */ private void carrierTerminated(Poller readPoller) { - readPoller.setShutdown(); - try { - readPoller.wakeupPoller(); - } catch (Throwable e) { - e.printStackTrace(); - } + readPoller.shutdown(); } @Override diff --git a/src/java.base/share/classes/sun/security/pkcs/PKCS7.java b/src/java.base/share/classes/sun/security/pkcs/PKCS7.java index a6cd5eba4740..7356ea84c651 100644 --- a/src/java.base/share/classes/sun/security/pkcs/PKCS7.java +++ b/src/java.base/share/classes/sun/security/pkcs/PKCS7.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.io.*; import java.math.BigInteger; import java.net.URI; +import java.time.Instant; import java.util.*; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; @@ -805,7 +806,7 @@ public static byte[] generateSignedData( new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID), new PKCS9Attribute(PKCS9Attribute.SIGNING_TIME_OID, - new Date()), + Instant.now()), new PKCS9Attribute(PKCS9Attribute.CMS_ALGORITHM_PROTECTION_OID, derAp.toByteArray()), new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, diff --git a/src/java.base/share/classes/sun/security/pkcs/PKCS9Attribute.java b/src/java.base/share/classes/sun/security/pkcs/PKCS9Attribute.java index 86677e8cd718..f60648770295 100644 --- a/src/java.base/share/classes/sun/security/pkcs/PKCS9Attribute.java +++ b/src/java.base/share/classes/sun/security/pkcs/PKCS9Attribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -153,8 +153,8 @@ private static void add(ObjectIdentifier oid, boolean singleValued, DerOutputStream::putOctetString, DerValue.tag_OctetString); - add(SIGNING_TIME_OID, true, java.util.Date.class, - DerValue::getTime, + add(SIGNING_TIME_OID, true, java.time.Instant.class, + DerValue::getInstant, DerOutputStream::putTime, DerValue.tag_UtcTime, DerValue.tag_GeneralizedTime); diff --git a/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java index 01e0dc8aff97..ee4247680e0b 100644 --- a/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java +++ b/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java @@ -2393,8 +2393,14 @@ private void loadSafeContents(DerInputStream stream) " should have a value " + e.getMessage()); } if (attrId.equals(PKCS9FriendlyName_OID)) { + if (valSet.length == 0) { + throw new IOException("Empty attribute value set for " + attrId); + } alias = valSet[0].getBMPString(); } else if (attrId.equals(PKCS9LocalKeyId_OID)) { + if (valSet.length == 0) { + throw new IOException("Empty attribute value set for " + attrId); + } keyId = valSet[0].getOctetString(); } else if (attrId.equals(TrustedKeyUsage_OID)) { diff --git a/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java index afef70a29d5f..b4bcbe651ace 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -201,6 +201,15 @@ class DHServerKeyExchangeMessage extends HandshakeMessage { } if (x509Credentials == null) { + // Only anonymous key exchange is unsigned. For any other + // cipher suite the server Certificate message must have been + // received before the ServerKeyExchange message. + if (!chc.negotiatedCipherSuite.isAnonymous()) { + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + "No X.509 credentials negotiated for " + + "DH ServerKeyExchange: missing Certificate"); + } + // anonymous, no authentication, no signature if (m.hasRemaining()) { throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, diff --git a/src/java.base/share/classes/sun/security/ssl/DHasKEM.java b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java index 9f860af101e0..64342729fcac 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHasKEM.java +++ b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java @@ -51,6 +51,8 @@ import java.security.spec.XECPublicKeySpec; import java.util.Arrays; +import static sun.security.util.SecurityConstants.PROVIDER_VER; + /** * The DHasKEM class presents a KEM abstraction layer over traditional * DH-based key exchange, which can be used for either straight @@ -60,6 +62,22 @@ * when hybrid implementations are required. */ public class DHasKEM implements KEMSpi { + // This provider is used only by SunJSSE and is never installed in the + // system provider list. It exposes the internal DH-as-KEM adapter to + // Hybrid.KEMImpl through the public KEM API without exposing KEM.DH + // as a system provider service. + static final Provider PROVIDER = new ProviderImpl(); + + private static final class ProviderImpl extends Provider { + @java.io.Serial + private static final long serialVersionUID = 0L; + + ProviderImpl() { + super("DHAsKEM", PROVIDER_VER, + "Internal DH-as-KEM provider"); + put("KEM.DH", DHasKEM.class.getName()); + } + } @Override public EncapsulatorSpi engineNewEncapsulator( @@ -270,14 +288,20 @@ private SecretKey DH(String alg, PrivateKey skE, PublicKey pkR) // X25519/X448 shared secret. if (this == X25519 || this == X448) { byte[] s = secret.getEncoded(); - byte data = 0; - for (byte b : s) { - data |= b; - } - if (data == 0) { - // Trigger ILLEGAL_PARAMETER alert - throw new IllegalArgumentException( - "All-zero shared secret"); + try { + byte data = 0; + for (byte b : s) { + data |= b; + } + if (data == 0) { + // Trigger ILLEGAL_PARAMETER alert + throw new IllegalArgumentException( + "All-zero shared secret"); + } + } finally { + // getEncoded() returns a temporary copy of the + // shared secret. + Arrays.fill(s, (byte) 0); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java index 9a2c21db05c8..1e5250447c14 100644 --- a/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -244,6 +244,15 @@ class ECDHServerKeyExchangeMessage extends HandshakeMessage { } if (x509Credentials == null) { + // Only anonymous key exchange is unsigned. For any other + // cipher suite the server Certificate message must have been + // received before the ServerKeyExchange message. + if (!chc.negotiatedCipherSuite.isAnonymous()) { + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + "No X.509 credentials negotiated for " + + "ECDH ServerKeyExchange: missing Certificate"); + } + // anonymous, no authentication, no signature if (m.hasRemaining()) { throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, diff --git a/src/java.base/share/classes/sun/security/ssl/Hybrid.java b/src/java.base/share/classes/sun/security/ssl/Hybrid.java index 2d00973318a2..be21cc8b989f 100644 --- a/src/java.base/share/classes/sun/security/ssl/Hybrid.java +++ b/src/java.base/share/classes/sun/security/ssl/Hybrid.java @@ -25,6 +25,10 @@ package sun.security.ssl; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; + import sun.security.util.ArrayUtil; import sun.security.util.CurveDB; import sun.security.util.ECUtil; @@ -37,10 +41,9 @@ import javax.crypto.SecretKey; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidParameterException; import java.security.InvalidKeyException; -import java.security.Key; import java.security.KeyFactory; -import java.security.KeyFactorySpi; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyPairGeneratorSpi; @@ -52,15 +55,27 @@ import java.security.spec.*; import java.util.Arrays; import java.util.Locale; - -// The Hybrid class wraps two underlying algorithms (left and right sides) -// in a single TLS hybrid named group. -// It implements: -// - Hybrid KeyPair generation -// - Hybrid KeyFactory for decoding concatenated hybrid public keys -// - Hybrid KEM implementation for performing encapsulation and -// decapsulation over two underlying algorithms (traditional -// algorithm and post-quantum KEM algorithm) +import java.util.Objects; + +// The Hybrid class contains internal implementations for the TLS 1.3 +// hybrid key exchange named groups: X25519MLKEM768, SecP256r1MLKEM768, +// and SecP384r1MLKEM1024. It wraps two underlying algorithms (left and +// right sides) in a single TLS hybrid named group. +// +// These hybrid key exchange algorithms are registered in SunJCE so that +// SunJSSE can select them. They are not general purpose KEM algorithms. +// They are exposed through the JCA KeyPairGenerator and KEM APIs so that +// SunJSSE can use them. Applications should not use them as general purpose +// KEM algorithms. +// +// Their public key encoding is the TLS 1.3 key_share encoding, not an +// X.509 SubjectPublicKeyInfo encoding, and the algorithms have no object +// identifiers. Hence, the public key's getFormat() method must return "RAW", +// and getEncoded() must return the raw format of key_share encoding. +// +// A provider can represent a negotiated shared secret as an opaque SecretKey. +// If its key cannot be used with the selected TLS HKDF implementation, the +// provider must supply a compatible TLS HKDF implementation. public class Hybrid { @@ -81,63 +96,94 @@ private static AlgorithmParameterSpec getSpec(String name) { } } - private static KeyPairGenerator getKeyPairGenerator(String name) throws - NoSuchAlgorithmException { + // The layouts below describe only the TLS hybrid groups currently + // supported by the JDK. It assumes an EC component on the left or + // X25519 on the right, and ML-KEM as the only PQC component. + private static KeyPairGenerator getKeyPairGenerator(String name) + throws NoSuchAlgorithmException { if (name.startsWith("secp")) { name = "EC"; } return KeyPairGenerator.getInstance(name); } - private static KeyFactory getKeyFactory(String name) throws - NoSuchAlgorithmException { + private static KeyFactory getKeyFactory(String name) + throws NoSuchAlgorithmException { if (name.startsWith("secp")) { name = "EC"; } return KeyFactory.getInstance(name); } - /** - * Returns a KEM instance for each side of the hybrid algorithm. - * For traditional key exchange algorithms, we use the DH-based KEM - * implementation provided by DHasKEM class. - * For ML-KEM post-quantum algorithms, we obtain a KEM instance - * with "ML-KEM". This is done to work with 3rd-party providers that - * only have "ML-KEM" KEM algorithm. - */ - private static KEM getKEM(String name) throws NoSuchAlgorithmException { + private static KEM getKEM(String name) + throws NoSuchAlgorithmException { if (name.startsWith("secp") || name.equals("X25519")) { - return KEM.getInstance("DH", HybridProvider.PROVIDER); - } else { - return KEM.getInstance("ML-KEM"); + return KEM.getInstance("DH", DHasKEM.PROVIDER); } + return KEM.getInstance("ML-KEM"); } + /** + * A KeyPairGenerator implementation for a TLS 1.3 hybrid key exchange + * named group. + * + * This implementation is exposed through the JCA KeyPairGenerator API + * only so that TLS can obtain a key pair for a hybrid key_share. It is + * not a general purpose keypair generator. The generated public key has + * RAW format and its encoding is the TLS 1.3 key_share value. It is not + * an X.509 SubjectPublicKeyInfo value. + */ public static class KeyPairGeneratorImpl extends KeyPairGeneratorSpi { + private final String name; private final KeyPairGenerator left; private final KeyPairGenerator right; private final AlgorithmParameterSpec leftSpec; private final AlgorithmParameterSpec rightSpec; - public KeyPairGeneratorImpl(String leftAlg, String rightAlg) + public KeyPairGeneratorImpl(String name, String leftAlg, String rightAlg) throws NoSuchAlgorithmException { + this.name = name; left = getKeyPairGenerator(leftAlg); right = getKeyPairGenerator(rightAlg); leftSpec = getSpec(leftAlg); rightSpec = getSpec(rightAlg); + try { + initComponents(null); + } catch (InvalidAlgorithmParameterException e) { + throw new NoSuchAlgorithmException( + "Cannot initialize hybrid key pair generator", e); + } + } + + private void initComponents(SecureRandom random) + throws InvalidAlgorithmParameterException { + left.initialize(leftSpec, random); + right.initialize(rightSpec, random); } @Override public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { - left.initialize(leftSpec, random); - right.initialize(rightSpec, random); + if (!(params instanceof NamedParameterSpec namedSpec) || + !name.equalsIgnoreCase(namedSpec.getName())) { + throw new InvalidAlgorithmParameterException( + "Expected NamedParameterSpec for " + name); + } + initComponents(random); } @Override public void initialize(int keysize, SecureRandom random) { - // NO-OP (do nothing) + if (keysize != -1) { + throw new InvalidParameterException("keysize not supported"); + } + try { + initComponents(random); + } catch (InvalidAlgorithmParameterException e) { + throw new ProviderException( + "Cannot initialize hybrid key pair generator", e); + } } @Override @@ -145,75 +191,64 @@ public KeyPair generateKeyPair() { var kp1 = left.generateKeyPair(); var kp2 = right.generateKeyPair(); return new KeyPair( - new PublicKeyImpl("Hybrid", kp1.getPublic(), + new PublicKeyImpl(name, kp1.getPublic(), kp2.getPublic()), - new PrivateKeyImpl("Hybrid", kp1.getPrivate(), + new PrivateKeyImpl(name, kp1.getPrivate(), kp2.getPrivate())); } } - public static class KeyFactoryImpl extends KeyFactorySpi { + // Decodes the RAW TLS key_share accepted by the built-in hybrid KEM. + // This is not a JCA KeyFactory service. + private static final class RawPublicKeyDecoder { private final KeyFactory left; private final KeyFactory right; private final int leftlen; + private final int rightlen; private final String leftname; private final String rightname; - public KeyFactoryImpl(String left, String right) + private final String name; + + RawPublicKeyDecoder(String name, String left, String right) throws NoSuchAlgorithmException { + this.name = name; this.left = getKeyFactory(left); this.right = getKeyFactory(right); - this.leftlen = leftPublicLength(left); + this.leftlen = publicLength(left); + this.rightlen = publicLength(right); this.leftname = left; this.rightname = right; } - @Override - protected PublicKey engineGeneratePublic(KeySpec keySpec) - throws InvalidKeySpecException { - throw new InvalidKeySpecException("Not supported"); - } - - @Override - protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws - InvalidKeySpecException { - throw new InvalidKeySpecException("Not supported"); - } - - @Override - protected T engineGetKeySpec(Key key, - Class keySpec) throws InvalidKeySpecException { - throw new InvalidKeySpecException("Not supported"); - } - - private static int leftPublicLength(String name) { + private static int publicLength(String name) { return switch (name.toLowerCase(Locale.ROOT)) { case "secp256r1" -> 65; case "secp384r1" -> 97; + case "x25519" -> 32; case "ml-kem-768" -> 1184; + case "ml-kem-1024" -> 1568; default -> throw new IllegalArgumentException( - "Unknown named group: " + name); + "Unknown component algorithm: " + name); }; } - @Override - protected Key engineTranslateKey(Key inKey) throws InvalidKeyException { + PublicKeyImpl decode(PublicKey inKey) throws InvalidKeyException { if (inKey == null) { throw new InvalidKeyException("key must not be null"); } - if (inKey instanceof PublicKey - && "RAW".equalsIgnoreCase(inKey.getFormat())) { + if ("RAW".equalsIgnoreCase(inKey.getFormat())) { byte[] key = inKey.getEncoded(); if (key == null) { throw new InvalidKeyException( "Key contains null key data"); } - if (key.length <= leftlen) { + int expectedLen = leftlen + rightlen; + if (key.length != expectedLen) { throw new InvalidKeyException( - "Hybrid key length " + key.length + - " is too short and its left key length is " + - leftlen); + "Invalid hybrid key length " + key.length + + ", expected " + expectedLen); } byte[] leftKeyBytes = Arrays.copyOfRange(key, 0, leftlen); @@ -264,7 +299,7 @@ protected Key engineTranslateKey(Key inKey) throws InvalidKeyException { " algorithm: " + rightname); } - return new PublicKeyImpl("Hybrid", leftKey, rightKey); + return new PublicKeyImpl(name, leftKey, rightKey); } catch (Exception e) { throw new InvalidKeyException("Failed to decode " + "hybrid key", e); @@ -277,37 +312,61 @@ protected Key engineTranslateKey(Key inKey) throws InvalidKeyException { } } + /** + * A KEM implementation for a TLS 1.3 hybrid key exchange named group. + * + * This implementation is exposed through the JCA KEM API only so + * that TLS can perform hybrid key exchange. It is not a general + * purpose KEM. Its encapsulator accepts a public key with RAW + * format containing the TLS 1.3 key_share value, and it does not + * accept an X.509 SubjectPublicKeyInfo encoding. + */ public static class KEMImpl implements KEMSpi { + private final String name; private final KEM left; private final KEM right; + private final RawPublicKeyDecoder keyDecoder; - public KEMImpl(String left, String right) + public KEMImpl(String name, String left, String right) throws NoSuchAlgorithmException { + this.name = name; this.left = getKEM(left); this.right = getKEM(right); + this.keyDecoder = new RawPublicKeyDecoder(name, left, right); } @Override public EncapsulatorSpi engineNewEncapsulator(PublicKey publicKey, AlgorithmParameterSpec spec, SecureRandom secureRandom) throws InvalidAlgorithmParameterException, InvalidKeyException { - if (publicKey instanceof PublicKeyImpl pk) { - return new Handler(left.newEncapsulator(pk.left, secureRandom), - right.newEncapsulator(pk.right, secureRandom), - null, null); + if (spec != null) { + throw new InvalidAlgorithmParameterException( + "KEM parameters are not supported for " + name); + } + if (publicKey == null || + !name.equalsIgnoreCase(publicKey.getAlgorithm())) { + throw new InvalidKeyException("Incorrect public key algorithm"); } - throw new InvalidKeyException(); + PublicKeyImpl pk = publicKey instanceof PublicKeyImpl hybridKey + ? hybridKey : keyDecoder.decode(publicKey); + return new Handler(left.newEncapsulator(pk.left, secureRandom), + right.newEncapsulator(pk.right, secureRandom), null, null); } @Override public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, AlgorithmParameterSpec spec) throws InvalidAlgorithmParameterException, InvalidKeyException { - if (privateKey instanceof PrivateKeyImpl pk) { + if (spec != null) { + throw new InvalidAlgorithmParameterException( + "KEM parameters are not supported for " + name); + } + if (privateKey instanceof PrivateKeyImpl pk && + name.equalsIgnoreCase(pk.getAlgorithm())) { return new Handler(null, null, left.newDecapsulator(pk.left), right.newDecapsulator(pk.right)); } - throw new InvalidKeyException(); + throw new InvalidKeyException("Incorrect private key for " + name); } } @@ -332,17 +391,12 @@ private record Handler(KEM.Encapsulator le, KEM.Encapsulator re, public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) { int expectedSecretSize = engineSecretSize(); - if (!(from == 0 && to == expectedSecretSize)) { - throw new IllegalArgumentException( - "Invalid range for encapsulation: from = " + from + - " to = " + to + ", expected total secret size = " + - expectedSecretSize); - } + checkSecretRange(from, to, algorithm, expectedSecretSize); var left = le.encapsulate(); var right = re.encapsulate(); return new KEM.Encapsulated( - new SecretKeyImpl(left.key(), right.key()), + new SecretKeyImpl(algorithm, left.key(), right.key()), concat(left.encapsulation(), right.encapsulation()), null); } @@ -368,6 +422,8 @@ public int engineEncapsulationSize() { @Override public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, String algorithm) throws DecapsulateException { + Objects.requireNonNull(encapsulation, + "encapsulation must not be null"); int expectedEncSize = engineEncapsulationSize(); if (encapsulation.length != expectedEncSize) { throw new DecapsulateException( @@ -377,29 +433,51 @@ public SecretKey engineDecapsulate(byte[] encapsulation, int from, } int expectedSecretSize = engineSecretSize(); - if (!(from == 0 && to == expectedSecretSize)) { - throw new IllegalArgumentException( - "Invalid range for decapsulation: from = " + from + - " to = " + to + ", expected total secret size = " + - expectedSecretSize); - } + checkSecretRange(from, to, algorithm, expectedSecretSize); var left = Arrays.copyOf(encapsulation, ld.encapsulationSize()); var right = Arrays.copyOfRange(encapsulation, ld.encapsulationSize(), encapsulation.length); - return new SecretKeyImpl( - ld.decapsulate(left), - rd.decapsulate(right) + return new SecretKeyImpl(algorithm, + ld.decapsulate(left, 0, ld.secretSize(), "Generic"), + rd.decapsulate(right, 0, rd.secretSize(), "Generic") ); } + + private static void checkSecretRange(int from, int to, + String algorithm, int secretSize) { + Objects.requireNonNull(algorithm, "algorithm must not be null"); + if (from < 0 || from > to || to > secretSize) { + throw new IndexOutOfBoundsException( + "Invalid secret range: from = " + from + + ", to = " + to + ", secret size = " + + secretSize); + } + if (from != 0 || to != secretSize) { + throw new UnsupportedOperationException( + "Partial hybrid secrets are not supported"); + } + } } // Package-private - record SecretKeyImpl(SecretKey k1, SecretKey k2) - implements SecretKey { + static final class SecretKeyImpl implements SecretKey { + private static final long serialVersionUID = 1L; + + final SecretKey k1; + final SecretKey k2; + private final String algorithm; + private boolean destroyed; + + SecretKeyImpl(String algorithm, SecretKey k1, SecretKey k2) { + this.algorithm = algorithm; + this.k1 = k1; + this.k2 = k2; + } + @Override public String getAlgorithm() { - return "Generic"; + return algorithm; } @Override @@ -409,8 +487,44 @@ public String getFormat() { @Override public byte[] getEncoded() { + if (destroyed) { + throw new IllegalStateException("Key has been destroyed"); + } + // The component secrets are passed independently to HKDF so that + // a provider can keep either component opaque. return null; } + + @Override + public void destroy() { + if (!destroyed) { + KeyUtil.destroySecretKeys(k1, k2); + destroyed = true; + } + } + + @Override + public boolean isDestroyed() { + return destroyed; + } + + @Override + public boolean equals(Object obj) { + return this == obj || (obj instanceof SecretKeyImpl other && + algorithm.equalsIgnoreCase(other.algorithm) && + Objects.equals(k1, other.k1) && + Objects.equals(k2, other.k2)); + } + + @Override + public int hashCode() { + return Objects.hash(algorithm.toLowerCase(Locale.ENGLISH), k1, k2); + } + + private void writeObject(ObjectOutputStream out) throws IOException { + throw new NotSerializableException( + "Hybrid shared secret must not be serialized"); + } } /** @@ -464,8 +578,18 @@ static byte[] onlyKey(PublicKey key) { * Hybrid private key combines two underlying private keys (left and right). * It is for internal use only. The private keys should never be exported. */ - private record PrivateKeyImpl(String algorithm, PrivateKey left, - PrivateKey right) implements PrivateKey { + private static final class PrivateKeyImpl implements PrivateKey { + private static final long serialVersionUID = 1L; + + private final String algorithm; + private final PrivateKey left; + private final PrivateKey right; + + PrivateKeyImpl(String algorithm, PrivateKey left, PrivateKey right) { + this.algorithm = algorithm; + this.left = left; + this.right = right; + } @Override public String getAlgorithm() { @@ -479,11 +603,16 @@ public String getFormat() { return null; } - // getEncoded() returns an empty byte array because there is no + // getEncoded() returns null because there is no // standard encoding format for a hybrid private key. @Override public byte[] getEncoded() { return null; } + + private void writeObject(ObjectOutputStream out) throws IOException { + throw new NotSerializableException( + "Hybrid private key must not be serialized"); + } } } diff --git a/src/java.base/share/classes/sun/security/ssl/HybridProvider.java b/src/java.base/share/classes/sun/security/ssl/HybridProvider.java deleted file mode 100644 index 67549c6e1b07..000000000000 --- a/src/java.base/share/classes/sun/security/ssl/HybridProvider.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.ssl; - -import java.security.Provider; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Map; - -import static sun.security.util.SecurityConstants.PROVIDER_VER; - -// This is an internal provider used in the JSSE code for DH-as-KEM -// and Hybrid KEM support. It doesn't actually get installed in the -// system's list of security providers that is searched at runtime. -// JSSE loads this provider internally. -// It registers Hybrid KeyPairGenerator, KeyFactory, and KEM -// implementations for hybrid named groups as Provider services. - -public class HybridProvider { - - public static final Provider PROVIDER = new ProviderImpl(); - - private static final class ProviderImpl extends Provider { - @java.io.Serial - private static final long serialVersionUID = 0L; - - ProviderImpl() { - super("HybridAndDHAsKEM", PROVIDER_VER, - "Hybrid and DHAsKEM provider"); - put("KEM.DH", DHasKEM.class.getName()); - - // Hybrid KeyPairGenerator/KeyFactory/KEM - - // The order of shares in the concatenation for group name - // X25519MLKEM768 has been reversed as per RFC 10024. - var attrs = Map.of("name", "X25519MLKEM768", "left", "ML-KEM-768", - "right", "X25519"); - putService(new HybridService(this, "KeyPairGenerator", - "X25519MLKEM768", - "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", - null, attrs)); - putService(new HybridService(this, "KEM", - "X25519MLKEM768", - "sun.security.ssl.Hybrid$KEMImpl", - null, attrs)); - putService(new HybridService(this, "KeyFactory", - "X25519MLKEM768", - "sun.security.ssl.Hybrid$KeyFactoryImpl", - null, attrs)); - - attrs = Map.of("name", "SecP256r1MLKEM768", "left", "secp256r1", - "right", "ML-KEM-768"); - putService(new HybridService(this, "KeyPairGenerator", - "SecP256r1MLKEM768", - "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", - null, attrs)); - putService(new HybridService(this, "KEM", - "SecP256r1MLKEM768", - "sun.security.ssl.Hybrid$KEMImpl", - null, attrs)); - putService(new HybridService(this, "KeyFactory", - "SecP256r1MLKEM768", - "sun.security.ssl.Hybrid$KeyFactoryImpl", - null, attrs)); - - attrs = Map.of("name", "SecP384r1MLKEM1024", "left", "secp384r1", - "right", "ML-KEM-1024"); - putService(new HybridService(this, "KeyPairGenerator", - "SecP384r1MLKEM1024", - "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", - null, attrs)); - putService(new HybridService(this, "KEM", - "SecP384r1MLKEM1024", - "sun.security.ssl.Hybrid$KEMImpl", - null, attrs)); - putService(new HybridService(this, "KeyFactory", - "SecP384r1MLKEM1024", - "sun.security.ssl.Hybrid$KeyFactoryImpl", - null, attrs)); - } - } - - private static class HybridService extends Provider.Service { - - HybridService(Provider p, String type, String algo, String cn, - List aliases, Map attrs) { - super(p, type, algo, cn, aliases, attrs); - } - - @Override - public Object newInstance(Object ctrParamObj) - throws NoSuchAlgorithmException { - String type = getType(); - return switch (type) { - case "KeyPairGenerator" -> new Hybrid.KeyPairGeneratorImpl( - getAttribute("left"), getAttribute("right")); - case "KeyFactory" -> new Hybrid.KeyFactoryImpl( - getAttribute("left"), getAttribute("right")); - case "KEM" -> new Hybrid.KEMImpl( - getAttribute("left"), getAttribute("right")); - default -> throw new NoSuchAlgorithmException( - "Unexpected value: " + type); - }; - } - } -} diff --git a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java index 95b021b0f6ef..b6e2b5339135 100644 --- a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java +++ b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java @@ -35,12 +35,9 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; -import java.security.KeyFactory; import java.security.PrivateKey; -import java.security.Provider; import java.security.PublicKey; import java.security.SecureRandom; -import java.security.spec.X509EncodedKeySpec; import sun.security.util.KeyUtil; @@ -57,21 +54,19 @@ public class KAKeyDerivation implements SSLKeyDerivation { private final PrivateKey localPrivateKey; private final PublicKey peerPublicKey; private final byte[] keyshare; - private final Provider provider; // Constructor called by Key Agreement KAKeyDerivation(String algorithmName, HandshakeContext context, PrivateKey localPrivateKey, PublicKey peerPublicKey) { - this(algorithmName, null, context, localPrivateKey, + this(algorithmName, context, localPrivateKey, peerPublicKey, null); } // When the constructor called by KEM: store the client's public key or the // encapsulated message in keyshare. KAKeyDerivation(String algorithmName, - NamedGroup namedGroup, HandshakeContext context, PrivateKey localPrivateKey, PublicKey peerPublicKey, @@ -81,7 +76,6 @@ public class KAKeyDerivation implements SSLKeyDerivation { this.localPrivateKey = localPrivateKey; this.peerPublicKey = peerPublicKey; this.keyshare = keyshare; - this.provider = (namedGroup != null) ? namedGroup.getProvider() : null; } @Override @@ -148,10 +142,13 @@ private SecretKey deriveHandshakeSecret(String label, // NOTE: do not reuse the HKDF object for "TlsEarlySecret" for // the handshake secret key derivation (below) as it may not // work with the "sharedSecret" obj. + // Delayed provider selection lets a provider that created an + // opaque KEM secret supply the compatible TLS HKDF service. KDF hkdf = KDF.getInstance(hashAlg.hkdfAlgorithm); var spec = HKDFParameterSpec.ofExtract().addSalt(saltSecret); - if (sharedSecret instanceof Hybrid.SecretKeyImpl hsk) { - spec = spec.addIKM(hsk.k1()).addIKM(hsk.k2()); + if (sharedSecret instanceof Hybrid.SecretKeyImpl hybridSecret) { + spec = spec.addIKM(hybridSecret.k1) + .addIKM(hybridSecret.k2); } else { spec = spec.addIKM(sharedSecret); } @@ -161,6 +158,7 @@ private SecretKey deriveHandshakeSecret(String label, KeyUtil.destroySecretKeys(earlySecret, saltSecret); } } + /** * This method is called by the server to perform KEM encapsulation. * It uses the client's public key (sent by the client as a keyshare) @@ -182,28 +180,10 @@ KEM.Encapsulated encapsulate(String algorithm, SecureRandom random) // to TLS fatal alerts: // illegal_parameter alert or internal_error alert. try { - KeyFactory kf = (provider != null) ? - KeyFactory.getInstance(algorithmName, provider) : - KeyFactory.getInstance(algorithmName); - PublicKey pk; - try { - pk = (PublicKey) kf.translateKey( - KeyUtil.newRawPublicKey(algorithmName, keyshare)); - } catch (InvalidKeyException e) { - // Fallback to X.509 encoding if ML-KEM impl - // does not support translating from RAW - try { - pk = kf.generatePublic(new X509EncodedKeySpec( - KeyUtil.rawToX509(algorithmName, keyshare))); - } catch (GeneralSecurityException e2) { - e2.addSuppressed(e); - throw new InvalidKeyException(e2); - } - } - - KEM kem = (provider != null) ? - KEM.getInstance(algorithmName, provider) : - KEM.getInstance(algorithmName); + // Hybrid TLS keys have no X.509 encoding. The KEM receives the + // TLS key_share directly as a RAW public key. + PublicKey pk = KeyUtil.newRawPublicKey(algorithmName, keyshare); + KEM kem = KEM.getInstance(algorithmName); KEM.Encapsulator e = kem.newEncapsulator(pk, random); KEM.Encapsulated enc = e.encapsulate(); sharedSecret = enc.key(); @@ -245,9 +225,7 @@ private SecretKey t13DeriveKey(String type) // to TLS fatal alerts: // illegal_parameter alert or internal_error alert. try { - KEM kem = (provider != null) - ? KEM.getInstance(algorithmName, provider) - : KEM.getInstance(algorithmName); + KEM kem = KEM.getInstance(algorithmName); var decapsulator = kem.newDecapsulator(localPrivateKey); sharedSecret = decapsulator.decapsulate( keyshare, 0, decapsulator.secretSize(), diff --git a/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java index 2ce3c57e4124..dab8d9eed643 100644 --- a/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -121,10 +121,7 @@ static final class KEMReceiverPossession extends KEMPossession { // For KEM: This receiver side (client) generates a key pair. algName = ((NamedParameterSpec)namedGroup.keAlgParamSpec). getName(); - Provider provider = namedGroup.getProvider(); - KeyPairGenerator kpg = (provider != null) ? - KeyPairGenerator.getInstance(algName, provider) : - KeyPairGenerator.getInstance(algName); + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algName); kpg.initialize(namedGroup.keAlgParamSpec, random); KeyPair kp = kpg.generateKeyPair(); @@ -218,7 +215,7 @@ public SSLKeyDerivation createKeyDerivation( ng.equals(kcred.namedGroup)) { String name = ((NamedParameterSpec) ng.keAlgParamSpec).getName(); - return new KAKeyDerivation(name, ng, context, + return new KAKeyDerivation(name, context, kposs.getPrivateKey(), null, kcred.getKeyShare()); } diff --git a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java index 67780afea4ff..308dc46daf30 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -607,7 +607,7 @@ public byte[] produce(ConnectionContext context, String name = ((NamedParameterSpec) ng.keAlgParamSpec).getName(); KAKeyDerivation handshakeKD = new KAKeyDerivation( - name, ng, shc, null, null, + name, shc, null, null, kcred.getKeyShare()); var encaped = handshakeKD.encapsulate( "TlsHandshakeSecret", xp.getRandom()); diff --git a/src/java.base/share/classes/sun/security/ssl/NamedGroup.java b/src/java.base/share/classes/sun/security/ssl/NamedGroup.java index 094020602be4..730836380ffd 100644 --- a/src/java.base/share/classes/sun/security/ssl/NamedGroup.java +++ b/src/java.base/share/classes/sun/security/ssl/NamedGroup.java @@ -38,6 +38,7 @@ import java.util.Objects; import java.util.Set; import javax.crypto.KeyAgreement; +import javax.crypto.KEM; import javax.crypto.spec.DHParameterSpec; import sun.security.ssl.ECDHKeyExchange.ECDHEPossession; import sun.security.util.CurveDB; @@ -234,20 +235,17 @@ enum NamedGroup { X25519MLKEM768(0x11ec, "X25519MLKEM768", NamedGroupSpec.NAMED_GROUP_KEM, ProtocolVersion.PROTOCOLS_OF_13, - Hybrid.X25519_MLKEM768, - HybridProvider.PROVIDER), + Hybrid.X25519_MLKEM768), SECP256R1MLKEM768(0x11eb, "SecP256r1MLKEM768", NamedGroupSpec.NAMED_GROUP_KEM, ProtocolVersion.PROTOCOLS_OF_13, - Hybrid.SECP256R1_MLKEM768, - HybridProvider.PROVIDER), + Hybrid.SECP256R1_MLKEM768), SECP384R1MLKEM1024(0x11ed, "SecP384r1MLKEM1024", NamedGroupSpec.NAMED_GROUP_KEM, ProtocolVersion.PROTOCOLS_OF_13, - Hybrid.SECP384R1_MLKEM1024, - HybridProvider.PROVIDER), + Hybrid.SECP384R1_MLKEM1024), // Elliptic Curves (RFC 4492) // @@ -269,8 +267,6 @@ enum NamedGroup { final AlgorithmParameterSpec keAlgParamSpec; final AlgorithmParameters keAlgParams; final boolean isAvailable; - final Provider defaultProvider; - // performance optimization private static final Set KEY_AGREEMENT_PRIMITIVE_SET = Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.KEY_AGREEMENT)); @@ -279,23 +275,12 @@ enum NamedGroup { NamedGroupSpec namedGroupSpec, ProtocolVersion[] supportedProtocols, AlgorithmParameterSpec keAlgParamSpec) { - this(id, name, namedGroupSpec, supportedProtocols, keAlgParamSpec, - null); - } - - // Constructor used for all NamedGroup types - NamedGroup(int id, String name, - NamedGroupSpec namedGroupSpec, - ProtocolVersion[] supportedProtocols, - AlgorithmParameterSpec keAlgParamSpec, - Provider defaultProvider) { this.id = id; this.name = name; this.spec = namedGroupSpec; this.algorithm = namedGroupSpec.algorithm; this.supportedProtocols = supportedProtocols; this.keAlgParamSpec = keAlgParamSpec; - this.defaultProvider = defaultProvider; // Check if it is a supported named group. AlgorithmParameters algParams = null; @@ -312,14 +297,13 @@ enum NamedGroup { // Check the specific algorithm parameters. if (mediator) { try { - // Skip AlgorithmParameters for KEMs (not supported) - // Check KEM's availability via KeyFactory + // Skip AlgorithmParameters for KEMs (not supported). + // A direct hybrid KEM must provide both KeyPairGenerator + // and KEM. It does not require a KeyFactory because TLS + // passes a RAW key_share directly to the KEM encapsulator. if (namedGroupSpec == NamedGroupSpec.NAMED_GROUP_KEM) { - if (defaultProvider == null) { - KeyFactory.getInstance(name); - } else { - KeyFactory.getInstance(name, defaultProvider); - } + KeyPairGenerator.getInstance(name); + KEM.getInstance(name); } else { // ECDHE or others: use AlgorithmParameters as before algParams = AlgorithmParameters.getInstance( @@ -333,8 +317,8 @@ enum NamedGroup { if (SSLLogger.isOn() && SSLLogger.isOn(SSLLogger.Opt.HANDSHAKE)) { SSLLogger.warning( - "No AlgorithmParameters or KeyFactory for " + name, - exp); + "No AlgorithmParameters, KeyPairGenerator, " + + "or KEM for " + name, exp); } } else { // Please remove the following code if the XDH/X25519/X448 @@ -367,10 +351,6 @@ enum NamedGroup { this.keAlgParams = mediator ? algParams : null; } - Provider getProvider() { - return defaultProvider; - } - // // The next set of methods search & retrieve NamedGroups. // diff --git a/src/java.base/share/classes/sun/security/ssl/SSLLogger.java b/src/java.base/share/classes/sun/security/ssl/SSLLogger.java index 786cd01ac056..d9876b28c984 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLLogger.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLLogger.java @@ -555,8 +555,8 @@ private static String formatCertificate(Certificate certificate) { Debug.toString(x509.getSerialNumber()), x509.getSigAlgName(), x509.getIssuerX500Principal().toString(), - dateTimeFormat.format(x509.getNotBefore().toInstant()), - dateTimeFormat.format(x509.getNotAfter().toInstant()), + dateTimeFormat.format(x509.getNotBeforeInstant()), + dateTimeFormat.format(x509.getNotAfterInstant()), x509.getSubjectX500Principal().toString(), x509.getPublicKey().getAlgorithm() }; @@ -579,8 +579,8 @@ private static String formatCertificate(Certificate certificate) { Debug.toString(x509.getSerialNumber()), x509.getSigAlgName(), x509.getIssuerX500Principal().toString(), - dateTimeFormat.format(x509.getNotBefore().toInstant()), - dateTimeFormat.format(x509.getNotAfter().toInstant()), + dateTimeFormat.format(x509.getNotBeforeInstant()), + dateTimeFormat.format(x509.getNotAfterInstant()), x509.getSubjectX500Principal().toString(), x509.getPublicKey().getAlgorithm(), Utilities.indent(extBuilder.toString()) diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java b/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java index e188f698f4b0..65d3e8569ddb 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -133,6 +133,15 @@ public void consume(ConnectionContext context, // The consuming happens in client side only. ClientHandshakeContext chc = (ClientHandshakeContext)context; + // Check for an unprocessed server Certificate message. If + // that handshake consumer is still present then that expected + // message was not sent. + if (chc.handshakeConsumers.containsKey( + SSLHandshake.CERTIFICATE.id)) { + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + "Unexpected ServerHelloDone handshake message."); + } + SSLConsumer certStatCons = chc.handshakeConsumers.remove( SSLHandshake.CERTIFICATE_STATUS.id); if (certStatCons != null) { diff --git a/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java index be5814acc501..19fa2584ad82 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,6 +92,15 @@ public void consume(ConnectionContext context, // clean up this consumer chc.handshakeConsumers.remove(SSLHandshake.SERVER_KEY_EXCHANGE.id); + // If the Certificate consumer is still registered, the server + // omitted the required Certificate message before sending + // ServerKeyExchange. + if (chc.handshakeConsumers.containsKey( + SSLHandshake.CERTIFICATE.id)) { + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + "Unexpected ServerKeyExchange handshake message."); + } + // Any receipt/consumption of the CertificateRequest before // ServerKeyExchange is a state machine violation. We may not // know for sure if an early CR message is a violation though until @@ -131,4 +140,3 @@ public void consume(ConnectionContext context, } } } - diff --git a/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java b/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java index e58422073c61..5c63ce980d87 100644 --- a/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java @@ -239,6 +239,7 @@ byte[] encrypt(HandshakeContext hc, SSLSessionImpl session) { ByteBuffer aad = ByteBuffer.allocate(Integer.BYTES + 1); aad.putInt(key.num).put(compressed); + aad.flip(); c.updateAAD(aad); encrypted = c.doFinal(data); @@ -281,6 +282,7 @@ ByteBuffer decrypt(HandshakeContext hc) { byte compressed = data.get(); ByteBuffer aad = ByteBuffer.allocate(Integer.BYTES + 1); aad.putInt(keyID).put(compressed); + aad.flip(); c.updateAAD(aad); // use getOutputSize to avoid a ShortBufferException diff --git a/src/java.base/share/classes/sun/security/tools/keytool/CertAndKeyGen.java b/src/java.base/share/classes/sun/security/tools/keytool/CertAndKeyGen.java index 9b5d19e5f3bc..f4d5e65d18f5 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/CertAndKeyGen.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/CertAndKeyGen.java @@ -308,7 +308,8 @@ public X509Certificate getSelfCertificate (X500Name myname, Date firstDate, } CertificateValidity interval = - new CertificateValidity(firstDate,lastDate); + new CertificateValidity(firstDate.toInstant(), + lastDate.toInstant()); X509CertInfo info = new X509CertInfo(); // Add all mandatory attributes diff --git a/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/src/java.base/share/classes/sun/security/tools/keytool/Main.java index e5535be8f966..9460236365de 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1462,8 +1462,8 @@ private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStr Date firstDate = getStartDate(startDate); Date lastDate = getLastDate(firstDate, validity); - CertificateValidity interval = new CertificateValidity(firstDate, - lastDate); + CertificateValidity interval = new CertificateValidity(firstDate.toInstant(), + lastDate.toInstant()); PrivateKey privateKey = (PrivateKey)recoverKey(alias, storePass, keyPass).fst; @@ -1570,8 +1570,6 @@ private void doGenCRL(PrintStream out) Date firstDate = getStartDate(startDate); Date lastDate = getLastDate(firstDate, validity); - CertificateValidity interval = new CertificateValidity(firstDate, - lastDate); PrivateKey privateKey = (PrivateKey)recoverKey(alias, storePass, keyPass).fst; @@ -3241,8 +3239,9 @@ private void doSelfCert(String alias, String dname, String sigAlgName) // Extend its validity Date firstDate = getStartDate(startDate); Date lastDate = getLastDate(firstDate, validity); - CertificateValidity interval = new CertificateValidity(firstDate, - lastDate); + CertificateValidity interval = + new CertificateValidity(firstDate.toInstant(), + lastDate.toInstant()); certInfo.setValidity(interval); // Make new serial number diff --git a/src/java.base/share/classes/sun/security/util/DerInputStream.java b/src/java.base/share/classes/sun/security/util/DerInputStream.java index e0519f0fa098..3243ba61d384 100644 --- a/src/java.base/share/classes/sun/security/util/DerInputStream.java +++ b/src/java.base/share/classes/sun/security/util/DerInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.io.InputStream; import java.io.IOException; import java.math.BigInteger; +import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.Optional; @@ -189,18 +190,26 @@ public String getGeneralString() throws IOException { return getDerValue().getGeneralString(); } - public Date getTime() throws IOException { - return getDerValue().getTime(); + public Instant getInstant() throws IOException { + return getDerValue().getInstant(); } public Date getUTCTime() throws IOException { return getDerValue().getUTCTime(); } + public Instant getUTCInstant() throws IOException { + return getDerValue().getUTCInstant(); + } + public Date getGeneralizedTime() throws IOException { return getDerValue().getGeneralizedTime(); } + public Instant getGeneralizedInstant() throws IOException { + return getDerValue().getGeneralizedInstant(); + } + // Read a series of DerValue objects which is the sub-elements // of a SEQUENCE and SET. diff --git a/src/java.base/share/classes/sun/security/util/DerOutputStream.java b/src/java.base/share/classes/sun/security/util/DerOutputStream.java index 0cb7bc46f06b..47d278f3da39 100644 --- a/src/java.base/share/classes/sun/security/util/DerOutputStream.java +++ b/src/java.base/share/classes/sun/security/util/DerOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,9 +28,11 @@ import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.charset.Charset; -import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.Date; -import java.util.TimeZone; import java.util.Comparator; import java.util.Arrays; import java.util.Locale; @@ -483,20 +485,31 @@ private DerOutputStream writeString(String s, byte stringTag, Charset charset) { } /** - * 1/1/1950 is the lowest date that RFC 2630 serializes to UTC time + * 1/1/1950 00:00:00 is the lowest date that RFC 2630 serializes to UTC time */ - private static final Date utcLow = new Date(-631152000000L); // Dates before 1/1/1950 + private static final Instant utcLow = Instant.ofEpochSecond(-631152000L); /** - * 12/31/2049 is the highest date that RFC 2630 serializes to UTC time + * 12/31/2049 23:59:59 is the highest date that RFC 2630 serializes to UTC time */ - private static final Date utcHigh = new Date(2524607999000L); + private static final Instant utcHigh = Instant.ofEpochSecond(2524607999L); /** - * Takes a Date and chooses UTC or GeneralizedTime as per RFC 2630 + * 1/1/0001 00:00:00 is the lowest date representable by GeneralizedTime */ - public DerOutputStream putTime(Date d) { - return (d.before(utcLow) || d.after(utcHigh)) ? putGeneralizedTime(d) : putUTCTime(d); + private static final Instant generalizedLow = Instant.ofEpochSecond(-62135596800L); + + /** + * 12/31/9999 23:59:59 is the highest date representable by GeneralizedTime + */ + private static final Instant generalizedHigh = Instant.ofEpochSecond(253402300799L); + + /** + * Takes an instant and chooses UTC or GeneralizedTime as per RFC 2630. + */ + public DerOutputStream putTime(Instant d) { + d = d.truncatedTo(ChronoUnit.SECONDS); + return (d.isBefore(utcLow) || d.isAfter(utcHigh)) ? putGeneralizedTime(d) : putUTCInstant(d); } /** @@ -506,6 +519,16 @@ public DerOutputStream putTime(Date d) { * and with seconds (even if seconds=0) as per RFC 5280. */ public DerOutputStream putUTCTime(Date d) { + return putUTCInstant(d.toInstant()); + } + + /** + * Marshals a DER UTC time/date value. + * + *

YYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time + * and with seconds (even if seconds=0) as per RFC 5280. + */ + public DerOutputStream putUTCInstant(Instant d) { return putTime(d, DerValue.tag_UtcTime); } @@ -516,6 +539,16 @@ public DerOutputStream putUTCTime(Date d) { * and with seconds (even if seconds=0) as per RFC 5280. */ public DerOutputStream putGeneralizedTime(Date d) { + return putGeneralizedTime(d.toInstant()); + } + + /** + * Marshals a DER Generalized Time/date value. + * + *

YYYYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time + * and with seconds (even if seconds=0) as per RFC 5280. + */ + public DerOutputStream putGeneralizedTime(Instant d) { return putTime(d, DerValue.tag_GeneralizedTime); } @@ -526,25 +559,34 @@ public DerOutputStream putGeneralizedTime(Date d) { * @param d the date to be marshalled * @param tag the tag for UTC Time or Generalized Time */ - private DerOutputStream putTime(Date d, byte tag) { + private DerOutputStream putTime(Instant d, byte tag) { /* * Format the date. */ - - TimeZone tz = TimeZone.getTimeZone("GMT"); String pattern; + d = d.truncatedTo(ChronoUnit.SECONDS); + if (tag == DerValue.tag_UtcTime) { pattern = "yyMMddHHmmss'Z'"; + if (d.isBefore(utcLow) || d.isAfter(utcHigh)) { + throw new IllegalArgumentException( + "Instant " + d + " cannot be represented as UTC time"); + } } else { tag = DerValue.tag_GeneralizedTime; pattern = "yyyyMMddHHmmss'Z'"; + if (d.isBefore(generalizedLow) || d.isAfter(generalizedHigh)) { + throw new IllegalArgumentException( + "Instant " + d + " cannot be represented as GeneralizedTime"); + } } - SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US); - sdf.setTimeZone(tz); - byte[] time = (sdf.format(d)).getBytes(ISO_8859_1); + DateTimeFormatter dateTimeFormatter = + DateTimeFormatter.ofPattern(pattern, Locale.US); + byte[] time = d.atZone(ZoneId.of("GMT")).format(dateTimeFormatter) + .getBytes(ISO_8859_1); /* * Write the formatted date. diff --git a/src/java.base/share/classes/sun/security/util/DerValue.java b/src/java.base/share/classes/sun/security/util/DerValue.java index 8d86c8dd1439..1bfb3656ef06 100644 --- a/src/java.base/share/classes/sun/security/util/DerValue.java +++ b/src/java.base/share/classes/sun/security/util/DerValue.java @@ -33,6 +33,7 @@ import java.io.*; import java.math.BigInteger; import java.nio.charset.Charset; +import java.time.Instant; import java.util.*; import static java.nio.charset.StandardCharsets.ISO_8859_1; @@ -899,11 +900,11 @@ public void getNull() throws IOException { } /** - * Private helper routine to extract time from the der value. + * Private helper routine to extract time from the der value as an Instant. * @param generalized true if Generalized Time is to be read, false * if UTC Time is to be read. */ - private Date getTimeInternal(boolean generalized) throws IOException { + private Instant getTimeInternal(boolean generalized) throws IOException { /* * UTC time encoded as ASCII chars: @@ -1075,7 +1076,7 @@ private Date getTimeInternal(boolean generalized) throws IOException { default: throw new IOException("Parse " + type + " time, garbage offset"); } - return new Date(time); + return Instant.ofEpochMilli(time); } /** @@ -1091,11 +1092,11 @@ private static int toDigit(byte b, String type) throws IOException { } /** - * Determines whether Date was encoded as UTC or Generalized time and - * calls getUTCTime or getGeneralizedTime accordingly + * Determines whether {@code Instant} was encoded as UTC or Generalized time + * and calls getUTCInstant or getGeneralizedInstant accordingly. */ - public Date getTime() throws IOException { - return (tag == tag_UtcTime) ? getUTCTime() : getGeneralizedTime(); + public Instant getInstant() throws IOException { + return (tag == tag_UtcTime) ? getUTCInstant() : getGeneralizedInstant(); } /** @@ -1104,6 +1105,15 @@ public Date getTime() throws IOException { * @return the Date held in this DER value */ public Date getUTCTime() throws IOException { + return Date.from(getUTCInstant()); + } + + /** + * Returns an Instant if the DerValue is UtcTime. + * + * @return the Instant held in this DER value + */ + public Instant getUTCInstant() throws IOException { if (tag != tag_UtcTime) { throw new IOException("DerValue.getUTCTime, not a UtcTime: " + tag); } @@ -1120,6 +1130,15 @@ public Date getUTCTime() throws IOException { * @return the Date held in this DER value */ public Date getGeneralizedTime() throws IOException { + return Date.from(getGeneralizedInstant()); + } + + /** + * Returns an Instant if the DerValue is GeneralizedTime. + * + * @return the Instant held in this DER value + */ + public Instant getGeneralizedInstant() throws IOException { if (tag != tag_GeneralizedTime) { throw new IOException( "DerValue.getGeneralizedTime, not a GeneralizedTime: " + tag); diff --git a/src/java.base/share/classes/sun/security/x509/CertificateValidity.java b/src/java.base/share/classes/sun/security/x509/CertificateValidity.java index dab9ada4ece7..45c65d6c820f 100644 --- a/src/java.base/share/classes/sun/security/x509/CertificateValidity.java +++ b/src/java.base/share/classes/sun/security/x509/CertificateValidity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ import java.io.IOException; import java.security.cert.*; -import java.util.Date; +import java.time.Instant; import java.util.Objects; import sun.security.util.*; @@ -47,28 +47,28 @@ public class CertificateValidity implements DerEncoder { static final long YR_2050 = 2524608000000L; // Private data members - private final Date notBefore; - private final Date notAfter; + private final Instant notBefore; + private final Instant notAfter; // Returns the first time the certificate is valid. - public Date getNotBefore() { - return new Date(notBefore.getTime()); + public Instant getNotBefore() { + return notBefore; } // Returns the last time the certificate is valid. - public Date getNotAfter() { - return new Date(notAfter.getTime()); + public Instant getNotAfter() { + return notAfter; } /** * The constructor for this class for the specified interval. * - * @param notBefore the date and time before which the certificate - * is not valid - * @param notAfter the date and time after which the certificate is - * not valid + * @param notBefore the date and time as {@code Instant} before which the + * certificate is not valid + * @param notAfter the date and time as {@code Instant} after which the + * certificate is not valid */ - public CertificateValidity(Date notBefore, Date notAfter) { + public CertificateValidity(Instant notBefore, Instant notAfter) { this.notBefore = Objects.requireNonNull(notBefore); this.notAfter = Objects.requireNonNull(notAfter); } @@ -95,17 +95,17 @@ public CertificateValidity(DerInputStream in) throws IOException { throw new IOException("Invalid encoding for CertificateValidity"); if (seq[0].tag == DerValue.tag_UtcTime) { - notBefore = derVal.data.getUTCTime(); + notBefore = derVal.data.getUTCInstant(); } else if (seq[0].tag == DerValue.tag_GeneralizedTime) { - notBefore = derVal.data.getGeneralizedTime(); + notBefore = derVal.data.getGeneralizedInstant(); } else { throw new IOException("Invalid encoding for CertificateValidity"); } if (seq[1].tag == DerValue.tag_UtcTime) { - notAfter = derVal.data.getUTCTime(); + notAfter = derVal.data.getUTCInstant(); } else if (seq[1].tag == DerValue.tag_GeneralizedTime) { - notAfter = derVal.data.getGeneralizedTime(); + notAfter = derVal.data.getGeneralizedInstant(); } else { throw new IOException("Invalid encoding for CertificateValidity"); } @@ -129,13 +129,13 @@ public void encode(DerOutputStream out) { DerOutputStream pair = new DerOutputStream(); - if (notBefore.getTime() < YR_2050) { - pair.putUTCTime(notBefore); + if (notBefore.isBefore(Instant.ofEpochMilli(YR_2050))) { + pair.putUTCInstant(notBefore); } else pair.putGeneralizedTime(notBefore); - if (notAfter.getTime() < YR_2050) { - pair.putUTCTime(notAfter); + if (notAfter.isBefore(Instant.ofEpochMilli(YR_2050))) { + pair.putUTCInstant(notAfter); } else { pair.putGeneralizedTime(notAfter); } @@ -151,33 +151,29 @@ public void encode(DerOutputStream out) { */ public void valid() throws CertificateNotYetValidException, CertificateExpiredException { - Date now = new Date(); + final Instant now = Instant.now(); valid(now); } /** * Verify that the passed time is within the validity period. - * @param now the Date against which to compare the validity + * @param now the Instant against which to compare the validity * period. * * @exception CertificateExpiredException if the certificate has expired - * with respect to the Date supplied. + * with respect to the Instant supplied. * @exception CertificateNotYetValidException if the certificate is not - * yet valid with respect to the Date supplied. + * yet valid with respect to the Instant supplied. * */ - public void valid(Date now) + public void valid(Instant now) throws CertificateNotYetValidException, CertificateExpiredException { - /* - * we use the internal Dates rather than the passed in Date - * because someone could override the Date methods after() - * and before() to do something entirely different. - */ - if (notBefore.after(now)) { + + if (notBefore.isAfter(now)) { throw new CertificateNotYetValidException("NotBefore: " + notBefore.toString()); } - if (notAfter.before(now)) { + if (notAfter.isBefore(now)) { throw new CertificateExpiredException("NotAfter: " + notAfter.toString()); } diff --git a/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java b/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java index 86691a38aa29..37f859def542 100644 --- a/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java +++ b/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.security.cert.CertificateParsingException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; +import java.time.Instant; import java.util.Date; import java.util.Objects; @@ -64,8 +65,8 @@ public class PrivateKeyUsageExtension extends Extension { private static final byte TAG_BEFORE = 0; private static final byte TAG_AFTER = 1; - private Date notBefore = null; - private Date notAfter = null; + private Instant notBefore; + private Instant notAfter; // Encode this extension value. private void encodeThis() { @@ -96,12 +97,12 @@ private void encodeThis() { * The default constructor for PrivateKeyUsageExtension. At least one * of the arguments must be non null. * - * @param notBefore the date/time before which the private key - * should not be used - * @param notAfter the date/time after which the private key - * should not be used. + * @param notBefore the date/time as {@code Instant} before which the + * private key should not be used + * @param notAfter the date/time as {@code Instant} after which the private + * key should not be used. */ - public PrivateKeyUsageExtension(Date notBefore, Date notAfter) { + public PrivateKeyUsageExtension(Instant notBefore, Instant notAfter) { if (notBefore == null && notAfter == null) { throw new IllegalArgumentException( "notBefore and notAfter cannot both be null"); @@ -146,7 +147,7 @@ public PrivateKeyUsageExtension(Boolean critical, Object value) } opt.resetTag(DerValue.tag_GeneralizedTime); str = new DerInputStream(opt.toByteArray()); - notBefore = str.getGeneralizedTime(); + notBefore = str.getGeneralizedInstant(); } else if (opt.isContextSpecific(TAG_AFTER) && !opt.isConstructed()) { @@ -156,7 +157,7 @@ public PrivateKeyUsageExtension(Boolean critical, Object value) } opt.resetTag(DerValue.tag_GeneralizedTime); str = new DerInputStream(opt.toByteArray()); - notAfter = str.getGeneralizedTime(); + notAfter = str.getGeneralizedInstant(); } else throw new IOException("Invalid encoding of " + "PrivateKeyUsageExtension"); @@ -194,37 +195,46 @@ public String toString() { */ public void valid() throws CertificateNotYetValidException, CertificateExpiredException { - Date now = new Date(); - valid(now); + valid(Instant.now()); } /** - * Verify that the passed time is within the validity period. + * Verify that the passed in time is within the validity period. * * @exception CertificateExpiredException if the certificate has expired - * with respect to the Date supplied. + * with respect to the {@code Instant} supplied. * @exception CertificateNotYetValidException if the certificate is not - * yet valid with respect to the Date supplied. + * yet valid with respect to the {@code Instant} supplied. * */ - public void valid(Date now) + public void valid(Instant now) throws CertificateNotYetValidException, CertificateExpiredException { Objects.requireNonNull(now); - /* - * we use the internal Dates rather than the passed in Date - * because someone could override the Date methods after() - * and before() to do something entirely different. - */ - if (notBefore != null && notBefore.after(now)) { + + if (notBefore != null && notBefore.isAfter(now)) { throw new CertificateNotYetValidException("NotBefore: " + notBefore.toString()); } - if (notAfter != null && notAfter.before(now)) { + if (notAfter != null && notAfter.isBefore(now)) { throw new CertificateExpiredException("NotAfter: " + notAfter.toString()); } } + /** + * Verify that the passed in time is within the validity period. + * + * @exception CertificateExpiredException if the certificate has expired + * with respect to the Date supplied. + * @exception CertificateNotYetValidException if the certificate is not + * yet valid with respect to the Date supplied. + * + */ + public void valid(Date now) + throws CertificateNotYetValidException, CertificateExpiredException { + valid(now.toInstant()); + } + /** * Write the extension to the OutputStream. * @@ -241,11 +251,11 @@ public void encode(DerOutputStream out) { } public Date getNotBefore() { - return new Date(notBefore.getTime()); + return Date.from(notBefore); } public Date getNotAfter() { - return new Date(notAfter.getTime()); + return Date.from(notAfter); } /** diff --git a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java index 0f4388fb07b6..ada8b634d8ae 100644 --- a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java +++ b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.security.*; import java.security.cert.*; import java.security.cert.Certificate; +import java.time.Instant; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -503,8 +504,8 @@ public static X509CertImpl newSigned(X509CertInfo info, PrivateKey key, String a */ public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { - Date date = new Date(); - checkValidity(date); + Instant instant = Instant.now(); + checkValidity(instant); } /** @@ -521,6 +522,27 @@ public void checkValidity() * yet valid with respect to the date supplied. */ public void checkValidity(Date date) + throws CertificateExpiredException, CertificateNotYetValidException { + checkValidity(date.toInstant()); + } + + /** + * Checks that the specified instant is within the certificate's + * validity period, or basically if the certificate would be + * valid at the specified date/time. + * + * @param instant the Instant to check against to see if this certificate + * is valid at that date/time. + * + * @exception CertificateExpiredException if the certificate has expired + * with respect to the instant supplied. + * @exception CertificateNotYetValidException if the certificate is not + * yet valid with respect to the instant supplied. + * + * @since 28 + */ + @Override + public void checkValidity(Instant instant) throws CertificateExpiredException, CertificateNotYetValidException { CertificateValidity interval; @@ -531,7 +553,7 @@ public void checkValidity(Date date) } if (interval == null) throw new CertificateNotYetValidException("Null validity period"); - interval.valid(date); + interval.valid(instant); } /** @@ -661,6 +683,18 @@ public X500Principal getIssuerX500Principal() { * @return the start date of the validity period. */ public Date getNotBefore() { + return Date.from(getNotBeforeInstant()); + } + + /** + * Gets the notBefore instant from the validity period of the certificate. + * + * @return the start instant of the validity period. + * + * @since 28 + */ + @Override + public Instant getNotBeforeInstant() { return info.getValidity().getNotBefore(); } @@ -670,6 +704,18 @@ public Date getNotBefore() { * @return the end date of the validity period. */ public Date getNotAfter() { + return Date.from(getNotAfterInstant()); + } + + /** + * Gets the notAfter instant from the validity period of the certificate. + * + * @return the end instant of the validity period. + * + * @since 28 + */ + @Override + public Instant getNotAfterInstant() { return info.getValidity().getNotAfter(); } diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index 54a7c3b915a8..e45d191b7dbd 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -489,6 +489,39 @@ sun.security.krb5.disableReferrals=false # be overwritten with a System property (-Dsun.security.krb5.maxReferrals). sun.security.krb5.maxReferrals=5 +# +# Policy for Kerberos service transited field checking: +# +# In cross-realm authentication, if the service ticket includes a non-empty +# transited field but the ticket flags do not have TRANSIT-POLICY-CHECKED set, +# the application server should perform the transited-realm checks itself. +# This is required in Section 2.7 of RFC 4120. +# +# This property determines whether the server performs the transited-realm +# check when the service ticket does not have the TRANSIT-POLICY-CHECKED flag +# set. If the value is set to "true", the JDK performs the check when +# GSSContext.acceptSecContext is called to process the incoming context- +# establishment token, which contains the service ticket. +# +# The check uses the explicit paths configured in the [capaths] section of +# krb5.conf, or if that is not configured, uses an implicit hierarchical +# relationship between realm names. If any of the realms encoded in the +# transited field are not allowed, the context establishment will fail. +# If the value is set to "false", no check is performed. The default value +# of this property is "true". +# +# This property should be used at your own risk. +# +# If a system property of the same name is also specified, it supersedes the +# security property value defined here. +# +# Note: This property is currently used by the Java Kerberos GSS-API mechanism +# of the JDK Reference implementation. An application using native GSS-API +# does not use this property; instead it follows the policy of the underlying +# native GSS library. Support for this property is not guaranteed in other +# Java SE implementations. +sun.security.krb5.acceptor.checkTransitedPolicy = true + # # This property contains a list of disabled EC Named Curves that can be included # in the jdk.[tls|certpath|jar].disabledAlgorithms properties. To include this diff --git a/src/java.base/share/legal/zlib.md b/src/java.base/share/legal/zlib.md index c729c4248d48..d346a4d0c986 100644 --- a/src/java.base/share/legal/zlib.md +++ b/src/java.base/share/legal/zlib.md @@ -1,4 +1,4 @@ -## zlib v1.3.2 +## zlib v1.4 ### zlib License

diff --git a/src/java.base/share/native/libzip/zip_util.c b/src/java.base/share/native/libzip/zip_util.c
index 0e6e0da91f2f..cf4fba5f5814 100644
--- a/src/java.base/share/native/libzip/zip_util.c
+++ b/src/java.base/share/native/libzip/zip_util.c
@@ -477,9 +477,9 @@ growMetaNames(jzfile *zip)
     jint i;
     /* double the meta names array */
     const jint new_metacount = zip->metacount << 1;
-    zip->metanames =
-        realloc(zip->metanames, new_metacount * sizeof(zip->metanames[0]));
-    if (zip->metanames == NULL) return -1;
+    char** new_metanames = realloc(zip->metanames, new_metacount * sizeof(zip->metanames[0]));
+    if (new_metanames == NULL) return -1;
+    zip->metanames = new_metanames;
     for (i = zip->metacount; i < new_metacount; i++)
         zip->metanames[i] = NULL;
     zip->metacurrent = zip->metacount;
@@ -954,7 +954,9 @@ readCENHeader(jzfile *zip, jlong cenpos, jint bufsize)
     if (readFullyAt(zfd, cen, bufsize, cenpos) == -1)     goto Catch;
     censize = CENSIZE(cen);
     if (censize <= bufsize) return cen;
-    if ((cen = realloc(cen, censize)) == NULL)              goto Catch;
+    char* new_cen = realloc(cen, censize);
+    if (new_cen == NULL) goto Catch;
+    cen = new_cen;
     if (readFully(zfd, cen+bufsize, censize-bufsize) == -1) goto Catch;
     return cen;
 
diff --git a/src/java.base/share/native/libzip/zlib/ChangeLog b/src/java.base/share/native/libzip/zlib/ChangeLog
index 312753edadef..228a03afa1d7 100644
--- a/src/java.base/share/native/libzip/zlib/ChangeLog
+++ b/src/java.base/share/native/libzip/zlib/ChangeLog
@@ -1,6 +1,37 @@
 
                 ChangeLog file for zlib
 
+Changes in 1.4 (4 Nov 2026)
+- Change CMake library names on MSVC
+- Return z_off_t default to long for portability
+- Fail gzopen() with "x" if O_EXCL not available
+- Deliver all gzip data before reporting error
+- Fix gzwrite() buffer overflow (CVE-2026-85091)
+- Fix inflateGetDictionary() write past buffer on invalid window size
+- Fix window write overrun after inflateSync()
+- Fix read before provided data after repeated inflatePrime()'s
+- Fix write past pending buffer after repeated deflatePrime()'s
+- Fix copy of uninitialized memory by inflateBack() on invalid data
+- Fix copy of uninitialized memory after gzseek() as first write action
+- Fix read outside window after a deflateResetKeep() mid-stream
+- Avoid out-of-bounds pointer arithmetic in infback9() (CVE-2026-4738)
+- Fix several vulnerabilities in contrib/minizip
+- Fix truncated stream detection in gzread()
+- Fix pending skip handling in gzread()
+- Fix loss of zero fill on repeated gzseek()'s when writing
+- Fix inaccurate total_in after Z_NEED_DICT returned
+- Detect and report bad deflateSetDictionary() calls
+- Avoid undefined behaviors in C language usage
+- Fix minizip extra field overflows when almost full and need Zip64
+- Don't assume NULL is defined in compress.c and uncompr.c
+- Use the generated zconf.h when building test programs out of tree
+- Improve portability and functionality of CMake builds
+- Provide 64-bit file offsets on Windows with #defines as on Linux
+- Improve portability to Android, AIX, PowerPC, s390x, and Windows
+- Use a PCG random number generator instead of rand() in minizip
+- Clarify documentation
+- (See https://github.com/madler/zlib for all 195 commits)
+
 Changes in 1.3.2 (17 Feb 2026)
 - Continued rewrite of CMake build [Vollstrecker]
 - Various portability improvements
diff --git a/src/java.base/share/native/libzip/zlib/README b/src/java.base/share/native/libzip/zlib/README
index 2b1e6f36fe3e..265c8b47d316 100644
--- a/src/java.base/share/native/libzip/zlib/README
+++ b/src/java.base/share/native/libzip/zlib/README
@@ -1,6 +1,6 @@
 ZLIB DATA COMPRESSION LIBRARY
 
-zlib 1.3.2 is a general purpose data compression library.  All the code is
+zlib 1.4 is a general purpose data compression library.  All the code is
 thread safe (though see the FAQ for caveats).  The data format used by the zlib
 library is described by RFCs (Request for Comments) 1950 to 1952 at
 https://datatracker.ietf.org/doc/html/rfc1950 (zlib format), rfc1951 (deflate
@@ -31,7 +31,7 @@ Mark Nelson  wrote an article about zlib for the Jan.  1997
 issue of Dr.  Dobb's Journal; a copy of the article is available at
 https://zlib.net/nelson/ .
 
-The changes made in version 1.3.2 are documented in the file ChangeLog.
+The changes made in version 1.4 are documented in the file ChangeLog.
 
 Unsupported third party contributions are provided in directory contrib/ .
 
diff --git a/src/java.base/share/native/libzip/zlib/compress.c b/src/java.base/share/native/libzip/zlib/compress.c
index 54346ad2a2f1..832788e9248f 100644
--- a/src/java.base/share/native/libzip/zlib/compress.c
+++ b/src/java.base/share/native/libzip/zlib/compress.c
@@ -52,8 +52,8 @@ int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
     const uInt max = (uInt)-1;
     z_size_t left;
 
-    if ((sourceLen > 0 && source == NULL) ||
-        destLen == NULL || (*destLen > 0 && dest == NULL))
+    if ((sourceLen > 0 && source == Z_NULL) ||
+        destLen == Z_NULL || (*destLen > 0 && dest == Z_NULL))
         return Z_STREAM_ERROR;
 
     left = *destLen;
diff --git a/src/java.base/share/native/libzip/zlib/deflate.c b/src/java.base/share/native/libzip/zlib/deflate.c
index 0ec56ec5691f..5918d8cb00b4 100644
--- a/src/java.base/share/native/libzip/zlib/deflate.c
+++ b/src/java.base/share/native/libzip/zlib/deflate.c
@@ -76,7 +76,7 @@
 #include "deflate.h"
 
 const char deflate_copyright[] =
-   " deflate 1.3.2 Copyright 1995-2026 Jean-loup Gailly and Mark Adler ";
+   " deflate 1.4 Copyright 1995-2026 Jean-loup Gailly and Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -469,7 +469,6 @@ int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
 
     s->wrap = wrap;
-    s->gzhead = Z_NULL;
     s->w_bits = (uInt)windowBits;
     s->w_size = 1 << s->w_bits;
     s->w_mask = s->w_size - 1;
@@ -592,7 +591,8 @@ int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary,
         return Z_STREAM_ERROR;
     s = strm->state;
     wrap = s->wrap;
-    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
+    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead ||
+        (wrap == 0 && (long)s->strstart != s->block_start))
         return Z_STREAM_ERROR;
 
     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
@@ -695,7 +695,20 @@ int ZEXPORT deflateResetKeep(z_streamp strm) {
         adler32(0L, Z_NULL, 0);
     s->last_flush = -2;
 
-    _tr_init(s);
+    s->gzhead = Z_NULL;
+
+    {
+        /* Retain the hash work done for level 0. */
+        uInt matches = s->level == 0 ? s->matches : 0;
+        _tr_init(s);
+        s->matches = matches;
+    }
+
+    /* Keep the window and the hash, but drop what was left unfinished */
+    s->block_start = (long)s->strstart;
+    s->lookahead = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
 
     return Z_OK;
 }
@@ -707,6 +720,7 @@ local void lm_init(deflate_state *s) {
     s->window_size = (ulg)2L*s->w_size;
 
     CLEAR_HASH(s);
+    s->matches = 0;             /* the hash is clear */
 
     /* Set the default configuration parameters:
      */
@@ -769,18 +783,23 @@ int ZEXPORT deflateUsed(z_streamp strm, int *bits) {
 int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) {
     deflate_state *s;
     int put;
+    int need;
 
     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
     s = strm->state;
-#ifdef LIT_MEM
-    if (bits < 0 || bits > 16 ||
-        (uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3))
+    if (bits < 0 || bits > 16)
         return Z_BUF_ERROR;
-#else
-    if (bits < 0 || bits > 16 ||
-        s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
+    if (s->pending_out != s->pending_buf) {
+        /* move partially flushed pending output to buffer start */
+        Bytef *to = s->pending_buf, *from = s->pending_out;
+        ulg n = s->pending;
+        while (n--)
+            *to++ = *from++;
+        s->pending_out = s->pending_buf;
+    }
+    need = (s->bi_valid + bits) >> 3;
+    if (s->pending_buf_size - s->pending < (ulg)need)
         return Z_BUF_ERROR;
-#endif
     do {
         put = Buf_size - s->bi_valid;
         if (put > bits)
@@ -1340,39 +1359,49 @@ int ZEXPORT deflateEnd(z_streamp strm) {
  */
 int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {
 #ifdef MAXSEG_64K
-    (void)dest;
     (void)source;
+    if (dest != Z_NULL)
+        dest->state = Z_NULL;
     return Z_STREAM_ERROR;
 #else
     deflate_state *ds;
     deflate_state *ss;
 
-
-    if (deflateStateCheck(source) || dest == Z_NULL) {
+    if (dest == Z_NULL)
+        return Z_STREAM_ERROR;
+    if (deflateStateCheck(source)) {
+        dest->state = Z_NULL;
         return Z_STREAM_ERROR;
     }
 
     ss = source->state;
 
-    zmemcpy(dest, source, sizeof(z_stream));
-
-    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
-    if (ds == Z_NULL) return Z_MEM_ERROR;
-    zmemzero(ds, sizeof(deflate_state));
-    dest->state = (struct internal_state FAR *) ds;
+    ds = (deflate_state *) ZALLOC(source, 1, sizeof(deflate_state));
+    if (ds == Z_NULL) {
+        dest->state = Z_NULL;
+        return Z_MEM_ERROR;
+    }
     zmemcpy(ds, ss, sizeof(deflate_state));
-    ds->strm = dest;
-
-    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
-    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
-    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
-    ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS);
-
+    ds->window = (Bytef *) ZALLOC(source, ds->w_size, 2*sizeof(Byte));
+    ds->prev   = (Posf *)  ZALLOC(source, ds->w_size, sizeof(Pos));
+    ds->head   = (Posf *)  ZALLOC(source, ds->hash_size, sizeof(Pos));
+    ds->pending_buf = (uchf *) ZALLOC(source, ds->lit_bufsize, LIT_BUFS);
     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
         ds->pending_buf == Z_NULL) {
-        deflateEnd (dest);
+        TRY_FREE(source, ds->pending_buf);
+        TRY_FREE(source, ds->head);
+        TRY_FREE(source, ds->prev);
+        TRY_FREE(source, ds->window);
+        ZFREE(source, ds);
+        dest->state = Z_NULL;
         return Z_MEM_ERROR;
     }
+
+    /* copy the stream and attach the new state */
+    zmemcpy(dest, source, sizeof(z_stream));
+    dest->state = (struct internal_state FAR *) ds;
+    ds->strm = dest;
+
     /* following zmemcpy's do not work for 16-bit MSDOS */
     zmemcpy(ds->window, ss->window, ss->high_water);
     zmemcpy(ds->prev, ss->prev,
@@ -1665,7 +1694,10 @@ local void check_match(deflate_state *s, IPos start, IPos match, int length) {
 /* Same but force premature exit if necessary. */
 #define FLUSH_BLOCK(s, last) { \
    FLUSH_BLOCK_ONLY(s, last); \
-   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
+   if (s->strm->avail_out == 0) { \
+      if (!(last)) return need_more; \
+      if (s->pending != 0 || s->wrap != 0) return finish_started; \
+   } \
 }
 
 /* Maximum stored block length in deflate format (not including header). */
@@ -1700,7 +1732,7 @@ local block_state deflate_stored(deflate_state *s, int flush) {
      * possible. If flushing, copy the remaining available input to next_out as
      * stored blocks, if there is enough space.
      */
-    int last = 0;
+    int last = 0, all;
     unsigned len, left, have;
     unsigned used = s->strm->avail_in;
     do {
@@ -1715,11 +1747,14 @@ local block_state deflate_stored(deflate_state *s, int flush) {
             /* maximum stored block length that will fit in avail_out: */
         have = s->strm->avail_out - have;
         left = (unsigned)(s->strstart - s->block_start);    /* window bytes */
-        if (len > (ulg)left + s->strm->avail_in)
+        if (left < len && s->strm->avail_in < len - left)
             len = left + s->strm->avail_in;     /* limit len to the input */
         if (len > have)
             len = have;                         /* limit len to the output */
 
+        /* all is true if len is all of the available input */
+        all = len >= left && len - left == s->strm->avail_in;
+
         /* If the stored block would be less than min_block in length, or if
          * unable to copy all of the available input when flushing, then try
          * copying to the window and the pending buffer instead. Also don't
@@ -1727,13 +1762,13 @@ local block_state deflate_stored(deflate_state *s, int flush) {
          */
         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
                                 flush == Z_NO_FLUSH ||
-                                len != left + s->strm->avail_in))
+                                !all))
             break;
 
         /* Make a dummy stored block in pending to get the header bytes,
          * including any pending bits. This also updates the debugging counts.
          */
-        last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
+        last = flush == Z_FINISH && all ? 1 : 0;
         _tr_stored_block(s, (char *)0, 0L, last);
 
         /* Replace the lengths in the dummy stored block with len. */
@@ -2038,7 +2073,8 @@ local block_state deflate_slow(deflate_state *s, int flush) {
             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
             /* Do not insert strings in hash table beyond this. */
 
-            check_match(s, s->strstart - 1, s->prev_match, (int)s->prev_length);
+            check_match(s, s->strstart - 1, s->prev_match,
+                        (int)s->prev_length);
 
             _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
                            s->prev_length - MIN_MATCH, bflush);
diff --git a/src/java.base/share/native/libzip/zlib/gzguts.h b/src/java.base/share/native/libzip/zlib/gzguts.h
index 0be646016ed8..70ca11af0bc3 100644
--- a/src/java.base/share/native/libzip/zlib/gzguts.h
+++ b/src/java.base/share/native/libzip/zlib/gzguts.h
@@ -116,8 +116,10 @@
 #        define vsnprintf _vsnprintf
 #      endif
 #    endif
-#  elif !defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L
-/* Otherwise if C89/90, assume no C99 snprintf() or vsnprintf() */
+#  elif (!defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L) && \
+        (!defined(__cplusplus) || __cplusplus < 201103L)
+/* Otherwise if C89/90 (and not C++11 or later), assume no C99 snprintf() or
+   vsnprintf() */
 #    ifndef NO_snprintf
 #      define NO_snprintf
 #    endif
@@ -152,14 +154,28 @@
 #  include 
 #  define zstrerror() gz_strwinerror((DWORD)GetLastError())
 #else
+#  include 
 #  ifndef NO_STRERROR
-#    include 
 #    define zstrerror() strerror(errno)
 #  else
 #    define zstrerror() "stdio error (consult errno)"
 #  endif
 #endif
 
+#ifdef EAGAIN
+#  ifdef EWOULDBLOCK
+#    define BLOCKED(e) ((e) == EAGAIN || (e) == EWOULDBLOCK)
+#  else
+#    define BLOCKED(e) ((e) == EAGAIN)
+#  endif
+#else
+#  ifdef EWOULDBLOCK
+#    define BLOCKED(e) ((e) == EWOULDBLOCK)
+#  else
+#    define BLOCKED(e) (0)
+#  endif
+#endif
+
 /* provide prototypes for these when building zlib without LFS */
 #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
     ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
@@ -238,3 +254,10 @@ char ZLIB_INTERNAL *gz_strwinerror(DWORD error);
    (possible z_off64_t types off_t, off64_t, and long are all signed) */
 unsigned ZLIB_INTERNAL gz_intmax(void);
 #define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
+
+/* largest value representable in z_off64_t */
+#ifndef CHAR_BIT
+#  define CHAR_BIT 8
+#endif
+#define GZ_OFF_MAX \
+    ((((z_off64_t)1 << (sizeof(z_off64_t) * CHAR_BIT - 2)) - 1) * 2 + 1)
diff --git a/src/java.base/share/native/libzip/zlib/gzlib.c b/src/java.base/share/native/libzip/zlib/gzlib.c
index 9489bcc1f12e..c62db8580075 100644
--- a/src/java.base/share/native/libzip/zlib/gzlib.c
+++ b/src/java.base/share/native/libzip/zlib/gzlib.c
@@ -92,9 +92,9 @@ char ZLIB_INTERNAL *gz_strwinerror(DWORD error) {
 /* Reset gzip file state */
 local void gz_reset(gz_statep state) {
     state->x.have = 0;              /* no output data available */
+    state->past = 0;                /* have not read past end yet */
     if (state->mode == GZ_READ) {   /* for reading ... */
         state->eof = 0;             /* not at end of file */
-        state->past = 0;            /* have not read past end yet */
         state->how = LOOK;          /* look for gzip header */
         state->junk = -1;           /* mark first member */
     }
@@ -112,9 +112,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
     gz_statep state;
     z_size_t len;
     int oflag = 0;
-#ifdef O_EXCL
     int exclusive = 0;
-#endif
 
     /* check input */
     if (path == NULL || mode == NULL)
@@ -160,11 +158,9 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
                 oflag |= O_CLOEXEC;
                 break;
 #endif
-#ifdef O_EXCL
             case 'x':
                 exclusive = 1;
                 break;
-#endif
             case 'f':
                 state->strategy = Z_FILTERED;
                 break;
@@ -220,10 +216,21 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
     /* if reading, direct == 1 for auto-detect, -1 for gzip only; if writing or
        appending, direct == 0 for gzip, 1 for transparent (copy in to out) */
 
+#ifndef O_EXCL
+    if (exclusive && state->mode != GZ_READ && fd < 0) {
+        /* exclusive creation request can't be honored -- fail out */
+        free(state);
+        return NULL;
+    }
+#endif
+
     /* save the path name for error messages */
 #ifdef WIDECHAR
-    if (fd == -2)
+    if (fd == -2) {
         len = wcstombs(NULL, path, 0);
+        if (len == (z_size_t)-1)
+            len = 0;            /* not representable in the current locale */
+    }
     else
 #endif
         len = strlen((const char *)path);
@@ -234,9 +241,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
     }
 #ifdef WIDECHAR
     if (fd == -2) {
-        if (len)
-            wcstombs(state->path, path, len + 1);
-        else
+        if (len == 0 || wcstombs(state->path, path, len + 1) != len)
             *(state->path) = 0;
     }
     else
@@ -245,7 +250,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
         (void)snprintf(state->path, len + 1, "%s", (const char *)path);
 #else
-        strcpy(state->path, path);
+        strcpy(state->path, (const char *)path);
 #endif
     }
 
@@ -279,9 +284,9 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
         if (oflag & O_NONBLOCK)
             fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
 #endif
-#ifdef O_CLOEXEC
+#if defined(O_CLOEXEC) && defined(FD_CLOEXEC)
         if (oflag & O_CLOEXEC)
-            fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | O_CLOEXEC);
+            fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
 #endif
         state->fd = fd;
     }
@@ -323,7 +328,7 @@ gzFile ZEXPORT gzdopen(int fd, const char *mode) {
     char *path;         /* identifier for error messages */
     gzFile gz;
 
-    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
+    if (fd < 0 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
         return NULL;
 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
     (void)snprintf(path, 7 + 3 * sizeof(int), "", fd);
@@ -390,7 +395,7 @@ int ZEXPORT gzrewind(gzFile file) {
 /* -- see zlib.h -- */
 z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
     unsigned n;
-    z_off64_t ret;
+    z_off64_t ret, pos;
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -408,18 +413,19 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
     if (whence != SEEK_SET && whence != SEEK_CUR)
         return -1;
 
-    /* normalize offset to a SEEK_CUR specification */
-    if (whence == SEEK_SET)
-        offset -= state->x.pos;
-    else {
-        offset += state->past ? 0 : state->skip;
-        state->skip = 0;
-    }
+    /* compute the absolute position */
+    pos = whence == SEEK_SET ? 0 :
+          state->x.pos + (state->past ? 0 : state->skip);
+    if (offset > GZ_OFF_MAX - pos)
+        return -1;                          /* would overflow z_off64_t */
+    if (offset < -pos)
+        return -1;                          /* before start of file */
+    pos += offset;
 
     /* if within raw area while reading, just go there */
-    if (state->mode == GZ_READ && state->how == COPY &&
-            state->x.pos + offset >= 0) {
-        ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR);
+    if (state->mode == GZ_READ && state->how == COPY) {
+        ret = LSEEK(state->fd, pos - state->x.pos - (z_off64_t)state->x.have,
+                    SEEK_CUR);
         if (ret == -1)
             return -1;
         state->x.have = 0;
@@ -428,20 +434,18 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
         state->skip = 0;
         gz_error(state, Z_OK, NULL);
         state->strm.avail_in = 0;
-        state->x.pos += offset;
-        return state->x.pos;
+        state->x.pos = pos;
+        return pos;
     }
 
-    /* calculate skip amount, rewinding if needed for back seek when reading */
-    if (offset < 0) {
+    /* rewind if needed for back seek when reading */
+    if (pos < state->x.pos) {
         if (state->mode != GZ_READ)         /* writing -- can't go backwards */
             return -1;
-        offset += state->x.pos;
-        if (offset < 0)                     /* before start of file! */
-            return -1;
-        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
+        if (gzrewind(file) == -1)           /* rewind, then skip to pos */
             return -1;
     }
+    offset = pos - state->x.pos;
 
     /* if reading, skip what's in output buffer (one less gzgetc() check) */
     if (state->mode == GZ_READ) {
@@ -455,7 +459,7 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
 
     /* request skip (if not zero) */
     state->skip = offset;
-    return state->x.pos + offset;
+    return pos;
 }
 
 /* -- see zlib.h -- */
@@ -584,10 +588,6 @@ void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) {
         state->msg = NULL;
     }
 
-    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
-    if (err != Z_OK && err != Z_BUF_ERROR && !state->again)
-        state->x.have = 0;
-
     /* set error code, and if no message, then done */
     state->err = err;
     if (msg == NULL)
diff --git a/src/java.base/share/native/libzip/zlib/gzread.c b/src/java.base/share/native/libzip/zlib/gzread.c
index 89144d2e56fe..ce7da3d0c999 100644
--- a/src/java.base/share/native/libzip/zlib/gzread.c
+++ b/src/java.base/share/native/libzip/zlib/gzread.c
@@ -57,7 +57,7 @@ local int gz_load(gz_statep state, unsigned char *buf, unsigned len,
         *have += (unsigned)ret;
     } while (*have < len);
     if (ret < 0) {
-        if (errno == EAGAIN || errno == EWOULDBLOCK) {
+        if (BLOCKED(errno)) {
             state->again = 1;
             if (*have != 0)
                 return 0;
@@ -149,6 +149,13 @@ local int gz_look(gz_statep state) {
        if we're looking for a gzip member after the first one, which is not at
        the start, then proceed directly to look for a gzip member next */
     if (state->direct == -1 || state->junk == 0) {
+        /* wait for input before committing to another gzip member */
+        if (state->junk == 0 && strm->avail_in == 0) {
+            if (gz_avail(state) == -1)
+                return -1;
+            if (strm->avail_in == 0)
+                return 0;
+        }
         inflateReset(strm);
         state->how = GZIP;
         state->junk = state->junk != -1;
@@ -177,7 +184,7 @@ local int gz_look(gz_statep state) {
             strm->next_in[2] == 8 && strm->next_in[3] < 32) {
         inflateReset(strm);
         state->how = GZIP;
-        state->junk = 1;
+        state->junk = 0;
         state->direct = 0;
         return 0;
     }
@@ -272,6 +279,11 @@ local int gz_decomp(gz_statep state) {
 local int gz_fetch(gz_statep state) {
     z_streamp strm = &(state->strm);
 
+    /* after a serious error, only what is already in the output buffer is
+       delivered -- don't try to decompress any more */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return -1;
+
     do {
         switch(state->how) {
         case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
@@ -300,32 +312,46 @@ local int gz_fetch(gz_statep state) {
     return 0;
 }
 
+/* Apply as much of a pending skip request as the output already available in
+   state->x allows. */
+local void gz_skip_have(gz_statep state) {
+    unsigned n;
+
+    n = GT_OFF(state->x.have) ||
+        (z_off64_t)state->x.have > state->skip ?
+        (unsigned)state->skip : state->x.have;
+    state->x.have -= n;
+    state->x.next += n;
+    state->x.pos += n;
+    state->skip -= n;
+}
+
 /* Skip state->skip (> 0) uncompressed bytes of output.  Return -1 on error, 0
    on success. */
 local int gz_skip(gz_statep state) {
-    unsigned n;
-
     /* skip over len bytes or reach end-of-file, whichever comes first */
     do {
         /* skip over whatever is in output buffer */
-        if (state->x.have) {
-            n = GT_OFF(state->x.have) ||
-                (z_off64_t)state->x.have > state->skip ?
-                (unsigned)state->skip : state->x.have;
-            state->x.have -= n;
-            state->x.next += n;
-            state->x.pos += n;
-            state->skip -= n;
-        }
+        if (state->x.have)
+            gz_skip_have(state);
 
         /* output buffer empty -- return if we're at the end of the input */
-        else if (state->eof && state->strm.avail_in == 0)
+        else if (state->eof && state->strm.avail_in == 0) {
+            if (state->how == GZIP && state->err == Z_OK)
+                gz_error(state, Z_BUF_ERROR, "unexpected end of file");
+            state->skip = 0;
+            state->past = 1;
             break;
+        }
 
         /* need more data to skip -- load up output buffer */
         else {
-            /* get more output, looking for header if required */
-            if (gz_fetch(state) == -1)
+            /* get more output, looking for header if required. If the fetch
+               stalled but provided some output, consume it before returning
+               so that x.have > 0 always implies the data is at the current
+               logical position (x.pos), as assumed by the gzgetc() fast path
+               in zlib.h and gzread.c */
+            if (gz_fetch(state) == -1 && state->x.have == 0)
                 return -1;
         }
     } while (state->skip);
@@ -373,8 +399,11 @@ local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
         }
 
         /* output buffer empty -- return if we're at the end of the input */
-        else if (state->eof && state->strm.avail_in == 0)
+        else if (state->eof && state->strm.avail_in == 0) {
+            if (state->how == GZIP && state->err == Z_OK)
+                gz_error(state, Z_BUF_ERROR, "unexpected end of file");
             break;
+        }
 
         /* need output data -- for small len or new stream load up our output
            buffer, so that gzgetc() can be fast */
@@ -427,15 +456,21 @@ int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) {
     if (state->mode != GZ_READ)
         return -1;
 
-    /* check that there was no (serious) error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+    /* check that there was no (serious) error -- if there was, deliver any
+       data read before the error until it is exhausted, and only then return
+       the error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again &&
+            state->x.have == 0)
         return -1;
-    gz_error(state, Z_OK, NULL);
+    if (state->again)
+        gz_error(state, Z_OK, NULL);
 
     /* since an int is returned, make sure len fits in one, otherwise return
-       with an error (this avoids a flaw in the interface) */
+       with an error (this avoids a flaw in the interface) -- keep a pending
+       serious error, which is the one the caller needs to see */
     if ((int)len < 0) {
-        gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");
+        if (state->err == Z_OK || state->err == Z_BUF_ERROR)
+            gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");
         return -1;
     }
 
@@ -472,15 +507,22 @@ z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
     if (state->mode != GZ_READ)
         return 0;
 
-    /* check that there was no (serious) error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+    /* check that there was no (serious) error -- if there was, deliver any
+       data read before the error until it is exhausted, and only then return
+       the error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again &&
+            state->x.have == 0)
         return 0;
-    gz_error(state, Z_OK, NULL);
+    if (state->again)
+        gz_error(state, Z_OK, NULL);
 
-    /* compute bytes to read -- error on overflow */
+    /* compute bytes to read -- error on overflow, keeping a pending serious
+       error, which is the one the caller needs to see */
     len = nitems * size;
     if (size && len / size != nitems) {
-        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
+        if (state->err == Z_OK || state->err == Z_BUF_ERROR)
+            gz_error(state, Z_STREAM_ERROR,
+                     "request does not fit in a size_t");
         return 0;
     }
 
@@ -505,10 +547,14 @@ int ZEXPORT gzgetc(gzFile file) {
     if (state->mode != GZ_READ)
         return -1;
 
-    /* check that there was no (serious) error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+    /* check that there was no (serious) error -- if there was, deliver any
+       data read before the error until it is exhausted, and only then return
+       the error, as the gzgetc() macro does */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again &&
+            state->x.have == 0)
         return -1;
-    gz_error(state, Z_OK, NULL);
+    if (state->again)
+        gz_error(state, Z_OK, NULL);
 
     /* try output buffer (no need to check for skip request) */
     if (state->x.have) {
@@ -540,10 +586,15 @@ int ZEXPORT gzungetc(int c, gzFile file) {
     if (state->how == LOOK && state->x.have == 0)
         (void)gz_look(state);
 
-    /* check that there was no (serious) error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+    /* check that there was no (serious) error -- a character can still be
+       pushed back after one, since it is data that was read before the
+       error, and it will be returned before the error is signaled -- but only
+       if there is an output buffer to put it in */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again &&
+            state->size == 0)
         return -1;
-    gz_error(state, Z_OK, NULL);
+    if (state->again)
+        gz_error(state, Z_OK, NULL);
 
     /* process a skip request */
     if (state->skip && gz_skip(state) == -1)
@@ -565,7 +616,8 @@ int ZEXPORT gzungetc(int c, gzFile file) {
 
     /* if no room, give up (must have already done a gzungetc()) */
     if (state->x.have == (state->size << 1)) {
-        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
+        if (state->err == Z_OK || state->err == Z_BUF_ERROR)
+            gz_error(state, Z_DATA_ERROR, "out of room to push characters");
         return -1;
     }
 
@@ -601,10 +653,14 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
     if (state->mode != GZ_READ)
         return NULL;
 
-    /* check that there was no (serious) error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+    /* check that there was no (serious) error -- if there was, deliver any
+       data read before the error until it is exhausted, and only then return
+       the error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again &&
+            state->x.have == 0)
         return NULL;
-    gz_error(state, Z_OK, NULL);
+    if (state->again)
+        gz_error(state, Z_OK, NULL);
 
     /* process a skip request */
     if (state->skip && gz_skip(state) == -1)
@@ -616,8 +672,9 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
     left = (unsigned)len - 1;
     if (left) do {
         /* assure that something is in the output buffer */
-        if (state->x.have == 0 && gz_fetch(state) == -1)
-            break;                      /* error */
+        if (state->x.have == 0 && gz_fetch(state) == -1 &&
+                state->x.have == 0)
+            break;                      /* error, and nothing left to return */
         if (state->x.have == 0) {       /* end of file */
             state->past = 1;            /* read past end */
             break;                      /* return what we have */
@@ -641,7 +698,7 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
     /* append a terminating zero to the string (we don't check for a zero in
        the contents, let the user worry about that) -- return the terminated
        string, or if nothing was read, NULL */
-    if (buf == str)
+    if (buf == str && len > 1)
         return NULL;
     buf[0] = 0;
     return str;
@@ -658,8 +715,10 @@ int ZEXPORT gzdirect(gzFile file) {
 
     /* if the state is not known, but we can find out, then do so (this is
        mainly for right after a gzopen() or gzdopen()) */
-    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
+    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) {
         (void)gz_look(state);
+        gz_skip_have(state);        /* apply skip to current buffer */
+    }
 
     /* return 1 if transparent, 0 if processing a gzip stream */
     return state->direct == 1;
diff --git a/src/java.base/share/native/libzip/zlib/gzwrite.c b/src/java.base/share/native/libzip/zlib/gzwrite.c
index 5719bbffe00a..cf933bef87b8 100644
--- a/src/java.base/share/native/libzip/zlib/gzwrite.c
+++ b/src/java.base/share/native/libzip/zlib/gzwrite.c
@@ -65,8 +65,8 @@ local int gz_init(gz_statep state) {
             gz_error(state, Z_MEM_ERROR, "out of memory");
             return -1;
         }
-        strm->next_in = NULL;
     }
+    strm->next_in = NULL;
 
     /* mark state as initialized */
     state->size = state->want;
@@ -103,7 +103,7 @@ local int gz_comp(gz_statep state, int flush) {
             put = strm->avail_in > max ? max : strm->avail_in;
             writ = (int)write(state->fd, strm->next_in, put);
             if (writ < 0) {
-                if (errno == EAGAIN || errno == EWOULDBLOCK)
+                if (BLOCKED(errno))
                     state->again = 1;
                 gz_error(state, Z_ERRNO, zstrerror());
                 return -1;
@@ -138,7 +138,7 @@ local int gz_comp(gz_statep state, int flush) {
                       (unsigned)(strm->next_out - state->x.next);
                 writ = (int)write(state->fd, state->x.next, put);
                 if (writ < 0) {
-                    if (errno == EAGAIN || errno == EWOULDBLOCK)
+                    if (BLOCKED(errno))
                         state->again = 1;
                     gz_error(state, Z_ERRNO, zstrerror());
                     return -1;
@@ -180,6 +180,11 @@ local int gz_zero(gz_statep state) {
     unsigned n;
     z_streamp strm = &(state->strm);
 
+    /* allocate memory if this is the first time through -- the input buffer
+       must exist before it is zeroed below */
+    if (state->size == 0 && gz_init(state) == -1)
+        return -1;
+
     /* consume whatever's left in the input buffer */
     if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
         return -1;
@@ -199,8 +204,14 @@ local int gz_zero(gz_statep state) {
         n -= strm->avail_in;
         state->x.pos += n;
         state->skip -= n;
-        if (ret == -1)
+        if (ret == -1) {
+            /* discard any unconsumed zero fill -- it was not yet accounted
+               for in state->skip, so it will be generated again when the
+               operation is retried */
+            strm->avail_in = 0;
+            strm->next_in = state->in;
             return -1;
+        }
     } while (state->skip);
     return 0;
 }
@@ -272,6 +283,7 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
                 return state->again ? put - len : 0;
             }
         } while (len);
+        state->strm.next_in = state->in;
     }
 
     /* input was all buffered or compressed */
@@ -398,9 +410,10 @@ int ZEXPORT gzputs(gzFile file, const char *s) {
     return len && put == 0 ? -1 : (int)put;
 }
 
-#if (((!defined(STDC) && !defined(Z_HAVE_STDARG_H)) || !defined(NO_vsnprintf)) && \
-     (defined(STDC) || defined(Z_HAVE_STDARG_H) || !defined(NO_snprintf))) || \
-    defined(ZLIB_INSECURE)
+#if (((!defined(STDC) && !defined(Z_HAVE_STDARG_H)) || \
+      !defined(NO_vsnprintf)) && \
+     (defined(STDC) || defined(Z_HAVE_STDARG_H) || \
+     !defined(NO_snprintf))) || defined(ZLIB_INSECURE)
 /* If the second half of the input buffer is occupied, write out the contents.
    If there is any input remaining due to a non-blocking stall on write, move
    it to the start of the buffer. Return true if this did not open up the
@@ -507,6 +520,14 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) {
 
     /* write out buffer if more than half is occupied */
     ret = gz_vacate(state);
+    if (ret) {
+        /* discard unwritten formatted output */
+        strm->avail_in -= (unsigned)len;
+        state->x.pos -= len;
+        if (state->again)
+            gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf");
+        return state->err;
+    }
     if (state->err && !state->again)
         return state->err;
     return len;
@@ -580,6 +601,7 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
                a Z_BUF_ERROR to let the application know that this gzprintf()
                needs to be retried. */
             gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf");
+            return state->err;
         }
         if (!state->again)
             return state->err;
@@ -620,6 +642,14 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
 
     /* write out buffer if more than half is occupied */
     ret = gz_vacate(state);
+    if (ret) {
+        /* discard unwritten formatted output */
+        strm->avail_in -= (unsigned)len;
+        state->x.pos -= len;
+        if (state->again)
+            gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf");
+        return state->err;
+    }
     if (state->err && !state->again)
         return state->err;
     return (int)len;
diff --git a/src/java.base/share/native/libzip/zlib/infback.c b/src/java.base/share/native/libzip/zlib/infback.c
index 0becbb9eb4f6..c2286bd20699 100644
--- a/src/java.base/share/native/libzip/zlib/infback.c
+++ b/src/java.base/share/native/libzip/zlib/infback.c
@@ -447,8 +447,6 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             /* use inflate_fast() if we have enough input and output */
             if (have >= 6 && left >= 258) {
                 RESTORE();
-                if (state->whave < state->wsize)
-                    state->whave = state->wsize - left;
                 inflate_fast(strm, state->wsize);
                 LOAD();
                 break;
diff --git a/src/java.base/share/native/libzip/zlib/inflate.c b/src/java.base/share/native/libzip/zlib/inflate.c
index c548f98f6de3..16bc832948e3 100644
--- a/src/java.base/share/native/libzip/zlib/inflate.c
+++ b/src/java.base/share/native/libzip/zlib/inflate.c
@@ -151,6 +151,14 @@ int ZEXPORT inflateReset(z_streamp strm) {
 
     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
     state = (struct inflate_state FAR *)strm->state;
+    if (state->wbits != state->reqbits) {
+        if (state->window != Z_NULL) {
+            ZFREE(strm, state->window);
+            state->window = Z_NULL;
+        }
+        state->wbits = state->reqbits;
+    }
+    state->wrap = state->reqwrap;
     state->wsize = 0;
     state->whave = 0;
     state->wnext = 0;
@@ -189,8 +197,8 @@ int ZEXPORT inflateReset2(z_streamp strm, int windowBits) {
     }
 
     /* update state and reset the rest of it */
-    state->wrap = wrap;
-    state->wbits = (unsigned)windowBits;
+    state->reqwrap = state->wrap = wrap;
+    state->reqbits = state->wbits = (unsigned)windowBits;
     return inflateReset(strm);
 }
 
@@ -561,13 +569,13 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             }
             DROPBITS(4);
             len = BITS(4) + 8;
-            if (state->wbits == 0)
-                state->wbits = len;
-            if (len > 15 || len > state->wbits) {
+            if (len > 15 || (state->wbits != 0 && len > state->wbits)) {
                 strm->msg = (z_const char *)"invalid window size";
                 state->mode = BAD;
                 break;
             }
+            if (state->wbits == 0)
+                state->wbits = len;
             state->dmax = 1U << len;
             state->flags = 0;               /* indicate zlib header */
             Tracev((stderr, "inflate:   zlib header ok\n"));
@@ -724,6 +732,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
         case DICT:
             if (state->havedict == 0) {
                 RESTORE();
+                strm->total_in += in - strm->avail_in;
                 return Z_NEED_DICT;
             }
             strm->adler = state->check = adler32(0L, Z_NULL, 0);
@@ -936,7 +945,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             state->mode = LEN;
                 /* fallthrough */
         case LEN:
-            if (have >= 6 && left >= 258) {
+            if (have >= 6 && left >= 258 && bits < 8) {
                 RESTORE();
                 inflate_fast(strm, out);
                 LOAD();
@@ -1215,7 +1224,8 @@ int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary,
     int ret;
 
     /* check state */
-    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    if (inflateStateCheck(strm) || dictionary == Z_NULL)
+        return Z_STREAM_ERROR;
     state = (struct inflate_state FAR *)strm->state;
     if (state->wrap != 0 && state->mode != DICT)
         return Z_STREAM_ERROR;
@@ -1320,15 +1330,23 @@ int ZEXPORT inflateSync(z_streamp strm) {
 
     /* return no joy or set up to restart inflate() on a new block */
     if (state->have != 4) return Z_DATA_ERROR;
-    if (state->flags == -1)
-        state->wrap = 0;    /* if no header yet, treat as raw */
-    else
-        state->wrap &= ~4;  /* no point in computing a check value now */
     flags = state->flags;
     in = strm->total_in;  out = strm->total_out;
     inflateReset(strm);
     strm->total_in = in;  strm->total_out = out;
     state->flags = flags;
+    if (flags == -1)
+        state->wrap = 0;    /* if no header yet, treat as raw */
+    else
+        state->wrap &= ~4;  /* no point in computing a check value now */
+    if (state->wbits == 0) {
+        /* we never got to see a header for the window size -- set to max */
+        if (state->window != Z_NULL) {
+            ZFREE(strm, state->window);
+            state->window = Z_NULL;
+        }
+        state->wbits = 15;
+    }
     state->mode = TYPE;
     return Z_OK;
 }
@@ -1355,14 +1373,21 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
     unsigned char FAR *window;
 
     /* check input */
-    if (inflateStateCheck(source) || dest == Z_NULL)
+    if (dest == Z_NULL)
         return Z_STREAM_ERROR;
+    if (inflateStateCheck(source)) {
+        dest->state = Z_NULL;
+        return Z_STREAM_ERROR;
+    }
     state = (struct inflate_state FAR *)source->state;
 
     /* allocate space */
     copy = (struct inflate_state FAR *)
            ZALLOC(source, 1, sizeof(struct inflate_state));
-    if (copy == Z_NULL) return Z_MEM_ERROR;
+    if (copy == Z_NULL) {
+        dest->state = Z_NULL;
+        return Z_MEM_ERROR;
+    }
     zmemzero(copy, sizeof(struct inflate_state));
     window = Z_NULL;
     if (state->window != Z_NULL) {
@@ -1370,6 +1395,7 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
                  ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
         if (window == Z_NULL) {
             ZFREE(source, copy);
+            dest->state = Z_NULL;
             return Z_MEM_ERROR;
         }
     }
@@ -1415,6 +1441,10 @@ int ZEXPORT inflateValidate(z_streamp strm, int check) {
         state->wrap |= 4;
     else
         state->wrap &= ~4;
+    if (check && state->reqwrap)
+        state->reqwrap |= 4;
+    else
+        state->reqwrap &= ~4;
     return Z_OK;
 }
 
diff --git a/src/java.base/share/native/libzip/zlib/inflate.h b/src/java.base/share/native/libzip/zlib/inflate.h
index 7828fb5db38e..1f2783e58cf8 100644
--- a/src/java.base/share/native/libzip/zlib/inflate.h
+++ b/src/java.base/share/native/libzip/zlib/inflate.h
@@ -109,6 +109,7 @@ struct inflate_state {
     int last;                   /* true if processing last block */
     int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip,
                                    bit 2 true to validate check value */
+    int reqwrap;                /* requested wrap */
     int havedict;               /* true if dictionary provided */
     int flags;                  /* gzip header method and flags, 0 if zlib, or
                                    -1 if raw or no header yet */
@@ -117,7 +118,8 @@ struct inflate_state {
     unsigned long total;        /* protected copy of output count */
     gz_headerp head;            /* where to save gzip header information */
         /* sliding window */
-    unsigned wbits;             /* log base 2 of requested window size */
+    unsigned reqbits;           /* requested log base 2 of window size */
+    unsigned wbits;             /* current log base 2 of window size */
     unsigned wsize;             /* window size or zero if not using window */
     unsigned whave;             /* valid bytes in the window */
     unsigned wnext;             /* window write index */
diff --git a/src/java.base/share/native/libzip/zlib/inftrees.c b/src/java.base/share/native/libzip/zlib/inftrees.c
index 5f5d6b4baef2..7486efef8ee9 100644
--- a/src/java.base/share/native/libzip/zlib/inftrees.c
+++ b/src/java.base/share/native/libzip/zlib/inftrees.c
@@ -47,7 +47,7 @@
 #define MAXBITS 15
 
 const char inflate_copyright[] =
-   " inflate 1.3.2 Copyright 1995-2026 Mark Adler ";
+   " inflate 1.4 Copyright 1995-2026 Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -95,7 +95,7 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
     static const unsigned short lext[31] = { /* Length codes 257..285 extra */
         16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
-        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 75};
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 71, 77};
     static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
diff --git a/src/java.base/share/native/libzip/zlib/inftrees.h b/src/java.base/share/native/libzip/zlib/inftrees.h
index b9b4fc2fb2bc..51f67b68c65b 100644
--- a/src/java.base/share/native/libzip/zlib/inftrees.h
+++ b/src/java.base/share/native/libzip/zlib/inftrees.h
@@ -70,8 +70,14 @@ typedef struct {
    inflate_table() calls in inflate.c and infback.c.  If the root table size is
    changed, then these maximum sizes would be need to be recalculated and
    updated. */
-#define ENOUGH_LENS 852
-#define ENOUGH_DISTS 592
+#ifndef PKZIP_BUG_WORKAROUND
+#  define ENOUGH_LENS 852
+#  define ENOUGH_DISTS 592
+#else
+/* That workaround permits 288 literal/length codes and 32 distance codes. */
+#  define ENOUGH_LENS 854
+#  define ENOUGH_DISTS 594
+#endif
 #define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
 
 /* Type of code to build for inflate_table() */
diff --git a/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java b/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
index dfde58f0122d..46affe2cd5e2 100644
--- a/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
+++ b/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
@@ -1,6 +1,6 @@
-Changes in JDK's in-tree zlib compared to upstream zlib 1.3.2
+Changes in JDK's in-tree zlib compared to upstream zlib 1.4
 
-(1) renamed adler32.c -> zadler32.c, crc32c -> zcrc32.c
+(1) renamed adler32.c -> zadler32.c, crc32.c -> zcrc32.c
 
 
   
diff --git a/src/java.base/share/native/libzip/zlib/trees.c b/src/java.base/share/native/libzip/zlib/trees.c
index cc7b136bcf68..bf5c1b24149e 100644
--- a/src/java.base/share/native/libzip/zlib/trees.c
+++ b/src/java.base/share/native/libzip/zlib/trees.c
@@ -251,7 +251,7 @@ local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
 
         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
-            n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
+            n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
     }
 }
 
diff --git a/src/java.base/share/native/libzip/zlib/uncompr.c b/src/java.base/share/native/libzip/zlib/uncompr.c
index 25da59461c37..d55a4f2d66ca 100644
--- a/src/java.base/share/native/libzip/zlib/uncompr.c
+++ b/src/java.base/share/native/libzip/zlib/uncompr.c
@@ -57,8 +57,8 @@ int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
     const uInt max = (uInt)-1;
     z_size_t len, left;
 
-    if (sourceLen == NULL || (*sourceLen > 0 && source == NULL) ||
-        destLen == NULL || (*destLen > 0 && dest == NULL))
+    if (sourceLen == Z_NULL || (*sourceLen > 0 && source == Z_NULL) ||
+        destLen == Z_NULL || (*destLen > 0 && dest == Z_NULL))
         return Z_STREAM_ERROR;
 
     len = *sourceLen;
diff --git a/src/java.base/share/native/libzip/zlib/zconf.h b/src/java.base/share/native/libzip/zlib/zconf.h
index d4589739a0ae..542e462ac177 100644
--- a/src/java.base/share/native/libzip/zlib/zconf.h
+++ b/src/java.base/share/native/libzip/zlib/zconf.h
@@ -523,6 +523,10 @@ typedef uLong FAR uLongf;
 
 #if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
 #  define Z_LFS64
+#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \
+      !defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__))
+#  define Z_LFS64       /* native Windows has 64-bit file offsets */
+#  define Z_WINLFS
 #endif
 
 #if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
@@ -540,7 +544,7 @@ typedef uLong FAR uLongf;
 #endif
 
 #ifndef z_off_t
-#  define z_off_t long long
+#  define z_off_t long
 #endif
 
 #if !defined(_WIN32) && defined(Z_LARGE64)
@@ -555,6 +559,11 @@ typedef uLong FAR uLongf;
 #  define z_off64_t z_off_t
 #endif
 
+#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO)
+#  undef z_off_t
+#  define z_off_t z_off64_t
+#endif
+
 /* MVS linker does not support external names larger than 8 bytes */
 #if defined(__MVS__)
   #pragma map(deflateInit_,"DEIN")
diff --git a/src/java.base/share/native/libzip/zlib/zcrc32.c b/src/java.base/share/native/libzip/zlib/zcrc32.c
index 133cbe158aa4..0161f1ee20e8 100644
--- a/src/java.base/share/native/libzip/zlib/zcrc32.c
+++ b/src/java.base/share/native/libzip/zlib/zcrc32.c
@@ -710,7 +710,7 @@ uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) {
 #endif
 
             /* Initialize the CRC for each braid. */
-            crc0 = crc;
+            crc0 = (z_crc_t)crc;
 #if N > 1
             crc1 = 0;
 #if N > 2
diff --git a/src/java.base/share/native/libzip/zlib/zlib.h b/src/java.base/share/native/libzip/zlib/zlib.h
index 90230f4f23fb..15b6b927a10c 100644
--- a/src/java.base/share/native/libzip/zlib/zlib.h
+++ b/src/java.base/share/native/libzip/zlib/zlib.h
@@ -23,7 +23,7 @@
  */
 
 /* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.3.2, February 17th, 2026
+  version 1.4, November 4th, 2026
 
   Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
 
@@ -65,11 +65,11 @@
 extern "C" {
 #endif
 
-#define ZLIB_VERSION "1.3.2"
-#define ZLIB_VERNUM 0x1320
+#define ZLIB_VERSION "1.4"
+#define ZLIB_VERNUM 0x1400
 #define ZLIB_VER_MAJOR 1
-#define ZLIB_VER_MINOR 3
-#define ZLIB_VER_REVISION 2
+#define ZLIB_VER_MINOR 4
+#define ZLIB_VER_REVISION 0
 #define ZLIB_VER_SUBREVISION 0
 
 /*
@@ -720,7 +720,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
    (such as zalloc being Z_NULL).  msg is left unchanged in both source and
-   destination.
+   destination.  If deflateCopy fails and dest is not Z_NULL, then dest->state
+   is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can
+   be called safely, though dest is not a usable stream.
 */
 
 ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
@@ -793,17 +795,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen);
 ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
 /*
      deflateBound() returns an upper bound on the compressed size after
-   deflation of sourceLen bytes.  It must be called after deflateInit() or
-   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
-   to allocate an output buffer for deflation in a single pass, and so would be
-   called before deflate().  If that first deflate() call is provided the
-   sourceLen input bytes, an output buffer allocated to the size returned by
-   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
-   to return Z_STREAM_END.  Note that it is possible for the compressed size to
-   be larger than the value returned by deflateBound() if flush options other
-   than Z_FINISH or Z_NO_FLUSH are used.
-
-     delfateBound_z() is the same, but takes and returns a size_t length.  Note
+  deflation of sourceLen bytes.  It must be called after deflateInit() or
+  deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if
+  used.  This would be used to allocate an output buffer for deflation in a
+  single pass, and so would be called before deflate().  If that first
+  deflate() call is provided the sourceLen input bytes, an output buffer
+  allocated to the size returned by deflateBound(), and the flush value
+  Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END.  Note that it
+  is possible for the compressed size to be larger than the value returned by
+  deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
+
+     deflateBound_z() is the same, but takes and returns a size_t length.  Note
    that a long is 32 bits on Windows.
 */
 
@@ -813,7 +815,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
 /*
      deflatePending() returns the number of bytes and bits of output that have
    been generated, but not yet provided in the available output.  The bytes not
-   provided would be due to the available output space having being consumed.
+   provided would be due to the available output space having been consumed.
    The number of bits of output not provided are between 0 and 7, where they
    await more bits to join them in order to fill out a full byte.  If pending
    or bits are Z_NULL, then those values are not set.
@@ -893,8 +895,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
    instead.  windowBits must be greater than or equal to the windowBits value
    provided to deflateInit2() while compressing, or it must be equal to 15 if
    deflateInit2() was not used.  If a compressed stream with a larger window
-   size is given as input, inflate() will return with the error code
-   Z_DATA_ERROR instead of trying to allocate a larger window.
+   size is given as input, inflate() may return with a Z_DATA_ERROR.
 
      windowBits can also be zero to request that inflate use the window size in
    the zlib header of the compressed stream.
@@ -1004,7 +1005,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
      inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
    (such as zalloc being Z_NULL).  msg is left unchanged in both source and
-   destination.
+   destination.  If inflateCopy fails and dest is not Z_NULL, then dest->state
+   is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can
+   be called safely, though dest is not a usable stream.
 */
 
 ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
@@ -1119,9 +1122,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
    a terminating zero.  If any of extra, name, or comment are not present in
    the header, then that field's pointer is set to Z_NULL.  This allows the use
    of deflateSetHeader() with the returned structure to duplicate the header.
-   Note that if those fields initially pointed to allocated memory, then the
-   application will need to save them elsewhere so that they can be eventually
-   freed.
+   Though take care that none of the fields were truncated before so using it,
+   lest havoc ensue.  Note that if those fields initially pointed to allocated
+   memory, then the application will need to save them elsewhere so that they
+   can be eventually freed.
 
      If inflateGetHeader is not used, then the header information is simply
    discarded.  The header is always checked for validity, including the header
@@ -1418,8 +1422,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
    errno can be checked to determine if the reason gzopen failed was that the
    file could not be opened. Note that if 'N' is in mode for non-blocking, the
    open() itself can fail in order to not block. In that case gzopen() will
-   return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can
-   then be re-tried. If the application would like to block on opening the
+   return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen()
+   can then be re-tried. If the application would like to block on opening the
    file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
    resulting file descriptor and 'N' in the mode, which will set it to non-
    blocking.
@@ -1525,9 +1529,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
      gzfread() returns the number of full items read of size size, or zero if
    the end of the file was reached and a full item could not be read, or if
    there was an error.  gzerror() must be consulted if zero is returned in
-   order to determine if there was an error.  If the multiplication of size and
-   nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
-   is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
+   order to determine if there was an error.  If some data was read before an
+   error, then that data is returned until exhausted, after which the next call
+   will return zero and gzerror() will report the error.  If the multiplication
+   of size and nitems overflows, i.e. the product does not fit in a z_size_t,
+   then nothing is read, zero is returned, and the error state is set to
+   Z_STREAM_ERROR.
 
      In the event that the end of file is reached and only a partial item is
    available at the end, i.e. the remaining uncompressed data length is not a
@@ -1593,7 +1600,7 @@ ZEXTERN int ZEXPORTVA gzprintf();
    these possibilities can be determined using zlibCompileFlags().
 
      If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
-   the non-blocking write destination.
+   the non-blocking write destination. The operation can be retried.
 */
 
 ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
@@ -1701,7 +1708,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
      gzseek returns the resulting offset location as measured in bytes from
    the beginning of the uncompressed stream, or -1 in case of error, in
    particular if the file is opened for writing and the new starting position
-   would be before the current position.
+   would be before the current position, or if the resulting position would
+   not be representable in the offset type. If gzseek returns -1, the stream
+   position is unchanged.
 */
 
 ZEXTERN int ZEXPORT gzrewind(gzFile file);
@@ -1802,7 +1811,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
    If errnum is not NULL, *errnum is set to zlib error number.  If an error
    occurred in the file system and not in the compression library, *errnum is
    set to Z_ERRNO and the application may consult errno to get the exact error
-   code.
+   code.  The error is reported by gzerror() as soon as it is detected, which
+   may be before all of the data read prior to the error has been returned.
 
      The application must not modify the returned string.  Future calls to
    this function may invalidate the previously returned string.  If file is
@@ -1996,7 +2006,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file);       /* backward compatibility */
  * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
  * both are true, the application gets the *64 functions, and the regular
  * functions are changed to 64 bits) -- in case these are set on systems
- * without large file support, _LFS64_LARGEFILE must also be true
+ * without large file support, _LFS64_LARGEFILE must also be true, except on
+ * native Windows, where 64-bit offsets are always available
  */
 #ifdef Z_LARGE64
    ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
@@ -2053,7 +2064,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file);       /* backward compatibility */
 
 #endif /* !Z_SOLO */
 
-/* undocumented functions */
+/* undocumented functions (not part of the zlib API) */
 ZEXTERN const char   * ZEXPORT zError(int);
 ZEXTERN int            ZEXPORT inflateSyncPoint(z_streamp);
 ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
diff --git a/src/java.base/share/native/libzip/zlib/zutil.c b/src/java.base/share/native/libzip/zlib/zutil.c
index c57c162ffde8..ae5e85102786 100644
--- a/src/java.base/share/native/libzip/zlib/zutil.c
+++ b/src/java.base/share/native/libzip/zlib/zutil.c
@@ -195,7 +195,6 @@ int ZLIB_INTERNAL zmemcmp(const void FAR *s1, const void FAR *s2, z_size_t n) {
 
 void ZLIB_INTERNAL zmemzero(void FAR *b, z_size_t len) {
     uchf *p = b;
-    if (len == 0) return;
     while (len) {
         *p++ = 0;
         len--;
@@ -252,7 +251,11 @@ voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) {
     } else {
         buf = farmalloc(bsize + 16L);
     }
-    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
+    if (buf == NULL) return NULL;
+    if (next_ptr >= MAX_PTR) {
+        farfree(buf);
+        return NULL;
+    }
     table[next_ptr].org_ptr = buf;
 
     /* Normalize the pointer to seg:0 */
diff --git a/src/java.base/unix/native/libnio/ch/UnixFileDispatcherImpl.c b/src/java.base/unix/native/libnio/ch/UnixFileDispatcherImpl.c
index d0703da4e497..d538f3cbe9f7 100644
--- a/src/java.base/unix/native/libnio/ch/UnixFileDispatcherImpl.c
+++ b/src/java.base/unix/native/libnio/ch/UnixFileDispatcherImpl.c
@@ -342,29 +342,27 @@ Java_sun_nio_ch_UnixFileDispatcherImpl_map0(JNIEnv *env, jclass klass, jobject f
         flags = MAP_PRIVATE;
     }
 
-    // if MAP_SYNC and MAP_SHARED_VALIDATE are not defined then it is
-    // best to define them here. This ensures the code compiles on old
-    // OS releases which do not provide the relevant headers. If run
-    // on the same machine then it will work if the kernel contains
-    // the necessary support otherwise mmap should fail with an
-    // invalid argument error
-
-#ifndef MAP_SYNC
-#define MAP_SYNC 0x80000
-#endif
-#ifndef MAP_SHARED_VALIDATE
-#define MAP_SHARED_VALIDATE 0x03
-#endif
-
     if (map_sync) {
         // ensure
         //  1) this is Linux on AArch64, x86_64, or PPC64 LE
         //  2) the mmap APIs are available at compile time
 #if !defined(LINUX) || ! (defined(aarch64) || (defined(amd64) && defined(_LP64)) || defined(ppc64le))
-        // TODO - implement for solaris/AIX/BSD/WINDOWS and for 32 bit
+        // TODO - implement for AIX/BSD/WINDOWS and for 32 bit
         JNU_ThrowInternalError(env, "should never call map on platform where MAP_SYNC is unimplemented");
         return IOS_THROWN;
 #else
+        // if MAP_SYNC and MAP_SHARED_VALIDATE are not defined then it is
+        // best to define them here. This ensures the code compiles on old
+        // OS releases which do not provide the relevant headers. If run
+        // on the same machine then it will work if the kernel contains
+        // the necessary support otherwise mmap should fail with an
+        // invalid argument error
+#ifndef MAP_SYNC
+#define MAP_SYNC 0x80000
+#endif
+#ifndef MAP_SHARED_VALIDATE
+#define MAP_SHARED_VALIDATE 0x03
+#endif
         flags |= MAP_SYNC | MAP_SHARED_VALIDATE;
 #endif
     }
diff --git a/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java b/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java
index f15f39f0d521..fce4cb177a3e 100644
--- a/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java
+++ b/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,7 +37,6 @@
 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.file.Files;
-import java.nio.file.Path;
 import java.nio.channels.spi.*;
 import java.security.SecureRandom;
 import java.util.Random;
@@ -97,7 +96,11 @@ public void interrupt() {}
         }
 
         private class LoopbackConnector implements Runnable {
-
+            /**
+             * Creates a connected "socket pair", verifying the accepted connection.
+             * Uses non-blocking I/O and Net.poll to avoid recursive initialization
+             * issues with the virtual threads poller I/O mechanism.
+             */
             @Override
             public void run() {
                 ServerSocketChannel ssc = null;
@@ -111,28 +114,47 @@ public void run() {
                     ByteBuffer secret = ByteBuffer.allocate(NUM_SECRET_BYTES);
                     ByteBuffer bb = ByteBuffer.allocate(NUM_SECRET_BYTES);
 
-                    for(;;) {
-                        // Bind ServerSocketChannel to a port on the loopback
-                        // address
+                    for (;;) {
+                        // Bind ServerSocketChannel to a port on the loopback address
                         if (ssc == null || !ssc.isOpen()) {
-                            ssc = createListener(preferUnixDomain);
+                            ssc = createListener(sp, preferUnixDomain);
+                            ssc.configureBlocking(false);
                             sa = ssc.getLocalAddress();
                         }
 
                         // Establish connection (assume connection is eagerly accepted)
-                        sc1 = SocketChannel.open(sa);
+                        sc1 = (sa instanceof UnixDomainSocketAddress)
+                                ? sp.openSocketChannel(UNIX)
+                                : sp.openSocketChannel();
+                        sc1.configureBlocking(false);
+                        if (!sc1.connect(sa)) {
+                            do {
+                                poll(sc1, Net.POLLOUT);
+                            } while (!sc1.finishConnect());
+                        }
                         RANDOM_NUMBER_GENERATOR.nextBytes(secret.array());
-                        do {
-                            sc1.write(secret);
-                        } while (secret.hasRemaining());
+                        sc1.write(secret);
+                        if (secret.hasRemaining()) {
+                            throw new IOException("Short write during handshake");
+                        }
                         secret.rewind();
+                        sc1.configureBlocking(true);
 
-                        // Get a connection and verify it is legitimate
-                        sc2 = ssc.accept();
+                        // Accept a connection and verify it is legitimate
+                        while ((sc2 = ssc.accept()) == null) {
+                            poll(ssc, Net.POLLIN);
+                        }
+                        sc2.configureBlocking(false);
                         do {
-                            sc2.read(bb);
+                            int n = sc2.read(bb);
+                            if (n < 0) {
+                                throw new IOException("EOF during handshake");
+                            } else if (n == 0) {
+                                poll(sc2, Net.POLLIN);
+                            }
                         } while (bb.hasRemaining());
                         bb.rewind();
+                        sc2.configureBlocking(true);
 
                         if (bb.equals(secret))
                             break;
@@ -162,6 +184,10 @@ public void run() {
                     } catch (IOException e2) {}
                 }
             }
+
+            private void poll(SelectableChannel channel, int event) throws IOException {
+                Net.poll(((SelChImpl) channel).getFD(), event, -1);
+            }
         }
     }
 
@@ -200,11 +226,12 @@ public SinkChannelImpl sink() {
         return sink;
     }
 
-    private static ServerSocketChannel createListener(boolean preferUnixDomain) throws IOException {
+    private static ServerSocketChannel createListener(SelectorProvider sp,
+                                                      boolean preferUnixDomain) throws IOException {
         ServerSocketChannel listener = null;
         if (preferUnixDomain && UnixDomainSockets.isSupported()) {
             try {
-                listener = ServerSocketChannel.open(UNIX);
+                listener = sp.openServerSocketChannel(UNIX);
                 listener.bind(null);
                 return listener;
             } catch (IOException | UnsupportedOperationException e) {
@@ -212,7 +239,7 @@ private static ServerSocketChannel createListener(boolean preferUnixDomain) thro
                     listener.close();
             }
         }
-        listener = ServerSocketChannel.open();
+        listener = sp.openServerSocketChannel();
         InetAddress lb = InetAddress.getLoopbackAddress();
         listener.bind(new InetSocketAddress(lb, 0));
         return listener;
diff --git a/src/java.base/windows/classes/sun/nio/ch/WEPollPoller.java b/src/java.base/windows/classes/sun/nio/ch/WEPollPoller.java
index 9f575072f224..9d27fd33dc1a 100644
--- a/src/java.base/windows/classes/sun/nio/ch/WEPollPoller.java
+++ b/src/java.base/windows/classes/sun/nio/ch/WEPollPoller.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,25 +37,49 @@ class WEPollPoller extends Poller {
     private final int event;
     private final long address;
 
+    // pipe used for wakeup during shutdown
+    private final PipeImpl pipe;
+    private final int fd0;
+    private final int fd1;
+
     WEPollPoller(boolean read) throws IOException {
         long handle =  WEPoll.create();
-        long address;
+        long address = 0L;
+        PipeImpl pipe = null;
         try {
             address = WEPoll.allocatePollArray(MAX_EVENTS_TO_POLL);
+
+            // register one end of the pipe with wepoll to allow for wakeup
+            pipe = new PipeImpl(DefaultSelectorProvider.get(), true, false);
+            pipe.sink().configureBlocking(false);
+            int err = WEPoll.ctl(handle, EPOLL_CTL_ADD, pipe.source().getFDVal(), EPOLLIN);
+            if (err != 0) {
+                throw new IOException("epoll_ctl failed: " + err);
+            }
         } catch (Throwable e) {
             WEPoll.close(handle);
+            if (address != 0L) WEPoll.freePollArray(address);
+            if (pipe != null) {
+                pipe.sink().close();
+                pipe.source().close();
+            }
             throw e;
         }
 
         this.event = (read) ? EPOLLIN : EPOLLOUT;
         this.handle = handle;
         this.address = address;
+        this.pipe = pipe;
+        this.fd0 = pipe.source().getFDVal();
+        this.fd1 = pipe.sink().getFDVal();
     }
 
     @Override
-    void close() {
+    void close() throws IOException {
         WEPoll.close(handle);
         WEPoll.freePollArray(address);
+        pipe.sink().close();
+        pipe.source().close();
     }
 
     @Override
@@ -70,17 +94,26 @@ void implStopPoll(int fdVal, boolean polled) {
         WEPoll.ctl(handle, EPOLL_CTL_DEL, fdVal, 0);
     }
 
+    @Override
+    void wakeupPoller() throws IOException {
+        IOUtil.write1(fd1, (byte) 0);
+    }
+
     @Override
     int poll(int timeout) throws IOException {
         int n = WEPoll.wait(handle, address, MAX_EVENTS_TO_POLL, timeout);
+        int polled = 0;
         int i = 0;
         while (i < n) {
             long event = WEPoll.getEvent(address, i);
             int fdVal = WEPoll.getDescriptor(event);
-            polled(fdVal);
+            if (fdVal != fd0) {
+                polled(fdVal);
+                polled++;
+            }
             i++;
         }
-        return n;
+        return polled;
     }
 }
 
diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m
index 8da421183b7c..36fb5dcb6663 100644
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m
@@ -42,9 +42,6 @@
 #define IS(BITS, KEY) \
     ((BITS & MASK(KEY)) != 0)
 
-#define SET(BITS, KEY, VALUE) \
-    BITS = VALUE ? BITS | MASK(KEY) : BITS & ~MASK(KEY)
-
 static jclass jc_CPlatformWindow = NULL;
 #define GET_CPLATFORM_WINDOW_CLASS() \
     GET_CLASS(jc_CPlatformWindow, "sun/lwawt/macosx/CPlatformWindow");
diff --git a/src/java.desktop/share/classes/java/awt/image/BufferedImage.java b/src/java.desktop/share/classes/java/awt/image/BufferedImage.java
index 52bf8a8c4bf3..7057be39fe12 100644
--- a/src/java.desktop/share/classes/java/awt/image/BufferedImage.java
+++ b/src/java.desktop/share/classes/java/awt/image/BufferedImage.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -282,13 +282,72 @@ public class BufferedImage extends java.awt.Image
         initIDs();
     }
 
+    private static void checkDimensions(final int width, final int height) {
+         if (width <= 0 || height <= 0) {
+             throw new IllegalArgumentException(
+                      "width " + width + " and height " + height + " must both be > 0");
+         }
+         long lsz = (long)width * height;
+         if (lsz > Integer.MAX_VALUE) {
+             throw new IllegalArgumentException(
+                      "width " + width + " * height " + height + " overflows int");
+         }
+    }
+
     /**
      * Constructs a {@code BufferedImage} of one of the predefined
      * image types.  The {@code ColorSpace} for the image is the
      * default sRGB space.
+     * @apiNote
+     * There are limits on the size of a {@code BufferedImage} that derive from
+     * the APIs involved and the exact implementation of a particular pre-defined type.
+     * 
    + *
  • {@code BufferedImage} is an image type that supports {@link #getNumXTiles() only one tile}. + *
  • The organization of samples (e.g. red, green, blue, and alpha channels) for the pixels + * are specified by the {@code SampleModel}. + *
  • Each of the pre-defined image types documents the {@code SampleModel} subtypes + * that it can use, not always directly, but as required by the {@code ColorModel}. + *
  • {@code SampleModel} supports only supports up to {@code Integer.MAX_VALUE} pixels, + * so no {@code BufferedImage} can exceed that number of pixels. + *
  • The pixels are stored in a {@code DataBuffer}. + *
  • A {@code DataBuffer} is a container for one or more banks of + * Java primitive arrays so the number of data elements that can be + * stored per bank is limited by the maximum size of a Java array. + * This is at most {@code Integer.MAX_VALUE} elements, and may be less. + *
+ * Therefore, the number of data elements needed per pixel for an {@code imageType} + * further limits the maximum image size, and this is not the same for all pre-defined + * image types. + *

+ * For example {@code TYPE_3BYTE_BGR} uses byte array elements for storage. + * If the {@code ComponentSampleModel} used by the implementation supports + * only a single bank in its {@code DataBuffer}, then it will only be able + * to hold one third as many pixels as an implementation that uses a + * {@code BandedSampleModel} and a {@code DataBuffer} with 3 banks, one per band. + *

+ * And {@code TYPE_INT_BGR} needs only one bank in its {@code DataBuffer} + * to support the same image size as the banded 3 byte format. + *

+ * So the maximum number of pixels in a {@code BufferedImage} is + * format and implementation dependent. Applications must be aware of these + * limitations when creating images. + * @implNote + * This implementation uses a single data bank to store all image data for + * the pre-defined image types {@code TYPE_3BYTE_BGR}, + * {@code TYPE_4BYTE_ABGR} and {@code TYPE_4BYTE_ABGR_PRE}. + * * @param width width of the created image * @param height height of the created image * @param imageType type of the created image + * @throws IllegalArgumentException if {@code width} or {@code height} is + * not greater than zero. + * @throws IllegalArgumentException if the multiplication product of + * {@code width} and {@code height} exceeds {@code Integer.MAX_VALUE}, + * or, when further multiplied by the number of data elements per pixel + * for the specified {@code imageType}, exceeds the maximum that can be stored + * by this implementation. + * @throws IllegalArgumentException if the {@code imageType} is not one of + * the pre-defined recognized image types. * @see ColorSpace * @see #TYPE_INT_RGB * @see #TYPE_INT_ARGB @@ -307,6 +366,31 @@ public class BufferedImage extends java.awt.Image public BufferedImage(int width, int height, int imageType) { + + checkDimensions(width, height); + + /* Most BufferedImage formats use one data buffer element per pixel. + * But for the NBYTE formats the BufferedImage implementation + * uses an interleaved raster which has a ByteDataBuffer of a single bank, + * so either 3 or 4 bytes is used for each pixel. + */ + int spp = 1; + switch (imageType) { + case TYPE_3BYTE_BGR: + spp = 3; + break; + case TYPE_4BYTE_ABGR: + case TYPE_4BYTE_ABGR_PRE: + spp = 4; + break; + } + long lsz = (long)width * height; + if ((spp != 1) && (lsz * spp > Integer.MAX_VALUE)) { + throw new IllegalArgumentException( + "width " + width + " * height " + height + " * " + + spp + " samples per pixel overflow int"); + } + switch (imageType) { case TYPE_INT_RGB: { @@ -517,6 +601,10 @@ public BufferedImage(int width, * @param height height of the created image * @param imageType type of the created image * @param cm {@code IndexColorModel} of the created image + * @throws IllegalArgumentException if {@code width} or {@code height} is + * not greater than zero. + * @throws IllegalArgumentException if the multiplication product of + * {@code width} and {@code height} exceeds {@code Integer.MAX_VALUE}. * @throws IllegalArgumentException if the imageType is not * TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED or if the imageType is * TYPE_BYTE_BINARY and the color map has more than 16 entries. @@ -527,6 +615,9 @@ public BufferedImage (int width, int height, int imageType, IndexColorModel cm) { + + checkDimensions(width, height); + if (cm.hasAlpha() && cm.isAlphaPremultiplied()) { throw new IllegalArgumentException("This image types do not have "+ "premultiplied alpha."); @@ -596,18 +687,12 @@ public BufferedImage (int width, * components. * @throws IllegalArgumentException if * {@code raster} is incompatible with {@code cm} + * @throws IllegalArgumentException if + * {@code raster.minX} or {@code raster.minY} is not zero * @see ColorModel * @see Raster * @see WritableRaster */ - - -/* - * - * FOR NOW THE CODE WHICH DEFINES THE RASTER TYPE IS DUPLICATED BY DVF - * SEE THE METHOD DEFINERASTERTYPE @ RASTEROUTPUTMANAGER - * - */ public BufferedImage (ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, diff --git a/src/java.desktop/share/legal/lcms.md b/src/java.desktop/share/legal/lcms.md index b2ea686eee06..0a130ae8bb5f 100644 --- a/src/java.desktop/share/legal/lcms.md +++ b/src/java.desktop/share/legal/lcms.md @@ -1,4 +1,4 @@ -## Little Color Management System (LCMS) v2.19.1 +## Little Color Management System (LCMS) v2.20.0 ### LCMS License

diff --git a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c
index 4022cb85bd45..6ddb1ee6b7af 100644
--- a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c
+++ b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1705,6 +1705,9 @@ jboolean ProcessPath(ProcessHandler* hnd,
 
                 break;
         }
+        if (hnd->resultCode != 0) {
+            return JNI_FALSE;
+        }
     }
 
     /* Performing closing of the unclosed segments */
@@ -1783,18 +1786,21 @@ typedef struct {
         (PTR)->plgMax = DF_MAX_POINT;                                       \
     } while(0)
 
-#define FD_ADD_POINT(PTR, X, Y, LASTPT)                                     \
+#define FD_ADD_POINT(HND, PTR, X, Y, LASTPT)                                \
     do {                                                                    \
         Point* _pnts = (PTR)->plgPnts;                                      \
         jint _size = (PTR)->plgSize;                                        \
         if (_size >= (PTR)->plgMax) {                                       \
             jint newMax = (PTR)->plgMax*2;                                  \
             if ((PTR)->plgPnts == (PTR)->dfPlgPnts) {                       \
-                (PTR)->plgPnts = (Point*)malloc(newMax*sizeof(Point));      \
-                memcpy((PTR)->plgPnts, _pnts, _size*sizeof(Point));         \
+                Point* _newp = (Point*)malloc(newMax*sizeof(Point));        \
+                if (_newp == NULL) { (HND)->resultCode = 1; break; }        \
+                memcpy(_newp, _pnts, _size*sizeof(Point));                  \
+                (PTR)->plgPnts = _newp;                                     \
             } else {                                                        \
-                (PTR)->plgPnts = (Point*)realloc(                           \
-                    _pnts, newMax*sizeof(Point));                           \
+                Point* _newp = (Point*)realloc(_pnts, newMax*sizeof(Point));\
+                if (_newp == NULL) { (HND)->resultCode = 1; break; }        \
+                (PTR)->plgPnts = _newp;                                     \
             }                                                               \
             _pnts = (PTR)->plgPnts;                                         \
             (PTR)->plgMax = newMax;                                         \
@@ -2157,10 +2163,10 @@ void  StoreFixedLine(ProcessHandler* hnd,jint x1,jint y1,jint x2,jint y2,
      * path
      */
     if (FD_IS_EMPTY(pfd) || FD_IS_ENDED(pfd)) {
-        FD_ADD_POINT(pfd, x1, y1, JNI_FALSE);
+        FD_ADD_POINT(hnd, pfd, x1, y1, JNI_FALSE);
     }
 
-    FD_ADD_POINT(pfd, x2, y2, JNI_FALSE);
+    FD_ADD_POINT(hnd, pfd, x2, y2, JNI_FALSE);
 
     if (endSubPath) {
         FD_SET_ENDED(pfd);
@@ -2196,7 +2202,8 @@ doFillPath(DrawHandler* dhnd,
         NULL,
         PH_STROKE_DEFAULT,
         PH_MODE_FILL_CLIP,
-        NULL
+        NULL,
+        0
     };
 
     /* Initialization of the following fields in the declaration of the hnd
@@ -2226,6 +2233,8 @@ doDrawPath(DrawHandler* dhnd,
                     jfloat* coords, jint maxCoords,
                     jbyte* types, jint numTypes, PHStroke stroke)
 {
+    jint res;
+
     ProcessHandler hnd =
     {
         &ProcessFixedLine,
@@ -2233,7 +2242,8 @@ doDrawPath(DrawHandler* dhnd,
         NULL,
         PH_STROKE_DEFAULT,
         PH_MODE_DRAW_CLIP,
-        NULL
+        NULL,
+        0
     };
 
     /* Initialization of the following fields in the declaration of the hnd
@@ -2242,9 +2252,14 @@ doDrawPath(DrawHandler* dhnd,
      */
     hnd.dhnd = dhnd;
     hnd.stroke = stroke;
+    hnd.resultCode = 0;
 
     hnd.pProcessEndSubPath = (pProcessEndSubPath == NULL)?
         stubEndSubPath : pProcessEndSubPath;
-    return ProcessPath(&hnd, (jfloat)transX, (jfloat)transY, coords, maxCoords,
-                       types, numTypes);
+    res = ProcessPath(&hnd, (jfloat)transX, (jfloat)transY, coords, maxCoords,
+                      types, numTypes);
+    if (!res) {
+        return JNI_FALSE;
+    }
+    return JNI_TRUE;
 }
diff --git a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.h b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.h
index dee4ce1f08b2..53ff8536a5b5 100644
--- a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.h
+++ b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.h
@@ -89,6 +89,7 @@ typedef struct _ProcessHandler {
     PHStroke stroke;
     PHClip clipMode;
     void* pData;
+    jint resultCode; /* 0 = OK, 1 = allocation error */
 } ProcessHandler;
 
 
diff --git a/src/java.desktop/share/native/liblcms/UPDATING.txt b/src/java.desktop/share/native/liblcms/UPDATING.txt
index 7c68243c65db..c64d3018f3ca 100644
--- a/src/java.desktop/share/native/liblcms/UPDATING.txt
+++ b/src/java.desktop/share/native/liblcms/UPDATING.txt
@@ -17,7 +17,7 @@ Update src/java.desktop/share/legal/lcms.md per the current license/copyrights/a
 
 Build on all platforms.
 If there are compiler warnings causing build failures, update the disabled warnings in
-make/modules/java.desktop/lib/Awt2dLibraries.gmk
+make/modules/java.desktop/lib/ClientLibraries.gmk
 Run all automated client tests on all platforms.
 Also run J2Ddemo and pay particular attention to the "color" tab.
 Visually verify the color transforms against the same with the current/previous JDK
\ No newline at end of file
diff --git a/src/java.desktop/share/native/liblcms/cmscgats.c b/src/java.desktop/share/native/liblcms/cmscgats.c
index d1585443816d..383ca8b6a8e9 100644
--- a/src/java.desktop/share/native/liblcms/cmscgats.c
+++ b/src/java.desktop/share/native/liblcms/cmscgats.c
@@ -2306,7 +2306,7 @@ cmsBool HeaderSection(cmsIT8* it8)
                     // for each pair, split the subkey and the value
                     Value = (char*)strrchr(Subkey, ',');
                     if (Value == NULL)
-                        return SynError(it8, "Invalid value for property '%s'.", VarName);
+                        break;
 
                     // gobble the spaces before the coma, and the coma itself
                     temp = Value++;
@@ -2321,7 +2321,7 @@ cmsBool HeaderSection(cmsIT8* it8)
                     Value += strspn(Value, " ");
 
                     if (Subkey[0] == 0 || Value[0] == 0)
-                        return SynError(it8, "Invalid value for property '%s'.", VarName);
+                        break;
                     AddToList(it8, &GetTable(it8)->HeaderList, VarName, Subkey, Value, WRITE_PAIR);
                 }
             }
@@ -2620,7 +2620,12 @@ cmsHANDLE  CMSEXPORT cmsIT8LoadFromMem(cmsContext ContextID, const void *Ptr, cm
     strncpy(it8->FileStack[0]->FileName, "", cmsMAX_PATH-1);
     it8-> Source = it8 -> MemoryBlock;
 
-    if (!ParseIT8(it8, type-1)) {
+    if (!ParseIT8(it8, type - 1)) {
+
+        while (it8->IncludeSP > 0) {
+            fclose(it8->FileStack[it8->IncludeSP]->Stream);
+            it8->IncludeSP--;
+        }
 
         cmsIT8Free(hIT8);
         return NULL;
@@ -2666,11 +2671,15 @@ cmsHANDLE  CMSEXPORT cmsIT8LoadFromFile(cmsContext ContextID, const char* cFileN
     strncpy(it8->FileStack[0]->FileName, cFileName, cmsMAX_PATH-1);
     it8->FileStack[0]->FileName[cmsMAX_PATH-1] = 0;
 
-    if (!ParseIT8(it8, type-1)) {
+    if (!ParseIT8(it8, type - 1)) {
 
-            fclose(it8 ->FileStack[0]->Stream);
-            cmsIT8Free(hIT8);
-            return NULL;
+        while (it8->IncludeSP > 0) {
+            fclose(it8->FileStack[it8->IncludeSP]->Stream);
+            it8->IncludeSP--;
+        }
+        fclose(it8->FileStack[0]->Stream);
+        cmsIT8Free(hIT8);
+        return NULL;
     }
 
     CookPointers(it8);
@@ -3199,7 +3208,10 @@ cmsBool ParseCube(cmsIT8* cube, cmsStage** Shaper, cmsStage** CLUT, char title[]
 
                     cmsFloat64Number nums[3];
 
-                    if (!ReadNumbers(cube, 3, nums)) return FALSE;
+                    if (!ReadNumbers(cube, 3, nums)) {
+                        _cmsFree(cube->ContextID, shapers);
+                        return FALSE;
+                    }
 
                     shapers[i + 0]               = (cmsFloat32Number) ((nums[0] - domain_min[0]) / (domain_max[0] - domain_min[0]));
                     shapers[i + 1 * shaper_size] = (cmsFloat32Number) ((nums[1] - domain_min[1]) / (domain_max[1] - domain_min[1]));
@@ -3216,11 +3228,13 @@ cmsBool ParseCube(cmsIT8* cube, cmsStage** Shaper, cmsStage** CLUT, char title[]
                 *Shaper = cmsStageAllocToneCurves(cube->ContextID, 3, curves);
 
                 cmsFreeToneCurveTriple(curves);
+                _cmsFree(cube->ContextID, shapers);
             }
 
             if (lut_size > 0) {
 
                 int nodes;
+                cmsFloat32Number* lut_table;
 
                 /**
                 * Professional LUT generation tools (e.g., Nobe LutBake) list 65×65×65 as their highest supported size.
@@ -3231,14 +3245,17 @@ cmsBool ParseCube(cmsIT8* cube, cmsStage** Shaper, cmsStage** CLUT, char title[]
                 nodes = lut_size * lut_size * lut_size;
 
 
-                cmsFloat32Number* lut_table = (cmsFloat32Number*) _cmsMalloc(cube->ContextID, nodes * 3 * sizeof(cmsFloat32Number));
+                lut_table = (cmsFloat32Number*) _cmsMalloc(cube->ContextID, nodes * 3 * sizeof(cmsFloat32Number));
                 if (lut_table == NULL) return FALSE;
 
                 for (i = 0; i < nodes; i++) {
 
                     cmsFloat64Number nums[3];
 
-                    if (!ReadNumbers(cube, 3, nums)) return FALSE;
+                    if (!ReadNumbers(cube, 3, nums)) {
+                        _cmsFree(cube->ContextID, lut_table);
+                        return FALSE;
+                    }
 
                     lut_table[i * 3 + 2] = (cmsFloat32Number) ((nums[0] - domain_min[0]) / (domain_max[0] - domain_min[0]));
                     lut_table[i * 3 + 1] = (cmsFloat32Number) ((nums[1] - domain_min[1]) / (domain_max[1] - domain_min[1]));
@@ -3265,7 +3282,7 @@ cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFileTHR(cmsContext ContextID, c
     cmsStage* CLUT = NULL;
     cmsStage* Shaper = NULL;
     cmsMLU* DescriptionMLU = NULL;
-    char title[MAXSTR];
+    char title[MAXSTR] = { 0 };
 
     _cmsAssert(cFileName != NULL);
 
@@ -3280,6 +3297,7 @@ cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFileTHR(cmsContext ContextID, c
     strncpy(cube->FileStack[0]->FileName, cFileName, cmsMAX_PATH - 1);
     cube->FileStack[0]->FileName[cmsMAX_PATH - 1] = 0;
 
+    // Note that it can allocate Shaper and CLUT even when failing
     if (!ParseCube(cube, &Shaper, &CLUT, title)) goto Done;
 
     // Success on parsing, let's create the profile
@@ -3301,16 +3319,16 @@ cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFileTHR(cmsContext ContextID, c
     // Populates the pipeline
     if (Shaper != NULL) {
         if (!cmsPipelineInsertStage(Pipeline, cmsAT_BEGIN, Shaper)) {
-            cmsStageFree(Shaper);
             goto Done;
         }
+        Shaper = NULL; // ownership has been transferred
     }
 
     if (CLUT != NULL) {
         if (!cmsPipelineInsertStage(Pipeline, cmsAT_END, CLUT)) {
-            cmsStageFree(CLUT);
             goto Done;
         }
+        CLUT = NULL;
     }
 
     // Propagate the description. We put no copyright because we know
@@ -3324,6 +3342,15 @@ cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFileTHR(cmsContext ContextID, c
 
 Done:
 
+    if (CLUT != NULL)
+        cmsStageFree(CLUT);
+
+    if (Shaper != NULL)
+        cmsStageFree(Shaper);
+
+    if (cube->FileStack[0]->Stream != NULL)
+        fclose(cube->FileStack[0]->Stream);
+
     if (DescriptionMLU != NULL)
         cmsMLUfree(DescriptionMLU);
 
diff --git a/src/java.desktop/share/native/liblcms/cmscnvrt.c b/src/java.desktop/share/native/liblcms/cmscnvrt.c
index c66dbcbebad8..aae3a07fe356 100644
--- a/src/java.desktop/share/native/liblcms/cmscnvrt.c
+++ b/src/java.desktop/share/native/liblcms/cmscnvrt.c
@@ -655,19 +655,22 @@ cmsPipeline* DefaultICCintents(cmsContext       ContextID,
     // Check for non-negatives clip
     if (dwFlags & cmsFLAGS_NONEGATIVES) {
 
-           if (ColorSpaceOut == cmsSigGrayData ||
-                  ColorSpaceOut == cmsSigRgbData ||
-                  ColorSpaceOut == cmsSigCmykData) {
+        if (ColorSpaceOut == cmsSigGrayData ||
+            ColorSpaceOut == cmsSigRgbData ||
+            ColorSpaceOut == cmsSigCmykData) {
 
-                  cmsStage* clip = _cmsStageClipNegatives(Result->ContextID, cmsChannelsOfColorSpace(ColorSpaceOut));
-                  if (clip == NULL) goto Error;
+            cmsStage* clip = _cmsStageClipNegatives(Result->ContextID, cmsChannelsOfColorSpace(ColorSpaceOut));
+            if (clip == NULL) goto Error;
 
-                  if (!cmsPipelineInsertStage(Result, cmsAT_END, clip))
-                         goto Error;
-           }
+            if (!cmsPipelineInsertStage(Result, cmsAT_END, clip))
+                goto Error;
+        }
 
     }
 
+    if (cmsChannelsOfColorSpace(ColorSpaceOut) != (cmsInt32Number) cmsPipelineOutputChannels(Result))
+        goto Error;
+
     return Result;
 
 Error:
@@ -852,11 +855,16 @@ cmsPipeline*  BlackPreservingKOnlyIntents(cmsContext     ContextID,
     // Insert possible devicelinks at the end
     for (i = lastProfilePos + 1; i < nProfiles; i++)
     {
+        int rc;
+
         cmsPipeline* devlink = _cmsReadDevicelinkLUT(hProfiles[i], ICCIntents[i]);
         if (devlink == NULL)
             goto Error;
 
-        if (!cmsPipelineCat(Result, devlink))
+        rc = cmsPipelineCat(Result, devlink);
+        cmsPipelineFree(devlink);
+
+        if (!rc)
             goto Error;
     }
 
@@ -1030,10 +1038,6 @@ cmsPipeline* BlackPreservingKPlaneIntents(cmsContext     ContextID,
         cmsGetDeviceClass(hLastProfile) == cmsSigOutputClass))
            return  DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
 
-    // Allocate an empty LUT for holding the result
-    Result = cmsPipelineAlloc(ContextID, 4, 4);
-    if (Result == NULL) return NULL;
-
     memset(&bp, 0, sizeof(bp));
 
     // We need the input LUT of the last profile, assuming this one is responsible of
@@ -1092,20 +1096,37 @@ cmsPipeline* BlackPreservingKPlaneIntents(cmsContext     ContextID,
     CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
     if (CLUT == NULL) goto Cleanup;
 
-    if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT))
+    // Allocate an empty LUT for holding the result
+    Result = cmsPipelineAlloc(ContextID, 4, 4);
+    if (Result == NULL) goto Cleanup;
+
+    if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT)) {
+        cmsPipelineFree(Result);
+        Result = NULL;
         goto Cleanup;
+    }
 
     cmsStageSampleCLut16bit(CLUT, BlackPreservingSampler, (void*) &bp, 0);
 
     // Insert possible devicelinks at the end
     for (i = lastProfilePos + 1; i < nProfiles; i++)
     {
+        int rc;
         cmsPipeline* devlink = _cmsReadDevicelinkLUT(hProfiles[i], ICCIntents[i]);
-        if (devlink == NULL)
+        if (devlink == NULL) {
+            cmsPipelineFree(Result);
+            Result = NULL;
             goto Cleanup;
+        }
 
-        if (!cmsPipelineCat(Result, devlink))
+        rc = cmsPipelineCat(Result, devlink);
+        cmsPipelineFree(devlink);
+
+        if (!rc) {
+            cmsPipelineFree(Result);
+            Result = NULL;
             goto Cleanup;
+        }
     }
 
 
diff --git a/src/java.desktop/share/native/liblcms/cmserr.c b/src/java.desktop/share/native/liblcms/cmserr.c
index 220602d4a361..d5beac1c88a4 100644
--- a/src/java.desktop/share/native/liblcms/cmserr.c
+++ b/src/java.desktop/share/native/liblcms/cmserr.c
@@ -619,6 +619,7 @@ static
 void* defMtxCreate(cmsContext id)
 {
     _cmsMutex* ptr_mutex = (_cmsMutex*) _cmsMalloc(id, sizeof(_cmsMutex));
+    if (ptr_mutex == NULL) return NULL;
     _cmsInitMutexPrimitive(ptr_mutex);
     return (void*) ptr_mutex;
 }
@@ -777,3 +778,43 @@ cmsBool _cmsRegisterParallelizationPlugin(cmsContext ContextID, cmsPluginBase* D
     return TRUE;
 }
 
+void _cmsAllocHeaderPluginChunk(struct _cmsContext_struct* ctx,
+                                const struct _cmsContext_struct* src)
+{
+    ctx->chunks[HeaderPlugin] = NULL;
+
+    if (src != NULL && src->chunks[HeaderPlugin] != NULL)
+        ctx->chunks[HeaderPlugin] = _cmsSubAllocDup(ctx->MemPool,
+                                                   src->chunks[HeaderPlugin],
+                                                   sizeof(_cmsHeaderPluginChunkType));
+}
+
+cmsBool _cmsRegisterHeaderPlugin(cmsContext ContextID, cmsPluginBase* Data)
+{
+    cmsPluginHeader* Plugin = (cmsPluginHeader*)Data;
+    struct _cmsContext_struct* ctx = _cmsGetContext(ContextID);
+    _cmsHeaderPluginChunkType* Chunk;
+
+    if (Data == NULL) {
+        ctx->chunks[HeaderPlugin] = NULL;
+        return TRUE;
+    }
+
+    if (Plugin->ReadPtr == NULL || Plugin->WritePtr == NULL)
+        return FALSE;
+
+    Chunk = (_cmsHeaderPluginChunkType*)ctx->chunks[HeaderPlugin];
+    if (Chunk == NULL) {
+        Chunk = (_cmsHeaderPluginChunkType*)
+            _cmsPluginMalloc(ContextID, sizeof(_cmsHeaderPluginChunkType));
+        if (Chunk == NULL)
+            return FALSE;
+
+        ctx->chunks[HeaderPlugin] = Chunk;
+    }
+
+    Chunk->ICCVersion = Plugin->ICCVersion;
+    Chunk->ReadPtr    = Plugin->ReadPtr;
+    Chunk->WritePtr   = Plugin->WritePtr;
+    return TRUE;
+}
diff --git a/src/java.desktop/share/native/liblcms/cmsintrp.c b/src/java.desktop/share/native/liblcms/cmsintrp.c
index 23e59a229a9f..c647934833df 100644
--- a/src/java.desktop/share/native/liblcms/cmsintrp.c
+++ b/src/java.desktop/share/native/liblcms/cmsintrp.c
@@ -406,8 +406,8 @@ void BilinearInterpFloat(const cmsFloat32Number Input[],
     px = fclamp(Input[0]) * p->Domain[0];
     py = fclamp(Input[1]) * p->Domain[1];
 
-    x0 = (int) _cmsQuickFloor(px); fx = px - (cmsFloat32Number) x0;
-    y0 = (int) _cmsQuickFloor(py); fy = py - (cmsFloat32Number) y0;
+    x0 = (int) floor(px); fx = px - (cmsFloat32Number) x0;
+    y0 = (int) floor(py); fy = py - (cmsFloat32Number) y0;
 
     X0 = p -> opta[1] * x0;
     X1 = X0 + (fclamp(Input[0]) >= 1.0 ? 0 : p->opta[1]);
@@ -1079,7 +1079,7 @@ void Eval4InputsFloat(const cmsFloat32Number Input[],
        cmsInterpParams p1;
 
        pk = fclamp(Input[0]) * p->Domain[0];
-       k0 = _cmsQuickFloor(pk);
+       k0 = (int)floor(pk);
        rest = pk - (cmsFloat32Number) k0;
 
        K0 = p -> opta[3] * k0;
@@ -1158,7 +1158,7 @@ static void Eval##N##InputsFloat(const cmsFloat32Number Input[], \
        cmsInterpParams p1;\
 \
        pk = fclamp(Input[0]) * p->Domain[0];\
-       k0 = _cmsQuickFloor(pk);\
+       k0 = (int) floor(pk);\
        rest = pk - (cmsFloat32Number) k0;\
 \
        K0 = p -> opta[NM] * k0;\
diff --git a/src/java.desktop/share/native/liblcms/cmsio0.c b/src/java.desktop/share/native/liblcms/cmsio0.c
index 6e2a856b4b81..287af893a4ec 100644
--- a/src/java.desktop/share/native/liblcms/cmsio0.c
+++ b/src/java.desktop/share/native/liblcms/cmsio0.c
@@ -271,7 +271,10 @@ cmsBool  MemoryClose(struct _cms_io_handler* iohandler)
 
     if (ResData ->FreeBlockOnClose) {
 
-        if (ResData ->Block) _cmsFree(iohandler ->ContextID, ResData ->Block);
+        if (ResData->Block) {
+            _cmsFree(iohandler->ContextID, ResData->Block);
+            ResData->Block = NULL;
+        }
     }
 
     _cmsFree(iohandler ->ContextID, ResData);
@@ -758,6 +761,7 @@ void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
         // Free previous version
         if (Icc ->TagSaveAsRaw[i]) {
             _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
+            Icc->TagPtrs[i] = NULL;
             Icc->TagSaveAsRaw[i] = FALSE;
         }
         else {
@@ -888,6 +892,60 @@ cmsBool validDeviceClass(cmsProfileClassSignature cl)
 
 }
 
+// Return the maximum version handled by the core or by the installed header plug-in.
+static
+cmsUInt32Number SupportedICCVersion(cmsContext ContextID)
+{
+    _cmsHeaderPluginChunkType* PluginChunk = (_cmsHeaderPluginChunkType*) _cmsContextGetClientChunk(ContextID, HeaderPlugin);
+
+    if (PluginChunk == NULL)
+        return 0x04400000;
+    else
+        return PluginChunk->ICCVersion;
+}
+
+// Invoke a profile-header read plug-in, preserving the caller's I/O position.
+static
+cmsBool ReadHeaderPlugin(_cmsICCPROFILE* Icc, cmsIOHANDLER* io)
+{
+    _cmsHeaderPluginChunkType* PluginChunk;
+    cmsUInt32Number CurrentPos;
+    cmsBool rc;
+
+    PluginChunk = (_cmsHeaderPluginChunkType*) _cmsContextGetClientChunk(Icc->ContextID, HeaderPlugin);
+    if (PluginChunk == NULL || PluginChunk->ReadPtr == NULL)
+        return TRUE;
+
+    CurrentPos = io->Tell(io);
+    rc = PluginChunk->ReadPtr(Icc->ContextID, (cmsHPROFILE)Icc, io);
+
+    if (!io->Seek(io, CurrentPos))
+        return FALSE;
+
+    return rc;
+}
+
+// Invoke a profile-header write plug-in, preserving the caller's I/O position.
+static
+cmsBool WriteHeaderPlugin(_cmsICCPROFILE* Icc, cmsIOHANDLER* io)
+{
+    _cmsHeaderPluginChunkType* PluginChunk;
+    cmsUInt32Number CurrentPos;
+    cmsBool rc;
+
+    PluginChunk = (_cmsHeaderPluginChunkType*) _cmsContextGetClientChunk(Icc->ContextID, HeaderPlugin);
+    if (PluginChunk == NULL || PluginChunk->WritePtr == NULL)
+        return TRUE;
+
+    CurrentPos = io->Tell(io);
+    rc = PluginChunk->WritePtr(Icc->ContextID, (cmsHPROFILE)Icc, io);
+
+    if (!io->Seek(io, CurrentPos))
+        return FALSE;
+
+    return rc;
+}
+
 // Read profile header and validate it
 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
 {
@@ -897,6 +955,7 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
     cmsUInt32Number HeaderSize;
     cmsIOHANDLER* io = Icc ->IOhandler;
     cmsUInt32Number TagCount;
+    cmsBool corruptedTagPos = FALSE;
 
 
     // Read the header
@@ -926,7 +985,7 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
     _cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
     Icc -> Version         = _cmsAdjustEndianess32(_validatedVersion(Header.version));
 
-    if (Icc->Version > 0x5000000) {
+    if (Icc->Version > SupportedICCVersion(Icc->ContextID)) {
         cmsSignalError(Icc->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported profile version '0x%x'", Icc->Version);
         return FALSE;
     }
@@ -939,8 +998,8 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
     // Get size as reported in header
     HeaderSize = _cmsAdjustEndianess32(Header.size);
 
-    // Make sure HeaderSize is lower than profile size
-    if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
+    // Make sure HeaderSize is at least same as reported size
+    if (HeaderSize >= Icc->IOhandler->ReportedSize)
             HeaderSize = Icc ->IOhandler ->ReportedSize;
 
 
@@ -950,6 +1009,8 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
     // The profile ID are 32 raw bytes
     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
 
+    if (!ReadHeaderPlugin(Icc, io))
+        return FALSE;
 
     // Read tag directory
     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
@@ -971,8 +1032,10 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
         // Perform some sanity check. Offset + size should fall inside file.
         if (Tag.size == 0 || Tag.offset == 0) continue;
         if (Tag.offset + Tag.size > HeaderSize ||
-            Tag.offset + Tag.size < Tag.offset)
-                  continue;
+            Tag.offset + Tag.size < Tag.offset) {
+            corruptedTagPos = TRUE;
+            continue;
+        }
 
         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
@@ -1010,6 +1073,14 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
         }
     }
 
+    // This is a small aid to diagnose malformed profiles. Please note that execution
+    // continues even if an error message is raised. This situation should NEVER occur
+    // with valid profiles and may indicate an attempted exploit.
+    if (corruptedTagPos) {
+        cmsSignalError(Icc->ContextID, cmsERROR_CORRUPTION_DETECTED,
+            "'size' field in header seems incorrect.");
+    }
+
     return TRUE;
 }
 
@@ -1021,6 +1092,11 @@ cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
     cmsTagEntry Tag;
     cmsUInt32Number Count;
 
+    if (Icc->Version > SupportedICCVersion(Icc->ContextID)) {
+        cmsSignalError(Icc->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported profile version '0x%x'", Icc->Version);
+        return FALSE;
+    }
+
     Header.size        = _cmsAdjustEndianess32(UsedSpace);
     Header.cmmId       = _cmsAdjustEndianess32(Icc ->CMM);
     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
@@ -1060,6 +1136,9 @@ cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
     // Dump the header
     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
 
+    if (!WriteHeaderPlugin(Icc, Icc->IOhandler))
+        return FALSE;
+
     // Saves Tag directory
 
     // Get true count
@@ -1414,7 +1493,31 @@ cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number
     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
 }
 
+// Set/Get user data for profiles
+void CMSEXPORT _cmsSetProfileUserData(cmsHPROFILE hProfile, void* Data, _cmsFreeUserDataFn FreeData)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*)hProfile;
+
+    _cmsAssert(Icc != NULL);
 
+    if (Icc->UsrData != NULL)
+    {
+        if (Icc->FreeUsrData != NULL)
+            Icc->FreeUsrData(Icc->ContextID, Icc->UsrData);
+    }
+
+    Icc->UsrData     = Data;
+    Icc->FreeUsrData = FreeData;
+}
+
+void* CMSEXPORT _cmsGetProfileUserData(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*)hProfile;
+
+    _cmsAssert(Icc != NULL);
+
+    return Icc->UsrData;
+}
 
 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
 static
@@ -1459,8 +1562,16 @@ cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
                     Mem = _cmsMalloc(Icc->ContextID, TagSize);
                     if (Mem == NULL) return FALSE;
 
-                    if (FileOrig->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
-                    if (!io->Write(io, TagSize, Mem)) return FALSE;
+                    if (FileOrig->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) {
+                        _cmsFree(Icc->ContextID, Mem);
+                        return FALSE;
+                    }
+
+                    if (!io->Write(io, TagSize, Mem)) {
+                        _cmsFree(Icc->ContextID, Mem);
+                        return FALSE;
+                    }
+
                     _cmsFree(Icc->ContextID, Mem);
 
                     Icc->TagSizes[i] = (io->UsedSpace - Begin);
@@ -1720,6 +1831,9 @@ cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
         rc &= cmsCloseIOhandler(Icc->IOhandler);
     }
 
+    if (Icc->UsrData != NULL && Icc->FreeUsrData != NULL)
+        Icc->FreeUsrData(Icc->ContextID, Icc->UsrData);
+
     _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
 
     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
@@ -2175,9 +2289,10 @@ cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, cons
     }
 
     // Mark the tag as being written as RAW
-    Icc ->TagSaveAsRaw[i] = TRUE;
-    Icc ->TagNames[i]     = sig;
-    Icc ->TagLinked[i]    = (cmsTagSignature) 0;
+    Icc ->TagSaveAsRaw[i]    = TRUE;
+    Icc ->TagNames[i]        = sig;
+    Icc ->TagLinked[i]       = (cmsTagSignature) 0;
+    Icc ->TagTypeHandlers[i] = NULL;
 
     // Keep a copy of the block
     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
diff --git a/src/java.desktop/share/native/liblcms/cmslut.c b/src/java.desktop/share/native/liblcms/cmslut.c
index 6ac5b63d2de1..9cc5d95c81b2 100644
--- a/src/java.desktop/share/native/liblcms/cmslut.c
+++ b/src/java.desktop/share/native/liblcms/cmslut.c
@@ -1538,7 +1538,7 @@ cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
 
     if (!BlessLUT(NewLUT))
     {
-        _cmsFree(lut->ContextID, NewLUT);
+        cmsPipelineFree(NewLUT);
         return NULL;
     }
 
diff --git a/src/java.desktop/share/native/liblcms/cmsnamed.c b/src/java.desktop/share/native/liblcms/cmsnamed.c
index 4338b7cb8f58..06e77cb334ca 100644
--- a/src/java.desktop/share/native/liblcms/cmsnamed.c
+++ b/src/java.desktop/share/native/liblcms/cmsnamed.c
@@ -287,8 +287,9 @@ cmsUInt32Number decodeUTF8(wchar_t* out, const char* in)
                     {
                         *out++ = (wchar_t)(0xd800 + (codepoint >> 10));
                         *out++ = (wchar_t)(0xdc00 + (codepoint & 0x03ff));
-                        size += 2;
                     }
+
+                    size += 2;
                 }
                 else
                     if (codepoint < 0xd800 || codepoint >= 0xe000)
diff --git a/src/java.desktop/share/native/liblcms/cmsopt.c b/src/java.desktop/share/native/liblcms/cmsopt.c
index bba317223835..bb11d6a65d3d 100644
--- a/src/java.desktop/share/native/liblcms/cmsopt.c
+++ b/src/java.desktop/share/native/liblcms/cmsopt.c
@@ -663,6 +663,16 @@ cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColor
     return TRUE;
 }
 
+// Adapt the interpolation callback to the pipeline evaluator signature.
+static
+void CLUTEval16(const cmsUInt16Number In[], cmsUInt16Number Out[], const void* D)
+{
+    const cmsInterpParams* p = (const cmsInterpParams*) D;
+
+    p ->Interpolation.Lerp16(In, Out, p);
+}
+
+
 // -----------------------------------------------------------------------------------------------------------------------------------------------
 // This function creates simple LUT from complex ones. The generated LUT has an optional set of
 // prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
@@ -807,7 +817,7 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
 
     if (DataSetIn == NULL && DataSetOut == NULL) {
 
-        _cmsPipelineSetOptimizationParameters(Dest, (_cmsPipelineEval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
+        _cmsPipelineSetOptimizationParameters(Dest, CLUTEval16, DataCLUT->Params, NULL, NULL);
     }
     else {
 
@@ -1658,12 +1668,16 @@ void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8Bi
 
 // Compute the matrix-shaper structure
 static
-cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
+cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3],
+                     cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat)
 {
     MatShaper8Data* p;
     int i, j;
     cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
 
+    // Cannot use the 8 bit reduction trick here
+    if (T_PREMUL(*InputFormat) || T_PREMUL(*OutputFormat)) return FALSE;
+
     // Allocate a big chuck of memory to store precomputed tables
     p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));
     if (p == NULL) return FALSE;
@@ -1821,7 +1835,7 @@ cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
         *dwFlags |= cmsFLAGS_NOCACHE;
 
         // Setup the optimizarion routines
-        SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, OutputFormat);
+        SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, InputFormat, OutputFormat);
     }
 
     cmsPipelineFree(Src);
diff --git a/src/java.desktop/share/native/liblcms/cmspack.c b/src/java.desktop/share/native/liblcms/cmspack.c
index b740567af3b6..10ce9f36383a 100644
--- a/src/java.desktop/share/native/liblcms/cmspack.c
+++ b/src/java.desktop/share/native/liblcms/cmspack.c
@@ -603,6 +603,7 @@ cmsUInt8Number* UnrollAnyWordsPremul(CMSREGISTER _cmsTRANSFORM* info,
    cmsUInt32Number DoSwap      = T_DOSWAP(info ->InputFormat);
    cmsUInt32Number Reverse     = T_FLAVOR(info ->InputFormat);
    cmsUInt32Number SwapFirst   = T_SWAPFIRST(info -> InputFormat);
+   cmsUInt32Number Extra       = T_EXTRA(info -> InputFormat);
    cmsUInt32Number ExtraFirst  = DoSwap ^ SwapFirst;
    cmsUInt32Number i;
 
@@ -610,7 +611,7 @@ cmsUInt8Number* UnrollAnyWordsPremul(CMSREGISTER _cmsTRANSFORM* info,
    cmsUInt32Number alpha_factor = _cmsToFixedDomain(alpha);
 
     if (ExtraFirst) {
-        accum += sizeof(cmsUInt16Number);
+        accum += Extra * sizeof(cmsUInt16Number);
     }
 
     for (i=0; i < nChan; i++) {
@@ -633,7 +634,7 @@ cmsUInt8Number* UnrollAnyWordsPremul(CMSREGISTER _cmsTRANSFORM* info,
     }
 
     if (!ExtraFirst) {
-        accum += sizeof(cmsUInt16Number);
+        accum += Extra * sizeof(cmsUInt16Number);
     }
 
     return accum;
@@ -687,6 +688,7 @@ cmsUInt8Number* UnrollPlanarWordsPremul(CMSREGISTER _cmsTRANSFORM* info,
     cmsUInt32Number SwapFirst = T_SWAPFIRST(info->InputFormat);
     cmsUInt32Number Reverse= T_FLAVOR(info ->InputFormat);
     cmsUInt32Number SwapEndian = T_ENDIAN16(info -> InputFormat);
+    cmsUInt32Number Extra = T_EXTRA(info -> InputFormat);
     cmsUInt32Number i;
     cmsUInt32Number ExtraFirst = DoSwap ^ SwapFirst;
     cmsUInt8Number* Init = accum;
@@ -695,7 +697,7 @@ cmsUInt8Number* UnrollPlanarWordsPremul(CMSREGISTER _cmsTRANSFORM* info,
     cmsUInt32Number alpha_factor = _cmsToFixedDomain(alpha);
 
     if (ExtraFirst) {
-        accum += Stride;
+        accum += Extra * Stride;
     }
 
     for (i=0; i < nChan; i++) {
@@ -1916,7 +1918,7 @@ cmsUInt8Number* PackPlanarWords(CMSREGISTER _cmsTRANSFORM* info,
     else
     {
         if (Premul && Extra)
-            alpha_factor = _cmsToFixedDomain(((cmsUInt16Number*)output)[nChan * Stride]);
+            alpha_factor = _cmsToFixedDomain(*(cmsUInt16Number*) (&output[nChan * Stride]));
     }
 
     for (i=0; i < nChan; i++) {
@@ -2762,6 +2764,8 @@ cmsUInt8Number* PackLabDoubleFrom16(CMSREGISTER _cmsTRANSFORM* info,
         cmsFloat64Number* Out = (cmsFloat64Number*) output;
         cmsLabEncoded2Float(&Lab, wOut);
 
+        Stride /= PixelSize(info->OutputFormat);
+
         Out[0]        = Lab.L;
         Out[Stride]   = Lab.a;
         Out[Stride*2] = Lab.b;
@@ -3402,7 +3406,7 @@ cmsUInt8Number* UnrollHalfTo16(CMSREGISTER _cmsTRANSFORM* info,
     cmsFloat32Number maximum = IsInkSpace(info ->InputFormat) ? 655.35F : 65535.0F;
 
 
-    Stride /= PixelSize(info->OutputFormat);
+    Stride /= PixelSize(info->InputFormat);
 
     if (ExtraFirst)
             start = Extra;
diff --git a/src/java.desktop/share/native/liblcms/cmsplugin.c b/src/java.desktop/share/native/liblcms/cmsplugin.c
index a943c9f4dd96..127c85802cdd 100644
--- a/src/java.desktop/share/native/liblcms/cmsplugin.c
+++ b/src/java.desktop/share/native/liblcms/cmsplugin.c
@@ -641,6 +641,10 @@ cmsBool CMSEXPORT cmsPluginTHR(cmsContext id, void* Plug_in)
                     if (!_cmsRegisterParallelizationPlugin(id, Plugin)) return FALSE;
                     break;
 
+                case cmsPluginHeaderSig:
+                    if (!_cmsRegisterHeaderPlugin(id, Plugin)) return FALSE;
+                    break;
+
                 default:
                     cmsSignalError(id, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin type '%X'", Plugin -> Type);
                     return FALSE;
@@ -681,7 +685,8 @@ static struct _cmsContext_struct globalContext = {
         &_cmsOptimizationPluginChunk,    //  OptimizationPlugin,
         &_cmsTransformPluginChunk,       //  TransformPlugin,
         &_cmsMutexPluginChunk,           //  MutexPlugin,
-        &_cmsParallelizationPluginChunk  //  ParallelizationPlugin
+        &_cmsParallelizationPluginChunk, //  ParallelizationPlugin
+        NULL                             //  HeaderPlugin
     },
 
     { NULL, NULL, NULL, NULL, NULL, NULL } // The default memory allocator is not used for context 0
@@ -820,7 +825,7 @@ void CMSEXPORT cmsUnregisterPluginsTHR(cmsContext ContextID)
     _cmsRegisterTransformPlugin(ContextID, NULL);
     _cmsRegisterMutexPlugin(ContextID, NULL);
     _cmsRegisterParallelizationPlugin(ContextID, NULL);
-
+    _cmsRegisterHeaderPlugin(ContextID, NULL);
 }
 
 
@@ -972,16 +977,24 @@ cmsContext CMSEXPORT cmsDupContext(cmsContext ContextID, void* NewUserData)
     _cmsAllocTransformPluginChunk(ctx, src);
     _cmsAllocMutexPluginChunk(ctx, src);
     _cmsAllocParallelizationPluginChunk(ctx, src);
+    _cmsAllocHeaderPluginChunk(ctx, src);
 
     // Make sure no one failed
     for (i=Logger; i < MemoryClientMax; i++) {
 
+        if (i == HeaderPlugin) continue;
+
         if (src ->chunks[i] == NULL) {
             cmsDeleteContext((cmsContext) ctx);
             return NULL;
         }
     }
 
+    if (src->chunks[HeaderPlugin] != NULL && ctx->chunks[HeaderPlugin] == NULL) {
+        cmsDeleteContext((cmsContext) ctx);
+        return NULL;
+    }
+
     return (cmsContext) ctx;
 }
 
diff --git a/src/java.desktop/share/native/liblcms/cmsps2.c b/src/java.desktop/share/native/liblcms/cmsps2.c
index 3901f92d2127..7f8cf5697626 100644
--- a/src/java.desktop/share/native/liblcms/cmsps2.c
+++ b/src/java.desktop/share/native/liblcms/cmsps2.c
@@ -847,7 +847,7 @@ int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, cmsUInt32Number Inte
         mpe = mpe ->Next;
     }
 
-    if (cmsStageType(mpe) == cmsSigCLutElemType) {
+    if (mpe != NULL && cmsStageType(mpe) == cmsSigCLutElemType) {
 
             _cmsIOPrintf(m, "/Table ");
             WriteCLUT(m, mpe, PreMaj, PostMaj, PreMin, PostMin, FALSE, (cmsColorSpaceSignature) 0);
diff --git a/src/java.desktop/share/native/liblcms/cmssamp.c b/src/java.desktop/share/native/liblcms/cmssamp.c
index 7c8c93d9d52d..30aa2e982eb0 100644
--- a/src/java.desktop/share/native/liblcms/cmssamp.c
+++ b/src/java.desktop/share/native/liblcms/cmssamp.c
@@ -152,6 +152,9 @@ cmsBool  BlackPointAsDarkerColorant(cmsHPROFILE    hInput,
     // Convert black to Lab
     cmsDoTransform(xform, Black, &Lab, 1);
 
+    // Force it to be neutral, check for inconsistencies
+    Lab.a = Lab.b = 0;
+
     if (Lab.L > 95)
         Lab.L = 0;  // for synthetical negative profiles
     else if (Lab.L < 0)
diff --git a/src/java.desktop/share/native/liblcms/cmstypes.c b/src/java.desktop/share/native/liblcms/cmstypes.c
index 6ef3031aee09..928806d91567 100644
--- a/src/java.desktop/share/native/liblcms/cmstypes.c
+++ b/src/java.desktop/share/native/liblcms/cmstypes.c
@@ -156,8 +156,28 @@ cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t*
     _cmsAssert(io != NULL);
     _cmsAssert(!(Array == NULL && n > 0));
 
-    for (i=0; i < n; i++) {
-        if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Array[i])) return FALSE;
+    for (i = 0; i < n; i++) {
+
+        wchar_t v = Array[i];
+        cmsUInt16Number out;
+
+        if (sizeof(wchar_t) == 4) {    // WCHAR_MAX support is required for C99
+
+            // UTF-32 wchar_t platforms
+            if (v <= 0xFFFF && !(v >= 0xD800 && v <= 0xDFFF))
+                out = (cmsUInt16Number)v;
+            else
+                out = (cmsUInt16Number)'?';
+        }
+        else {
+
+            // UTF-16 wchar_t platforms:
+            // preserve code units exactly, including surrogates.
+            out = (cmsUInt16Number)v;
+        }
+
+        if (!_cmsWriteUInt16Number(io, out))
+            return FALSE;
     }
 
     return TRUE;
@@ -1181,6 +1201,7 @@ void *Type_Text_Description_Read(struct _cms_typehandler_struct* self, cmsIOHAND
 
     if (!_cmsReadWCharArray(io, UnicodeCount, UnicodeString)) {
         _cmsFree(self->ContextID, (void*)UnicodeString);
+        UnicodeString = NULL;
         goto Done;
     }
 
@@ -1188,6 +1209,7 @@ void *Type_Text_Description_Read(struct _cms_typehandler_struct* self, cmsIOHAND
 
     if (!cmsMLUsetWide(mlu, cmsV2Unicode, cmsV2Unicode, UnicodeString)) {
         _cmsFree(self->ContextID, (void*)UnicodeString);
+        UnicodeString = NULL;
         goto Done;
     }
 
@@ -4814,6 +4836,7 @@ void *Type_MPE_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsU
     if (NewLUT == NULL) return NULL;
 
     if (!_cmsReadUInt32Number(io, &ElementCount)) goto Error;
+    if (ElementCount > 50) goto Error;
     if (!ReadPositionTable(self, io, ElementCount, BaseOffset, NewLUT, ReadMPEElem)) goto Error;
 
     // Check channel count
@@ -5210,6 +5233,7 @@ cmsBool AllocElem(cmsContext ContextID, _cmsDICelem* e,  cmsUInt32Number Count)
     if (e->Sizes == NULL) {
 
         _cmsFree(ContextID, e -> Offsets);
+        e->Offsets = NULL;
         return FALSE;
     }
 
@@ -5374,6 +5398,7 @@ cmsBool ReadOneWChar(cmsIOHANDLER* io,  _cmsDICelem* e, cmsUInt32Number i, wchar
 
       if (!_cmsReadWCharArray(io, nChars, *wcstr)) {
           _cmsFree(e ->ContextID, *wcstr);
+          *wcstr = NULL;
           return FALSE;
       }
 
@@ -5527,10 +5552,25 @@ void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* i
             rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU);
         }
 
-        if (NameWCS != NULL) _cmsFree(self ->ContextID, NameWCS);
-        if (ValueWCS != NULL) _cmsFree(self ->ContextID, ValueWCS);
-        if (DisplayNameMLU != NULL) cmsMLUfree(DisplayNameMLU);
-        if (DisplayValueMLU != NULL) cmsMLUfree(DisplayValueMLU);
+        if (NameWCS != NULL) {
+            _cmsFree(self->ContextID, NameWCS);
+            NameWCS = NULL;
+        }
+
+        if (ValueWCS != NULL) {
+            _cmsFree(self->ContextID, ValueWCS);
+            ValueWCS = NULL;
+        }
+
+        if (DisplayNameMLU != NULL) {
+            cmsMLUfree(DisplayNameMLU);
+            DisplayNameMLU = NULL;
+        }
+
+        if (DisplayValueMLU != NULL) {
+            cmsMLUfree(DisplayValueMLU);
+            DisplayValueMLU = NULL;
+        }
 
         if (!rc) goto Error;
     }
@@ -5542,6 +5582,10 @@ void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* i
 Error:
    FreeArray(&a);
    if (hDict != NULL) cmsDictFree(hDict);
+   if (NameWCS != NULL) _cmsFree(self->ContextID, NameWCS);
+   if (ValueWCS != NULL) _cmsFree(self->ContextID, ValueWCS);
+   if (DisplayNameMLU != NULL) cmsMLUfree(DisplayNameMLU);
+   if (DisplayValueMLU != NULL) cmsMLUfree(DisplayValueMLU);
    return NULL;
 }
 
diff --git a/src/java.desktop/share/native/liblcms/cmsvirt.c b/src/java.desktop/share/native/liblcms/cmsvirt.c
index 2b5cdf896f8b..8aef42eaa622 100644
--- a/src/java.desktop/share/native/liblcms/cmsvirt.c
+++ b/src/java.desktop/share/native/liblcms/cmsvirt.c
@@ -503,8 +503,14 @@ cmsHPROFILE CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIE
 {
     cmsHPROFILE hProfile;
     cmsPipeline* LUT = NULL;
+    cmsCIEXYZ xyz;
 
-    hProfile = cmsCreateRGBProfileTHR(ContextID, WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
+    if (WhitePoint == NULL)
+        xyz = *cmsD50_XYZ();
+    else
+        cmsxyY2XYZ(&xyz, WhitePoint);
+
+    hProfile = cmsCreateRGBProfileTHR(ContextID, NULL, NULL, NULL);
     if (hProfile == NULL) return NULL;
 
     cmsSetProfileVersion(hProfile, 2.1);
@@ -513,8 +519,8 @@ cmsHPROFILE CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIE
     cmsSetColorSpace(hProfile,  cmsSigLabData);
     cmsSetPCS(hProfile,         cmsSigLabData);
 
-    if (!SetTextTags(hProfile, L"Lab identity built-in"))
-        goto Error;
+    if (!cmsWriteTag(hProfile, cmsSigMediaWhitePointTag, &xyz)) goto Error;
+    if (!SetTextTags(hProfile, L"Lab identity built-in")) goto Error;
 
     // An identity LUT is all we need
     LUT = cmsPipelineAlloc(ContextID, 3, 3);
@@ -524,9 +530,7 @@ cmsHPROFILE CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIE
     if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCLut(ContextID, 3)))
         goto Error;
 
-    if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT))
-        goto Error;
-
+    if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
     cmsPipelineFree(LUT);
 
     return hProfile;
diff --git a/src/java.desktop/share/native/liblcms/cmsxform.c b/src/java.desktop/share/native/liblcms/cmsxform.c
index 397266551b97..c330b114abf4 100644
--- a/src/java.desktop/share/native/liblcms/cmsxform.c
+++ b/src/java.desktop/share/native/liblcms/cmsxform.c
@@ -949,7 +949,6 @@ _cmsTRANSFORM* AllocEmptyTransform(cmsContext ContextID, cmsPipeline* lut,
         // Get formatter function always return a valid union, but the contents of this union may be NULL.
         p ->FromInputFloat = _cmsGetFormatter(ContextID, *InputFormat,  cmsFormatterInput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
         p ->ToOutputFloat  = _cmsGetFormatter(ContextID, *OutputFormat, cmsFormatterOutput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
-        *dwFlags |= cmsFLAGS_CAN_CHANGE_FORMATTER;
 
         if (p ->FromInputFloat == NULL || p ->ToOutputFloat == NULL) {
 
@@ -1184,7 +1183,7 @@ cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
         if (hGamutProfile == NULL) dwFlags &= ~cmsFLAGS_GAMUTCHECK;
     }
 
-    if ((dwFlags & cmsFLAGS_GAMUTCHECK) && (nGamutPCSposition <= 0 || nGamutPCSposition >= nProfiles - 1)) {
+    if ((dwFlags & cmsFLAGS_GAMUTCHECK) && (nGamutPCSposition <= 0 || nGamutPCSposition > nProfiles - 1)) {
         cmsSignalError(ContextID, cmsERROR_RANGE, "Wrong gamut PCS position '%d'", nGamutPCSposition);
         return NULL;
     }
@@ -1252,12 +1251,20 @@ cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
 
 
     // Create a gamut check LUT if requested
-    if (hGamutProfile != NULL && (dwFlags & cmsFLAGS_GAMUTCHECK))
+    if (hGamutProfile != NULL && (dwFlags & cmsFLAGS_GAMUTCHECK)) {
+
         xform ->GamutCheck  = _cmsCreateGamutCheckPipeline(ContextID, hProfiles,
                                                         BPC, Intents,
                                                         AdaptationStates,
                                                         nGamutPCSposition,
                                                         hGamutProfile);
+        if (xform->GamutCheck == NULL) {
+            cmsSignalError(ContextID, cmsERROR_NULL, "Could't create gamut check on transform");
+            cmsDeleteTransform(xform);
+            return NULL;
+        }
+
+    }
 
 
     // Try to read input and output colorant table
@@ -1498,7 +1505,7 @@ cmsBool CMSEXPORT cmsChangeBuffersFormat(cmsHTRANSFORM hTransform,
     // We only can afford to change formatters if previous transform is at least 16 bits
     if (!(xform ->dwOriginalFlags & cmsFLAGS_CAN_CHANGE_FORMATTER)) {
 
-        cmsSignalError(xform ->ContextID, cmsERROR_NOT_SUITABLE, "cmsChangeBuffersFormat works only on transforms created originally with at least 16 bits of precision");
+        cmsSignalError(xform ->ContextID, cmsERROR_NOT_SUITABLE, "cmsChangeBuffersFormat works only on transforms created originally with 16 bits of precision");
         return FALSE;
     }
 
diff --git a/src/java.desktop/share/native/liblcms/lcms2.h b/src/java.desktop/share/native/liblcms/lcms2.h
index f05378ad95eb..ffff578490ef 100644
--- a/src/java.desktop/share/native/liblcms/lcms2.h
+++ b/src/java.desktop/share/native/liblcms/lcms2.h
@@ -52,7 +52,7 @@
 //
 //---------------------------------------------------------------------------------
 //
-// Version 2.19
+// Version 2.20
 //
 
 #ifndef _lcms2_H
@@ -115,7 +115,9 @@
 
 #ifndef CMS_USE_CPP_API
 #   ifdef __cplusplus
-#       if __cplusplus >= 201703L
+        // MSVC keeps __cplusplus at 199711L unless /Zc:__cplusplus is passed, so also
+        // honor _MSVC_LANG; otherwise the C++17 'register' removal below never triggers.
+#       if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
 #            define CMS_NO_REGISTER_KEYWORD 1
 #       endif
 extern "C" {
@@ -123,7 +125,7 @@ extern "C" {
 #endif
 
 // Version/release
-#define LCMS_VERSION        2190
+#define LCMS_VERSION        2200
 
 // I will give the chance of redefining basic types for compilers that are not fully C99 compliant
 #ifndef CMS_BASIC_TYPES_ALREADY_DEFINED
diff --git a/src/java.desktop/share/native/liblcms/lcms2_internal.h b/src/java.desktop/share/native/liblcms/lcms2_internal.h
index 073e497b1b85..5c1df49aab65 100644
--- a/src/java.desktop/share/native/liblcms/lcms2_internal.h
+++ b/src/java.desktop/share/native/liblcms/lcms2_internal.h
@@ -471,6 +471,9 @@ cmsBool _cmsRegisterMutexPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
 // Parallelization
 cmsBool _cmsRegisterParallelizationPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
 
+// Header
+cmsBool _cmsRegisterHeaderPlugin(cmsContext ContextID, cmsPluginBase* Data);
+
 // ---------------------------------------------------------------------------------------------------------
 
 // Suballocators.
@@ -519,6 +522,7 @@ typedef enum {
     TransformPlugin,
     MutexPlugin,
     ParallelizationPlugin,
+    HeaderPlugin,
 
     // Last in list
     MemoryClientMax
@@ -770,7 +774,17 @@ extern  _cmsParallelizationPluginChunkType _cmsParallelizationPluginChunk;
 void _cmsAllocParallelizationPluginChunk(struct _cmsContext_struct* ctx,
                                          const struct _cmsContext_struct* src);
 
+// Container for header plug-in
+typedef struct {
+
+    cmsUInt32Number          ICCVersion;
+    _cmsReadProfileHeaderFn  ReadPtr;
+    _cmsWriteProfileHeaderFn WritePtr;
 
+} _cmsHeaderPluginChunkType;
+
+void _cmsAllocHeaderPluginChunk(struct _cmsContext_struct* ctx,
+                                const struct _cmsContext_struct* src);
 
 // ----------------------------------------------------------------------------------
 // MLU internal representation
@@ -876,6 +890,10 @@ typedef struct _cms_iccprofile_struct {
     // Keep a mutex for cmsReadTag -- Note that this only works if the user includes a mutex plugin
     void *                   UsrMutex;
 
+    // User data for profile plug-ins
+    void *                   UsrData;
+    _cmsFreeUserDataFn       FreeUsrData;
+
 } _cmsICCPROFILE;
 
 // IO helpers for profiles
diff --git a/src/java.desktop/share/native/liblcms/lcms2_plugin.h b/src/java.desktop/share/native/liblcms/lcms2_plugin.h
index 85de9bc56d5f..a4b598b17377 100644
--- a/src/java.desktop/share/native/liblcms/lcms2_plugin.h
+++ b/src/java.desktop/share/native/liblcms/lcms2_plugin.h
@@ -239,6 +239,7 @@ typedef void*    (* _cmsDupUserDataFn)(cmsContext ContextID, const void* Data);
 #define cmsPluginTransformSig                0x7A666D48     // 'xfmH'
 #define cmsPluginMutexSig                    0x6D747A48     // 'mtxH'
 #define cmsPluginParalellizationSig          0x70726C48     // 'prlH
+#define cmsPluginHeaderSig                   0x68647248     // 'hdrH'
 
 typedef struct _cmsPluginBaseStruct {
 
@@ -375,6 +376,7 @@ typedef struct {
 // Formatter16 callback
 
 struct _cmstransform_struct;
+struct _cmsiccprofile_struct;
 
 typedef cmsUInt8Number* (* cmsFormatter16)(CMSREGISTER struct _cmstransform_struct* CMMcargo,
                                            CMSREGISTER cmsUInt16Number Values[],
@@ -719,6 +721,34 @@ typedef struct {
 }  cmsPluginParalellization;
 
 
+
+//----------------------------------------------------------------------------------------------------------
+// Header
+
+CMSAPI void   CMSEXPORT _cmsSetProfileUserData(cmsHPROFILE hProfile, void* Data, _cmsFreeUserDataFn FreeData);
+CMSAPI void*  CMSEXPORT _cmsGetProfileUserData(cmsHPROFILE hProfile);
+
+// The plug-in may use the I/O handler freely, but must not close it.
+// LittleCMS restores the handler position after each callback.
+
+typedef cmsBool (*_cmsReadProfileHeaderFn)(cmsContext ContextID,
+                                           cmsHPROFILE hProfile,
+                                           cmsIOHANDLER* io);
+
+typedef cmsBool (*_cmsWriteProfileHeaderFn)(cmsContext ContextID,
+                                            cmsHPROFILE hProfile,
+                                            cmsIOHANDLER* io);
+
+typedef struct {
+    cmsPluginBase              base;
+
+    cmsUInt32Number            ICCVersion;
+    _cmsReadProfileHeaderFn    ReadPtr;
+    _cmsWriteProfileHeaderFn   WritePtr;
+
+} cmsPluginHeader;
+
+
 #ifndef CMS_USE_CPP_API
 #   ifdef __cplusplus
     }
diff --git a/src/java.desktop/unix/native/common/java2d/x11/X11Renderer.c b/src/java.desktop/unix/native/common/java2d/x11/X11Renderer.c
index f01986ea9837..370950f38063 100644
--- a/src/java.desktop/unix/native/common/java2d/x11/X11Renderer.c
+++ b/src/java.desktop/unix/native/common/java2d/x11/X11Renderer.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -82,11 +82,14 @@ typedef struct {
         if (_npnts >= (PTR)->maxpoints) {                                   \
             jint newMax = (PTR)->maxpoints*2;                               \
             if ((PTR)->pPoints == (PTR)->dfPoints) {                        \
-                (PTR)->pPoints = (XPoint*)malloc(newMax*sizeof(XPoint));    \
-                memcpy((PTR)->pPoints, _pnts, _npnts*sizeof(XPoint));       \
+                XPoint* _newp = (XPoint*)malloc(newMax*sizeof(XPoint));     \
+                if (_newp == NULL) break;                                   \
+                memcpy(_newp, _pnts, _npnts*sizeof(XPoint));                \
+                (PTR)->pPoints = _newp;                                     \
             } else {                                                        \
-                (PTR)->pPoints = (XPoint*)realloc(                          \
-                    _pnts, newMax*sizeof(XPoint));                          \
+                XPoint* _newp = (XPoint*)realloc(_pnts, newMax*sizeof(XPoint)); \
+                if (_newp == NULL) break;                                   \
+                (PTR)->pPoints = _newp;                                     \
             }                                                               \
             _pnts = (PTR)->pPoints;                                         \
             (PTR)->maxpoints = newMax;                                      \
diff --git a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java
index 7b505de2801a..c2bed0c1b78e 100644
--- a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java
+++ b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java
@@ -35,6 +35,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InvalidObjectException;
+import java.io.ObjectInputFilter;
 import java.io.ObjectInputStream;
 import java.io.ObjectStreamClass;
 import java.io.Serializable;
@@ -1811,6 +1812,74 @@ private static RMIServer narrowJRMPServer(Object objref) {
         return (RMIServer) objref;
     }
 
+    /**
+     * ObjectInputFilter implementation for JMXServiceURL.
+     * Optional filters may be set from the env and System Property.
+     * If not decisive, the default filter is checked.
+     */
+    private static final class JMXURLObjectInputFilter implements ObjectInputFilter {
+
+        // Default filter.  Intentionally does NOT end in "!*", to leave some classes UNDECIDED.
+        private static final String DEFAULT_URL_FILTER_PATTERN =
+            // Permit proxy classes including older style jdk.proxy1.$Proxy0
+            "java.lang.reflect.Proxy;" +
+            "java.rmi.server.RemoteObjectInvocationHandler;" +
+            "jdk.proxy*;" +
+            "java.rmi.server.RemoteStub;" +
+            "java.rmi.server.RemoteObject;" +
+            "javax.management.remote.rmi.RMIServerImpl_Stub;";
+
+        private static final String URL_FILTER_OVERRIDE_PATTERN_NAME = "jmx.remote.rmi.connector.url.filter.pattern";
+
+        private final ObjectInputFilter envFilter;
+
+        private final ObjectInputFilter systemPropertyFilter;
+
+        private final ObjectInputFilter defaultFilter;
+
+        private static ObjectInputFilter filterFromPattern(String pattern) {
+            // createFilter returns null on empty pattern (pattern must not be null)
+            return ObjectInputFilter.Config.createFilter(pattern != null ? pattern : "");
+        }
+
+        public JMXURLObjectInputFilter(Map env) {
+            envFilter = filterFromPattern((String) env.get(URL_FILTER_OVERRIDE_PATTERN_NAME));
+            systemPropertyFilter = filterFromPattern(System.getProperty(URL_FILTER_OVERRIDE_PATTERN_NAME));
+            defaultFilter = ObjectInputFilter.Config.createFilter(DEFAULT_URL_FILTER_PATTERN);
+        }
+
+        @Override
+        public Status checkInput(FilterInfo info) {
+            Status status = Status.UNDECIDED;
+            // Check custom filters, if set.  Try next filter if UNDECIDED.
+            if (envFilter != null) {
+                status = envFilter.checkInput(info);
+                if (status != Status.UNDECIDED) {
+                    return status;
+                }
+            }
+            if (systemPropertyFilter != null) {
+                status = systemPropertyFilter.checkInput(info);
+                if (status != Status.UNDECIDED) {
+                    return status;
+                }
+            }
+            status = defaultFilter.checkInput(info);
+            if (status != Status.UNDECIDED) {
+                return status;
+            }
+            // Finally, permit client socket factory or RMIServer, to avoid requiring an exhaustive filter.
+            // Otherwise, return REJECTED.
+            Class c = info.serialClass();
+            if (RMIClientSocketFactory.class.isAssignableFrom(c)
+                || RMIServer.class.isAssignableFrom(c)) {
+                return Status.ALLOWED;
+            } else {
+                return Status.REJECTED;
+            }
+        }
+    }
+
     private RMIServer findRMIServerJRMP(String base64, Map env)
         throws IOException {
         final byte[] serialized;
@@ -1827,13 +1896,16 @@ private RMIServer findRMIServerJRMP(String base64, Map env)
                 (loader == null) ?
                     new ObjectInputStream(bin) :
                     new ObjectInputStreamWithLoader(bin, loader);
+
+        oin.setObjectInputFilter(new JMXURLObjectInputFilter(env));
+
         final Object stub;
         try {
             stub = oin.readObject();
         } catch (ClassNotFoundException e) {
             throw new MalformedURLException("Class not found: " + e);
         }
-        return (RMIServer)stub;
+        return (RMIServer) stub;
     }
 
     private static final class ObjectInputStreamWithLoader
diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java
index a1f5ece89a28..ff3c5d9d37b4 100644
--- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java
+++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,6 @@
 import java.util.Set;
 import javax.management.InstanceNotFoundException;
 import javax.management.ListenerNotFoundException;
-import javax.management.MBeanPermission;
 import javax.management.MBeanServer;
 import javax.management.MBeanServerDelegate;
 import javax.management.MBeanServerNotification;
diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java
index 89a77b3ddaf8..4cbceee7428f 100644
--- a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java
+++ b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,6 @@
 import java.util.HashMap;
 import java.util.Map;
 import javax.management.remote.JMXAuthenticator;
-import javax.security.auth.AuthPermission;
 import javax.security.auth.Subject;
 import javax.security.auth.callback.*;
 import javax.security.auth.login.AppConfigurationEntry;
diff --git a/src/java.management/share/classes/javax/management/MBeanServer.java b/src/java.management/share/classes/javax/management/MBeanServer.java
index 036fea93eb70..aba0f77d94f1 100644
--- a/src/java.management/share/classes/javax/management/MBeanServer.java
+++ b/src/java.management/share/classes/javax/management/MBeanServer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -222,8 +222,6 @@ public ObjectInstance getObjectInstance(ObjectName name)
      * Returns the number of MBeans registered in the MBean server.
      *
      * @return the number of registered MBeans, wrapped in an Integer.
-     * If the caller's permissions are restricted, this number may
-     * be greater than the number of MBeans the caller can access.
      */
     public Integer getMBeanCount();
 
diff --git a/src/java.management/share/classes/sun/management/Util.java b/src/java.management/share/classes/sun/management/Util.java
index 6ae270b05696..ff9e0dbf6992 100644
--- a/src/java.management/share/classes/sun/management/Util.java
+++ b/src/java.management/share/classes/sun/management/Util.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 
 package sun.management;
 
-import java.lang.management.ManagementPermission;
 import java.util.List;
 import javax.management.ObjectName;
 import javax.management.MalformedObjectNameException;
diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java
index 672f9c5ead41..31ce7de0468a 100644
--- a/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java
+++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -940,20 +941,29 @@ private static final boolean isServerInitiatedStream(int streamid) {
      */
     void processFrame(Http2Frame frame) throws IOException {
         Log.logFrames(frame, "IN");
-        int streamid = frame.streamid();
-        if (frame instanceof MalformedFrame) {
-            Log.logError(((MalformedFrame) frame).getMessage());
-            if (streamid == 0) {
-                framesDecoder.close("Malformed frame on stream 0");
-                protocolError(((MalformedFrame) frame).getErrorCode(),
-                        ((MalformedFrame) frame).getMessage());
+        if (frame instanceof MalformedFrame malformedFrame) {
+            Log.logError(malformedFrame.getMessage());
+            if (malformedFrame.isConnectionError()) {
+                protocolError(malformedFrame.getErrorCode(),
+                        malformedFrame.getMessage());
             } else {
-                if (debug.on())
-                    debug.log(() -> "Reset stream: " + ((MalformedFrame) frame).getMessage());
-                resetStream(streamid, ((MalformedFrame) frame).getErrorCode());
+                int errorStream = malformedFrame.streamid();
+                Stream stream = getStream(errorStream);
+                if (stream != null && !stream.isTerminalState()) {
+                    if (debug.on())
+                        debug.log(() -> "Reset stream " + errorStream + ": "
+                                + malformedFrame.getMessage());
+                    stream.onProtocolError(new ProtocolException(
+                            malformedFrame.getMessage()),
+                            malformedFrame.getErrorCode());
+                } else if (debug.on()) {
+                    debug.log(() -> "Ignoring malformed frame on idle or closed stream "
+                            + errorStream + ": " + malformedFrame.getMessage());
+                }
             }
             return;
         }
+        int streamid = frame.streamid();
         if (streamid == 0) {
             handleConnectionFrame(frame);
         } else {
diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java b/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java
index e66f2dfd4f1b..a12e9d25bba2 100644
--- a/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java
+++ b/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1875,6 +1876,33 @@ boolean isCanceled() {
         return errorRef.get() != null;
     }
 
+    /**
+     * Returns true if in closed/terminal state as defined by RFC 9113 (5.1).
+     * @return true if in closed/terminal state as defined by RFC 9113 (5.1).
+     */
+    boolean isTerminalState() {
+        // Closed locally or reset.
+        if (closed || streamState != 0) {
+            return true;
+        }
+        // Server finished sending.
+        if (!(endStreamSeen || endStreamReceived())) {
+            return false;
+        }
+        // Client finished sending. Never sends for PushedStream.
+        if (this instanceof PushedStream || requestBodyCF.isDone()) {
+            return true;
+        }
+        // Client finished sending for first request on an
+        // upgraded connection.
+        stateLock.lock();
+        try {
+            return requestSent;
+        } finally {
+            stateLock.unlock();
+        }
+    }
+
     /**
      * Returns the cause for which this exchange was canceled, if available.
      * @return the cause for which this exchange was canceled, if available.
diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/frame/FramesDecoder.java b/src/java.net.http/share/classes/jdk/internal/net/http/frame/FramesDecoder.java
index da05f6392c1f..0656b7f81c8d 100644
--- a/src/java.net.http/share/classes/jdk/internal/net/http/frame/FramesDecoder.java
+++ b/src/java.net.http/share/classes/jdk/internal/net/http/frame/FramesDecoder.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,10 +66,6 @@ public interface FrameProcessor {
     private final ArrayDeque tailBuffers = new ArrayDeque<>();
     private int tailSize = 0;
 
-    private boolean slicedToDataFrame = false;
-
-    private final List prepareToRelease = new ArrayList<>();
-
     // if true  - Frame Header was parsed (9 bytes consumed) and subsequent fields have meaning
     // otherwise - stopped at frames boundary
     private boolean frameHeaderParsed = false;
@@ -155,7 +152,6 @@ public void decode(ByteBuffer inBoundBuffer) throws IOException {
         while ((frame = nextFrame()) != null) {
             if (debug.on()) debug.log("Got frame: %s", frame);
             frameProcessor.processFrame(frame);
-            frameProcessed();
         }
     }
 
@@ -202,10 +198,6 @@ private Http2Frame nextFrame() throws IOException {
         }
     }
 
-    private void frameProcessed() {
-        prepareToRelease.clear();
-    }
-
     private void parseFrameHeader() throws IOException {
         int x = getInt();
         this.frameLength = (x >>> 8) & 0x00ffffff;
@@ -219,10 +211,6 @@ private void parseFrameHeader() throws IOException {
     // move next buffer from tailBuffers to currentBuffer if required
     private void nextBuffer() {
         if (!currentBuffer.hasRemaining()) {
-            if (!slicedToDataFrame) {
-                prepareToRelease.add(currentBuffer);
-            }
-            slicedToDataFrame = false;
             currentBuffer = tailBuffers.poll();
             if (currentBuffer != null) {
                 tailSize -= currentBuffer.remaining();
@@ -280,17 +268,11 @@ private List getBuffers(boolean isDataFrame, int bytecount) {
         while (bytecount > 0) {
             int remaining = currentBuffer.remaining();
             int extract = Math.min(remaining, bytecount);
-            ByteBuffer extractedBuf;
+            ByteBuffer extractedBuf = Utils.sliceWithLimitedCapacity(currentBuffer, extract);
             if (isDataFrame) {
-                extractedBuf = Utils.sliceWithLimitedCapacity(currentBuffer, extract)
-                                    .asReadOnlyBuffer();
-                slicedToDataFrame = true;
-            } else {
-                // Header frames here
-                // HPACK decoding should performed under lock and immediately after frame decoding.
-                // in that case it is safe to release original buffer,
-                // because of sliced buffer has a very short life
-                extractedBuf = Utils.sliceWithLimitedCapacity(currentBuffer, extract);
+                // HttpResponse.BodySubscriber implementation note indicates that
+                // "data containing the response body is immutable".
+                extractedBuf = extractedBuf.asReadOnlyBuffer();
             }
             res.add(extractedBuf);
             bytecount -= extract;
@@ -562,21 +544,30 @@ private Http2Frame parseContinuationFrame(int frameLength, int streamid, int fla
     }
 
     private Http2Frame parseAltSvcFrame(int frameLength, int frameStreamid, int frameFlags) {
+        if (frameLength < 2) {
+            return new MalformedFrame(ErrorFrame.FRAME_SIZE_ERROR,
+                    "AltSvcFrame length is " + frameLength + ", should be >= 2");
+        }
         var len = getShort();
+        if (len > frameLength - 2) {
+            return new MalformedFrame(ErrorFrame.FRAME_SIZE_ERROR,
+                    "AltSvcFrame origin length " + len + " > payload");
+        }
         byte[] origin;
         Optional originUri = Optional.empty();
         if (len > 0) {
             origin = getBytes(len);
             if (!isUSAscii(origin)) {
-                return new MalformedFrame(ErrorFrame.PROTOCOL_ERROR, frameStreamid,
-                        "illegal character in AltSvcFrame");
+                Log.logTrace("Ignoring AltSvcFrame with illegal character in origin");
+                skipBytes(frameLength - 2 - len);
+                return null;
             }
             originUri = Optional.of(new String(origin, StandardCharsets.US_ASCII));
         }
         byte[] altbytes = getBytes(frameLength - 2 - len);
         if (!isUSAscii(altbytes)) {
-            return new MalformedFrame(ErrorFrame.PROTOCOL_ERROR, frameStreamid,
-                    "illegal character in AltSvcFrame");
+            Log.logTrace("Ignoring AltSvcFrame with illegal character in value");
+            return null;
         }
         String altSvc = new String(altbytes, StandardCharsets.US_ASCII);
         return new AltSvcFrame(frameStreamid, 0, originUri, altSvc);
diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/frame/MalformedFrame.java b/src/java.net.http/share/classes/jdk/internal/net/http/frame/MalformedFrame.java
index 74894970fcba..37577a2ccc27 100644
--- a/src/java.net.http/share/classes/jdk/internal/net/http/frame/MalformedFrame.java
+++ b/src/java.net.http/share/classes/jdk/internal/net/http/frame/MalformedFrame.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,10 +28,10 @@
 
 public class MalformedFrame extends Http2Frame {
 
+    // if streamid() == 0 means Connection Error; RFC 7540 5.4.1
+    // if streamid() != 0 means Stream Error; RFC 7540 5.4.2
+
     private int errorCode;
-    // if errorStream == 0 means Connection Error; RFC 7540 5.4.1
-    // if errorStream != 0 means Stream Error; RFC 7540 5.4.2
-    private int errorStream;
     private String msg;
 
     /**
@@ -49,16 +50,15 @@ public MalformedFrame(int errorCode, String msg) {
      * @param msg - internal debug message
      */
     public MalformedFrame(int errorCode, int errorStream, String msg) {
-        super(0, 0);
+        super(errorStream, 0);
         this.errorCode = errorCode;
-        this.errorStream = errorStream;
         this.msg = msg;
     }
 
     @Override
     public String toString() {
         return super.toString() + " MalformedFrame, Error: " + ErrorFrame.stringForCode(errorCode)
-                + " streamid: " + streamid + " reason: " + msg;
+                + " reason: " + msg;
     }
 
     public int getErrorCode() {
@@ -68,4 +68,8 @@ public int getErrorCode() {
     public String getMessage() {
         return msg;
     }
+
+    public boolean isConnectionError() {
+        return streamid() == 0;
+    }
 }
diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbApReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbApReq.java
index 7d32bf9a9f64..ffb6c7b42ce8 100644
--- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbApReq.java
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbApReq.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,9 +37,15 @@
 import java.net.InetAddress;
 import sun.security.util.*;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
 import sun.security.krb5.internal.rcache.AuthTimeWithHash;
 
 import static sun.security.krb5.internal.Krb5.DEBUG;
@@ -341,12 +347,52 @@ private void authenticate(Krb5AcceptCredential cred, InetAddress initiator)
             }
         }
 
-        // XXX check for repeated authenticator
-        // if found
-        //    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
-        // else
-        //    save authenticator to check for later
+        if (DEBUG != null) {
+            DEBUG.println(">>> KrbApReq: Received ticket options " + enc_ticketPart.flags);
+        }
 
+        if (!enc_ticketPart.flags.get(Krb5.TKT_OPTS_TRANSIT_POLICY_CHECKED)
+                && enc_ticketPart.transited.contents.length != 0) {
+            // System property to control transited policy check:
+            //
+            // If true, compare transited field inside the service ticket to
+            // local settings, and fail with KRB_AP_PATH_NOT_ACCEPTED if there
+            // is no match. Otherwise, ignore the check.
+            //
+            // Default value is `true`. Set to `false` to revert to old behavior.
+            String propValue = SecurityProperties.getOverridableProperty(
+                    "sun.security.krb5.acceptor.checkTransitedPolicy");
+            if (propValue != null) {
+                propValue = propValue.toLowerCase(Locale.ROOT);
+            }
+            boolean checkTransitedPolicy = switch (propValue) {
+                case null -> true;
+                case "true" -> true;
+                case "false" -> false;
+                default -> throw new IllegalArgumentException(
+                        "Invalid property value: " + propValue);
+            };
+            if (checkTransitedPolicy) {
+                if (enc_ticketPart.transited.trType == Krb5.DOMAIN_X500_COMPRESS) {
+                    String transited = new String(
+                            enc_ticketPart.transited.contents, StandardCharsets.UTF_8);
+                    String cRealm = enc_ticketPart.cname.getRealmAsString();
+                    String sRealm = apReqMessg.ticket.sname.getRealmAsString();
+                    String[] allowed = Realm.getRealmsList(cRealm, sRealm);
+                    if (DEBUG != null) {
+                        DEBUG.println(">>> KrbApReq: transited realm is " + transited
+                                + ", allowed is " + Arrays.toString(allowed)
+                                + ". Checking from " + cRealm + " to " + sRealm);
+                    }
+                    List inTicket = parseTransited(transited);
+                    if (!Set.of(allowed).containsAll(inTicket)) {
+                        throw new KrbApErrException(Krb5.KRB_AP_PATH_NOT_ACCEPTED);
+                    }
+                } else {
+                    throw new KrbApErrException(Krb5.KRB_AP_PATH_NOT_ACCEPTED);
+                }
+            }
+        }
         KerberosTime now = KerberosTime.now();
 
         if ((enc_ticketPart.starttime != null &&
@@ -380,6 +426,29 @@ private void authenticate(Krb5AcceptCredential cred, InetAddress initiator)
         }
     }
 
+    // https://datatracker.ietf.org/doc/html/rfc4120#section-3.3.3.2
+    // Only support "," and "." as special characters.
+    private static List parseTransited(String input)
+            throws KrbApErrException {
+        ArrayList output = new ArrayList<>();
+        String last = null;
+        for (String s : input.split(",", -1)) {
+            if (s == null || s.isEmpty() || s.contains("/")
+                    || s.contains("\\") || s.contains(" ")) {
+                throw new KrbApErrException(Krb5.KRB_AP_PATH_NOT_ACCEPTED);
+            }
+            if (s.endsWith(".")) {
+                if (last == null) {
+                    throw new KrbApErrException(Krb5.KRB_AP_PATH_NOT_ACCEPTED);
+                }
+                s = s + last;
+            }
+            output.add(s);
+            last = s;
+        }
+        return output;
+    }
+
     /**
      * Returns the credentials that are contained in the ticket that
      * is part of this AP-REQ.
diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Krb5.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Krb5.java
index 641b860c364a..68120087281e 100644
--- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Krb5.java
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Krb5.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -71,6 +71,7 @@ public class Krb5 {
     public static final int TKT_OPTS_INITIAL      = 9;
     public static final int TKT_OPTS_PRE_AUTHENT  = 10;
     public static final int TKT_OPTS_HW_AUTHENT   = 11;
+    public static final int TKT_OPTS_TRANSIT_POLICY_CHECKED   = 12;
     public static final int TKT_OPTS_DELEGATE     = 13;
     public static final int TKT_OPTS_ENC_PA_REP   = 15;
     public static final int TKT_OPTS_MAX          = 31;
diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/TicketFlags.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/TicketFlags.java
index cc1951f370c2..294a4e69c9d0 100644
--- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/TicketFlags.java
+++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/TicketFlags.java
@@ -52,6 +52,8 @@
  *                   initial(9),
  *                   pre-authent(10),
  *                   hw-authent(11),
+ *                   transited-policy-checked(12),
+ *                   ok-as-delegate(13)
  *                   enc-pa-rep(15)
  *                  }
  */
@@ -180,9 +182,18 @@ public String toString() {
                 case 11:
                     sb.append("HW-AUTHENT;");
                     break;
+                case 12:
+                    sb.append("TRANSIT-POLICY-CHECKED;");
+                    break;
+                case 13:
+                    sb.append("OK-AS-DELEGATE;");
+                    break;
                 case 15:
                     sb.append("ENC-PA-REP;");
                     break;
+                default:
+                    sb.append(i).append(";");
+                    break;
                 }
             }
         }
diff --git a/src/java.security.jgss/windows/native/libsspi_bridge/sspi.cpp b/src/java.security.jgss/windows/native/libsspi_bridge/sspi.cpp
index dd84ab3057ba..b9345353480b 100644
--- a/src/java.security.jgss/windows/native/libsspi_bridge/sspi.cpp
+++ b/src/java.security.jgss/windows/native/libsspi_bridge/sspi.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -312,6 +312,71 @@ get_full_name(WCHAR* input)
     return fullname;
 }
 
+// Convert input channel binding to the windows cbt
+static SECURITY_STATUS
+convert_chan_bindings(gss_const_channel_bindings_t input_cb, PBYTE* cbBuffer, size_t* cbBufferLength) {
+
+    size_t length = sizeof(SEC_CHANNEL_BINDINGS);
+    if ((input_cb->initiator_address.length != 0 && input_cb->initiator_address.value == NULL) ||
+        input_cb->initiator_address.length > ULONG_MAX - length) {
+        return SEC_E_INVALID_TOKEN;
+    }
+    length += input_cb->initiator_address.length;
+    if ((input_cb->acceptor_address.length != 0 && input_cb->acceptor_address.value == NULL) ||
+        input_cb->acceptor_address.length > ULONG_MAX - length) {
+        return SEC_E_INVALID_TOKEN;
+    }
+    length += input_cb->acceptor_address.length;
+    if ((input_cb->application_data.length != 0 && input_cb->application_data.value == NULL) ||
+        input_cb->application_data.length > ULONG_MAX - length) {
+        return SEC_E_INVALID_TOKEN;
+    }
+    length += input_cb->application_data.length;
+
+    *cbBuffer = (PBYTE)calloc(1, length);
+    if (*cbBuffer == NULL) {
+        return SEC_E_INSUFFICIENT_MEMORY;
+    }
+
+    PBYTE data = *cbBuffer + sizeof(SEC_CHANNEL_BINDINGS);
+    PSEC_CHANNEL_BINDINGS windowsCbt = (PSEC_CHANNEL_BINDINGS)*cbBuffer;
+
+    windowsCbt->dwInitiatorAddrType = input_cb->initiator_addrtype;
+    if (input_cb->initiator_address.length != 0) {
+        windowsCbt->cbInitiatorLength =
+                (ULONG)input_cb->initiator_address.length;
+        windowsCbt->dwInitiatorOffset = (ULONG)(data - *cbBuffer);
+        memcpy(data,
+                input_cb->initiator_address.value,
+                input_cb->initiator_address.length);
+        data += input_cb->initiator_address.length;
+    }
+
+    windowsCbt->dwAcceptorAddrType = input_cb->acceptor_addrtype;
+    if (input_cb->acceptor_address.length != 0) {
+        windowsCbt->cbAcceptorLength =
+                (ULONG)input_cb->acceptor_address.length;
+        windowsCbt->dwAcceptorOffset = (ULONG)(data - *cbBuffer);
+        memcpy(data,
+                input_cb->acceptor_address.value,
+                input_cb->acceptor_address.length);
+        data += input_cb->acceptor_address.length;
+    }
+
+    if (input_cb->application_data.length != 0) {
+        windowsCbt->cbApplicationDataLength =
+                (ULONG)input_cb->application_data.length;
+        windowsCbt->dwApplicationDataOffset = (ULONG)(data - *cbBuffer);
+        memcpy(data,
+                input_cb->application_data.value,
+                input_cb->application_data.length);
+    }
+
+    *cbBufferLength = length;
+
+    return SEC_E_OK;
+}
+
 /* End support section */
 
 /* This section holds GSS-API exported functions */
@@ -868,7 +933,10 @@ gss_init_sec_context(OM_uint32 *minor_status,
     SECURITY_STATUS ss;
     TimeStamp lifeTime;
     SecBufferDesc inBuffDesc;
-    SecBuffer inSecBuff;
+    SecBuffer inSecBuff[2];
+    PBYTE cbBuffer = NULL;
+    size_t cbBufferLength = 0;
+    size_t inSecBuffCount = 0;
     SecBufferDesc outBuffDesc;
     SecBuffer outSecBuff;
     BOOLEAN isSPNEGO = is_same_oid(mech_type, &SPNEGO_OID);
@@ -918,13 +986,10 @@ gss_init_sec_context(OM_uint32 *minor_status,
     outSecBuff.BufferType = SECBUFFER_TOKEN;
 
     if (!firstTime) {
-        inBuffDesc.ulVersion = SECBUFFER_VERSION;
-        inBuffDesc.cBuffers = 1;
-        inBuffDesc.pBuffers = &inSecBuff;
-
-        inSecBuff.BufferType = SECBUFFER_TOKEN;
-        inSecBuff.cbBuffer = (ULONG)input_token->length;
-        inSecBuff.pvBuffer = input_token->value;
+        inSecBuff[0].BufferType = SECBUFFER_TOKEN;
+        inSecBuff[0].cbBuffer = (ULONG)input_token->length;
+        inSecBuff[0].pvBuffer = input_token->value;
+        inSecBuffCount = 1;
     } else if (!pc->phCred) {
         if (isSPNEGO && initiator_cred_handle
                 && initiator_cred_handle->phCredS) {
@@ -966,6 +1031,22 @@ gss_init_sec_context(OM_uint32 *minor_status,
             pc->isLocalCred = TRUE;
         }
     }
+
+    if (input_chan_bindings != GSS_C_NO_CHANNEL_BINDINGS) {
+        ss = convert_chan_bindings(input_chan_bindings, &cbBuffer, &cbBufferLength);
+        if (!SEC_SUCCESS(ss)) {
+            goto err;
+        }
+        inSecBuff[inSecBuffCount].BufferType = SECBUFFER_CHANNEL_BINDINGS;
+        inSecBuff[inSecBuffCount].cbBuffer = (ULONG)cbBufferLength;
+        inSecBuff[inSecBuffCount].pvBuffer = cbBuffer;
+        inSecBuffCount++;
+    }
+    if (inSecBuffCount) {
+        inBuffDesc.ulVersion = SECBUFFER_VERSION;
+        inBuffDesc.cBuffers = (ULONG)inSecBuffCount;
+        inBuffDesc.pBuffers = inSecBuff;
+    }
     ss = InitializeSecurityContext(
             pc->phCred,
             firstTime ? NULL : &pc->hCtxt,
@@ -973,13 +1054,18 @@ gss_init_sec_context(OM_uint32 *minor_status,
             flag,
             0,
             SECURITY_NATIVE_DREP,
-            firstTime ? NULL : &inBuffDesc,
+            inSecBuffCount ? &inBuffDesc : NULL,
             0,
             &pc->hCtxt,
             &outBuffDesc,
             &outFlag,
             &lifeTime);
 
+    if (cbBuffer != NULL) {
+        free(cbBuffer);
+        cbBuffer = NULL;
+    }
+
     if (!SEC_SUCCESS(ss)) {
         PP("InitializeSecurityContext failed");
         goto err;
diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Const.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Const.java
index c6b97db142e5..7ca7433d77b7 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Const.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Const.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -26,15 +26,15 @@
  * Constants for the project, mostly defined in the JVM specification.
  *
  * @since 6.0 (intended to replace the Constants interface)
- * @LastModified: Sept 2025
+ * @LastModified: Nov 2026
  */
 public final class Const {
 
     /**
      * Java class file format Magic number: {@value}.
      *
-     * @see  The ClassFile Structure
-     *      in The Java Virtual Machine Specification
+     * @see  The ClassFile Structure in The Java Virtual Machine
+     *      Specification
      */
     public static final int JVM_CLASSFILE_MAGIC = 0xCAFEBABE;
 
@@ -320,6 +320,38 @@ public final class Const {
      */
     public static final short MINOR_24 = 0;
 
+    /**
+     * Minor version number of class files for Java 25: {@value}.
+     *
+     * @see #MAJOR_25
+     * @since 6.11.0
+     */
+    public static final short MINOR_25 = 0;
+
+    /**
+     * Minor version number of class files for Java 26: {@value}.
+     *
+     * @see #MAJOR_26
+     * @since 6.12.0
+     */
+    public static final short MINOR_26 = 0;
+
+    /**
+     * Minor version number of class files for Java 27: {@value}.
+     *
+     * @see #MAJOR_27
+     * @since 6.13.0
+     */
+    public static final short MINOR_27 = 0;
+
+    /**
+     * Minor version number of class files for Java 28: {@value}.
+     *
+     * @see #MAJOR_28
+     * @since 6.13.0
+     */
+    public static final short MINOR_28 = 0;
+
     /**
      * Major version number of class files for Java 14: {@value}.
      *
@@ -408,6 +440,38 @@ public final class Const {
      */
     public static final short MAJOR_24 = 68;
 
+    /**
+     * Major version number of class files for Java 25: {@value}.
+     *
+     * @see #MINOR_25
+     * @since 6.11.0
+     */
+    public static final short MAJOR_25 = 69;
+
+    /**
+     * Major version number of class files for Java 26: {@value}.
+     *
+     * @see #MINOR_26
+     * @since 6.12.0
+     */
+    public static final short MAJOR_26 = 70;
+
+    /**
+     * Major version number of class files for Java 27: {@value}.
+     *
+     * @see #MINOR_27
+     * @since 6.13.0
+     */
+    public static final short MAJOR_27 = 71;
+
+    /**
+     * Major version number of class files for Java 27: {@value}.
+     *
+     * @see #MINOR_28
+     * @since 6.13.0
+     */
+    public static final short MAJOR_28 = 72;
+
     /**
      * Default major version number. Class file is for Java 1.1: {@value}.
      *
@@ -435,14 +499,14 @@ public final class Const {
     /**
      * One of the access flags for fields, methods, or classes: {@value}.
      *
-     * @see  Flag definitions for
-     *      Classes in the Java Virtual Machine Specification (Java SE 9 Edition).
-     * @see  Flag definitions for Fields
-     *      in the Java Virtual Machine Specification (Java SE 9 Edition).
-     * @see  Flag definitions for Methods
-     *      in the Java Virtual Machine Specification (Java SE 9 Edition).
-     * @see  Flag
-     *      definitions for Inner Classes in the Java Virtual Machine Specification (Java SE 9 Edition).
+     * @see  Flag definitions for Classes in the Java Virtual Machine
+     *      Specification (Java SE 9 Edition).
+     * @see  Flag definitions for Fields in the Java Virtual Machine
+     *      Specification (Java SE 9 Edition).
+     * @see  Flag definitions for Methods in the Java Virtual Machine
+     *      Specification (Java SE 9 Edition).
+     * @see  Flag definitions for Inner Classes in the Java
+     *      Virtual Machine Specification (Java SE 9 Edition).
      */
     public static final short ACC_PUBLIC = 0x0001;
 
@@ -585,8 +649,8 @@ public final class Const {
      * @see #ACC_PUBLIC
      */
     public static final short ACC_ENUM = 0x4000;
-
     // Applies to classes compiled by new compilers only
+
     /**
      * One of the access flags for MethodParameter or Module attributes: {@value}.
      *
@@ -617,135 +681,125 @@ public final class Const {
      * @since 6.4.0
      */
     public static final int MAX_ACC_FLAG_I = 0x8000; // ACC_MODULE is negative as a short
-
     // Note that do to overloading:
     // 'synchronized' is for methods, might be 'open' (if Module), 'super' (if class), or 'transitive' (if Module).
     // 'volatile' is for fields, might be 'bridge' (if method) or 'static_phase' (if Module)
     // 'transient' is for fields, might be 'varargs' (if method)
     // 'module' is for classes, might be 'mandated' (if Module or MethodParameters)
+
     /**
      * The names of the access flags.
      */
-    private static final String[] ACCESS_NAMES = {"public", "private", "protected", "static", "final", "synchronized", "volatile", "transient", "native",
-        "interface", "abstract", "strictfp", "synthetic", "annotation", "enum", "module"};
+    private static final String[] ACCESS_NAMES = { "public", "private", "protected", "static", "final", "synchronized", "volatile", "transient", "native",
+            "interface", "abstract", "strictfp", "synthetic", "annotation", "enum", "module" };
 
-    /** @since 6.0 */
+    /**
+     * The length of the ACCESS_NAMES array.
+     *
+     * @since 6.0
+     */
     public static final int ACCESS_NAMES_LENGTH = ACCESS_NAMES.length;
 
     /**
      * Marks a constant pool entry as type UTF-8: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Utf8 = 1;
-
     /*
-     * The description of the constant pool is at: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4
-     * References below are to the individual sections
+     * The description of the constant pool is at: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4 References below are to the
+     * individual sections
      */
 
     /**
      * Marks a constant pool entry as type Integer: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Integer = 3;
 
     /**
      * Marks a constant pool entry as type Float: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Float = 4;
 
     /**
      * Marks a constant pool entry as type Long: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Long = 5;
 
     /**
      * Marks a constant pool entry as type Double: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Double = 6;
 
     /**
      * Marks a constant pool entry as a Class: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Class = 7;
 
     /**
      * Marks a constant pool entry as a Field Reference: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Fieldref = 9;
 
     /**
      * Marks a constant pool entry as type String: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_String = 8;
 
     /**
      * Marks a constant pool entry as a Method Reference: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_Methodref = 10;
 
     /**
      * Marks a constant pool entry as an Interface Method Reference: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_InterfaceMethodref = 11;
 
     /**
      * Marks a constant pool entry as a name and type: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_NameAndType = 12;
 
     /**
      * Marks a constant pool entry as a Method Handle: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_MethodHandle = 15;
 
     /**
      * Marks a constant pool entry as a Method Type: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine Specification
      */
     public static final byte CONSTANT_MethodType = 16;
 
     /**
      * Marks a constant pool entry as dynamically computed: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine
+     *      Specification
      * @since 6.3
      */
     public static final byte CONSTANT_Dynamic = 17;
@@ -753,16 +807,16 @@ public final class Const {
     /**
      * Marks a constant pool entry as an Invoke Dynamic: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine
+     *      Specification
      */
     public static final byte CONSTANT_InvokeDynamic = 18;
 
     /**
      * Marks a constant pool entry as a Module Reference: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine
+     *      Specification
      * @since 6.1
      */
     public static final byte CONSTANT_Module = 19;
@@ -770,8 +824,8 @@ public final class Const {
     /**
      * Marks a constant pool entry as a Package Reference: {@value}.
      *
-     * @see  The Constant Pool in The
-     *      Java Virtual Machine Specification
+     * @see  The Constant Pool in The Java Virtual Machine
+     *      Specification
      * @since 6.1
      */
     public static final byte CONSTANT_Package = 20;
@@ -779,2017 +833,1984 @@ public final class Const {
     /**
      * The names of the types of entries in a constant pool. Use getConstantName instead
      */
-    private static final String[] CONSTANT_NAMES = {"", "CONSTANT_Utf8", "", "CONSTANT_Integer", "CONSTANT_Float", "CONSTANT_Long", "CONSTANT_Double",
-        "CONSTANT_Class", "CONSTANT_String", "CONSTANT_Fieldref", "CONSTANT_Methodref", "CONSTANT_InterfaceMethodref", "CONSTANT_NameAndType", "", "",
-        "CONSTANT_MethodHandle", "CONSTANT_MethodType", "CONSTANT_Dynamic", "CONSTANT_InvokeDynamic", "CONSTANT_Module", "CONSTANT_Package"};
+    private static final String[] CONSTANT_NAMES = { "", "CONSTANT_Utf8", "", "CONSTANT_Integer", "CONSTANT_Float", "CONSTANT_Long", "CONSTANT_Double",
+            "CONSTANT_Class", "CONSTANT_String", "CONSTANT_Fieldref", "CONSTANT_Methodref", "CONSTANT_InterfaceMethodref", "CONSTANT_NameAndType", "", "",
+            "CONSTANT_MethodHandle", "CONSTANT_MethodType", "CONSTANT_Dynamic", "CONSTANT_InvokeDynamic", "CONSTANT_Module", "CONSTANT_Package" };
 
     /**
-     * The name of the static initializer, also called "class initialization method" or "interface
-     * initialization method". This is {@value}.
+     * The name of the static initializer, also called "class initialization method" or "interface initialization method". This is {@value}.
      */
     public static final String STATIC_INITIALIZER_NAME = "";
 
     /**
-     * The name of every constructor method in a class, also called "instance initialization method". This is
-     * {@value}.
+     * The name of every constructor method in a class, also called "instance initialization method". This is {@value}.
      */
     public static final String CONSTRUCTOR_NAME = "";
 
     /**
      * The names of the interfaces implemented by arrays.
      */
-    private static final String[] INTERFACES_IMPLEMENTED_BY_ARRAYS = {"java.lang.Cloneable", "java.io.Serializable"};
+    private static final String[] INTERFACES_IMPLEMENTED_BY_ARRAYS = { "java.lang.Cloneable", "java.io.Serializable" };
 
     /**
      * Maximum Constant Pool entries: {@value}. One of the limitations of the Java Virtual Machine.
      *
-     * @see  The Java Virtual
-     *      Machine Specification, Java SE 8 Edition, page 330, chapter 4.11.
+     * @see  The Java Virtual Machine Specification, Java SE 8 Edition,
+     *      page 330, chapter 4.11.
      */
     public static final int MAX_CP_ENTRIES = 65535;
 
     /**
-     * Maximum code size (plus one; the code size must be LESS than this): {@value}.
-     * 

- * One of the limitations of the Java Virtual Machine. Note vmspec2 page 152 ("Limitations") says: - *

- *
"The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes of the indices in the exception_table of the Code
-     * attribute (4.7.3), in the LineNumberTable attribute (4.7.8), and in the LocalVariableTable attribute (4.7.9)." However this should be taken as an
-     * upper limit rather than the defined maximum. On page 134 (4.8.1 Static Constants) of the same spec, it says: "The value of the code_length item must be
-     * less than 65536."
+ * Maximum code size plus one; the code size must be LESS than {@value}. *

- * The entry in the Limitations section has been removed from later versions of the specification; it is not present in the Java SE 8 edition. + * This limitation is from The Java Virtual Machine Specification, Java + * SE 8 Edition, 4.7.3 The Code Attribute.: *

* - * @see The Java Virtual Machine Specification, Java SE 8 - * Edition, page 104, chapter 4.7. + *
+     * code_length
+     *
+     *  The value of the code_length item gives the number of bytes in the code array for this method.
+     *
+     *  The value of code_length must be greater than zero (as the code array must not be empty) and less than 65536"
+     * 
+ * + * @see The Java Virtual Machine Specification, Java SE 8 Edition, + * 4.7.3 The Code Attribute. */ public static final int MAX_CODE_SIZE = 65536; // bytes /** * The maximum number of dimensions in an array: {@value}. One of the limitations of the Java Virtual Machine. * - * @see Field Descriptors in - * The Java Virtual Machine Specification + * @see Field Descriptors in The Java Virtual Machine + * Specification */ public static final int MAX_ARRAY_DIMENSIONS = 255; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short NOP = 0; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ACONST_NULL = 1; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_M1 = 2; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_0 = 3; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_1 = 4; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_2 = 5; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_3 = 6; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_4 = 7; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ICONST_5 = 8; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LCONST_0 = 9; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LCONST_1 = 10; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FCONST_0 = 11; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FCONST_1 = 12; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FCONST_2 = 13; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DCONST_0 = 14; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DCONST_1 = 15; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short BIPUSH = 16; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short SIPUSH = 17; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LDC = 18; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LDC_W = 19; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LDC2_W = 20; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ILOAD = 21; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LLOAD = 22; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FLOAD = 23; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DLOAD = 24; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ALOAD = 25; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ILOAD_0 = 26; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ILOAD_1 = 27; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ILOAD_2 = 28; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ILOAD_3 = 29; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LLOAD_0 = 30; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LLOAD_1 = 31; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LLOAD_2 = 32; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LLOAD_3 = 33; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FLOAD_0 = 34; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FLOAD_1 = 35; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FLOAD_2 = 36; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FLOAD_3 = 37; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DLOAD_0 = 38; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DLOAD_1 = 39; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DLOAD_2 = 40; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DLOAD_3 = 41; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ALOAD_0 = 42; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ALOAD_1 = 43; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ALOAD_2 = 44; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ALOAD_3 = 45; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IALOAD = 46; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LALOAD = 47; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FALOAD = 48; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DALOAD = 49; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short AALOAD = 50; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short BALOAD = 51; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short CALOAD = 52; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short SALOAD = 53; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISTORE = 54; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSTORE = 55; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSTORE = 56; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSTORE = 57; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ASTORE = 58; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISTORE_0 = 59; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISTORE_1 = 60; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISTORE_2 = 61; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISTORE_3 = 62; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSTORE_0 = 63; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSTORE_1 = 64; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSTORE_2 = 65; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSTORE_3 = 66; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSTORE_0 = 67; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSTORE_1 = 68; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSTORE_2 = 69; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSTORE_3 = 70; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSTORE_0 = 71; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSTORE_1 = 72; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSTORE_2 = 73; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSTORE_3 = 74; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ASTORE_0 = 75; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ASTORE_1 = 76; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ASTORE_2 = 77; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ASTORE_3 = 78; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IASTORE = 79; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LASTORE = 80; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FASTORE = 81; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DASTORE = 82; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short AASTORE = 83; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short BASTORE = 84; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short CASTORE = 85; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short SASTORE = 86; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short POP = 87; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short POP2 = 88; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP = 89; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP_X1 = 90; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP_X2 = 91; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP2 = 92; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP2_X1 = 93; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DUP2_X2 = 94; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short SWAP = 95; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IADD = 96; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LADD = 97; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FADD = 98; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DADD = 99; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISUB = 100; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSUB = 101; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FSUB = 102; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DSUB = 103; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IMUL = 104; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LMUL = 105; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FMUL = 106; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DMUL = 107; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IDIV = 108; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LDIV = 109; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FDIV = 110; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DDIV = 111; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IREM = 112; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LREM = 113; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FREM = 114; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DREM = 115; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INEG = 116; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LNEG = 117; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FNEG = 118; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DNEG = 119; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISHL = 120; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSHL = 121; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ISHR = 122; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LSHR = 123; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IUSHR = 124; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LUSHR = 125; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IAND = 126; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LAND = 127; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IOR = 128; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LOR = 129; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IXOR = 130; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LXOR = 131; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IINC = 132; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2L = 133; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2F = 134; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2D = 135; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short L2I = 136; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short L2F = 137; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short L2D = 138; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short F2I = 139; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short F2L = 140; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short F2D = 141; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short D2I = 142; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short D2L = 143; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short D2F = 144; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2B = 145; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine Specification */ public static final short INT2BYTE = 145; // Old notation /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2C = 146; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine Specification */ public static final short INT2CHAR = 146; // Old notation /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short I2S = 147; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine Specification */ public static final short INT2SHORT = 147; // Old notation /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LCMP = 148; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FCMPL = 149; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FCMPG = 150; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DCMPL = 151; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DCMPG = 152; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFEQ = 153; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFNE = 154; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFLT = 155; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFGE = 156; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFGT = 157; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFLE = 158; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPEQ = 159; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPNE = 160; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPLT = 161; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPGE = 162; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPGT = 163; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ICMPLE = 164; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ACMPEQ = 165; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IF_ACMPNE = 166; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short GOTO = 167; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short JSR = 168; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short RET = 169; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short TABLESWITCH = 170; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LOOKUPSWITCH = 171; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IRETURN = 172; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short LRETURN = 173; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short FRETURN = 174; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short DRETURN = 175; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ARETURN = 176; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short RETURN = 177; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short GETSTATIC = 178; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short PUTSTATIC = 179; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short GETFIELD = 180; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short PUTFIELD = 181; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INVOKEVIRTUAL = 182; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INVOKESPECIAL = 183; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine Specification */ public static final short INVOKENONVIRTUAL = 183; // Old name in JDK 1.0 /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INVOKESTATIC = 184; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INVOKEINTERFACE = 185; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INVOKEDYNAMIC = 186; /** * Java VM opcode {@value}. * - * @see Opcode definitions in The - * Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short NEW = 187; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short NEWARRAY = 188; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ANEWARRAY = 189; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ARRAYLENGTH = 190; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short ATHROW = 191; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short CHECKCAST = 192; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short INSTANCEOF = 193; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short MONITORENTER = 194; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short MONITOREXIT = 195; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short WIDE = 196; /** * Java VM opcode {@value}. * - * @see Opcode - * definitions in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short MULTIANEWARRAY = 197; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFNULL = 198; /** * Java VM opcode {@value}. * - * @see Opcode definitions - * in The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short IFNONNULL = 199; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short GOTO_W = 200; /** * Java VM opcode {@value}. * - * @see Opcode definitions in - * The Java Virtual Machine Specification + * @see Opcode definitions in The Java Virtual Machine + * Specification */ public static final short JSR_W = 201; /** * JVM internal opcode {@value}. * - * @see Reserved opcodes in the Java - * Virtual Machine Specification + * @see Reserved opcodes in the Java Virtual Machine Specification */ public static final short BREAKPOINT = 202; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short LDC_QUICK = 203; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short LDC_W_QUICK = 204; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short LDC2_W_QUICK = 205; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short GETFIELD_QUICK = 206; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short PUTFIELD_QUICK = 207; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short GETFIELD2_QUICK = 208; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short PUTFIELD2_QUICK = 209; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short GETSTATIC_QUICK = 210; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short PUTSTATIC_QUICK = 211; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short GETSTATIC2_QUICK = 212; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short PUTSTATIC2_QUICK = 213; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKEVIRTUAL_QUICK = 214; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKENONVIRTUAL_QUICK = 215; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKESUPER_QUICK = 216; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKESTATIC_QUICK = 217; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKEINTERFACE_QUICK = 218; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKEVIRTUALOBJECT_QUICK = 219; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short NEW_QUICK = 221; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short ANEWARRAY_QUICK = 222; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short MULTIANEWARRAY_QUICK = 223; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short CHECKCAST_QUICK = 224; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INSTANCEOF_QUICK = 225; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short INVOKEVIRTUAL_QUICK_W = 226; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short GETFIELD_QUICK_W = 227; /** * JVM internal opcode {@value}. * - * @see - * Specification of _quick opcodes in the Java Virtual Machine Specification (version 1) - * @see Why the _quick - * opcodes were removed from the second version of the Java Virtual Machine Specification. + * @see Specification of _quick + * opcodes in the Java Virtual Machine Specification (version 1) + * @see Why the _quick opcodes were removed from the second + * version of the Java Virtual Machine Specification. */ public static final short PUTFIELD_QUICK_W = 228; /** * JVM internal opcode {@value}. * - * @see Reserved opcodes in the Java - * Virtual Machine Specification + * @see Reserved opcodes in the Java Virtual Machine Specification */ public static final short IMPDEP1 = 254; /** * JVM internal opcode {@value}. * - * @see Reserved opcodes in the Java - * Virtual Machine Specification + * @see Reserved opcodes in the Java Virtual Machine Specification */ public static final short IMPDEP2 = 255; /** - * BCEL virtual instruction for pushing an arbitrary data type onto the stack: {@value}. Will be converted to the appropriate JVM - * opcode when the class is dumped. + * BCEL virtual instruction for pushing an arbitrary data type onto the stack: {@value}. Will be converted to the appropriate JVM opcode when the class is + * dumped. */ public static final short PUSH = 4711; /** - * BCEL virtual instruction for either LOOKUPSWITCH or TABLESWITCH: {@value}. Will be converted to the appropriate JVM opcode when - * the class is dumped. + * BCEL virtual instruction for either LOOKUPSWITCH or TABLESWITCH: {@value}. Will be converted to the appropriate JVM opcode when the class is dumped. */ public static final short SWITCH = 4712; @@ -2821,64 +2842,64 @@ public final class Const { /** * Boolean data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_BOOLEAN = 4; /** * Char data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_CHAR = 5; /** * Float data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_FLOAT = 6; /** * Double data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_DOUBLE = 7; /** * Byte data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_BYTE = 8; /** * Short data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_SHORT = 9; /** * Int data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_INT = 10; /** * Long data type: {@value}. * - * @see Static Constraints in - * the Java Virtual Machine Specification + * @see Static Constraints in the Java Virtual Machine + * Specification */ public static final byte T_LONG = 11; @@ -2906,185 +2927,190 @@ public final class Const { public static final String[] EMPTY_STRING_ARRAY = {}; /** - * The primitive type names corresponding to the T_XX constants, e.g., TYPE_NAMES[T_INT] = "int" + * The primitive type names corresponding to the T_XX constants, for example, TYPE_NAMES[T_INT] = "int" */ - private static final String[] TYPE_NAMES = {ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "boolean", "char", "float", "double", "byte", "short", - "int", "long", "void", "array", "object", "unknown", "address"}; + private static final String[] TYPE_NAMES = { ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "boolean", "char", "float", "double", "byte", "short", + "int", "long", "void", "array", "object", "unknown", "address" }; /** - * The primitive class names corresponding to the T_XX constants, e.g., CLASS_TYPE_NAMES[T_INT] = "java.lang.Integer" + * The primitive class names corresponding to the T_XX constants, for example, CLASS_TYPE_NAMES[T_INT] = "java.lang.Integer" */ - private static final String[] CLASS_TYPE_NAMES = {ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "java.lang.Boolean", "java.lang.Character", - "java.lang.Float", "java.lang.Double", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Void", ILLEGAL_TYPE, - ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE}; + private static final String[] CLASS_TYPE_NAMES = { ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "java.lang.Boolean", "java.lang.Character", + "java.lang.Float", "java.lang.Double", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Void", ILLEGAL_TYPE, + ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE }; /** - * The signature characters corresponding to primitive types, e.g., SHORT_TYPE_NAMES[T_INT] = "I" + * The signature characters corresponding to primitive types, for example, SHORT_TYPE_NAMES[T_INT] = "I" */ - public static final String[] SHORT_TYPE_NAMES = {ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "Z", "C", "F", "D", "B", "S", "I", "J", "V", - ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE}; + public static final String[] SHORT_TYPE_NAMES = { ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE, "Z", "C", "F", "D", "B", "S", "I", "J", "V", + ILLEGAL_TYPE, ILLEGAL_TYPE, ILLEGAL_TYPE }; /** - * Number of byte code operands for each opcode, i.e., number of bytes after the tag byte itself. Indexed by opcode, so - * NO_OF_OPERANDS[BIPUSH] = the number of operands for a bipush instruction. + * Number of byte code operands for each opcode, that is, number of bytes after the tag byte itself. Indexed by opcode, so NO_OF_OPERANDS[BIPUSH] = the number + * of operands for a bipush instruction. */ - static final short[] NO_OF_OPERANDS = {0/* nop */, 0/* aconst_null */, 0/* iconst_m1 */, 0/* iconst_0 */, 0/* iconst_1 */, 0/* iconst_2 */, - 0/* iconst_3 */, 0/* iconst_4 */, 0/* iconst_5 */, 0/* lconst_0 */, 0/* lconst_1 */, 0/* fconst_0 */, 0/* fconst_1 */, 0/* fconst_2 */, 0/* dconst_0 */, - 0/* dconst_1 */, 1/* bipush */, 2/* sipush */, 1/* ldc */, 2/* ldc_w */, 2/* ldc2_w */, 1/* iload */, 1/* lload */, 1/* fload */, 1/* dload */, - 1/* aload */, 0/* iload_0 */, 0/* iload_1 */, 0/* iload_2 */, 0/* iload_3 */, 0/* lload_0 */, 0/* lload_1 */, 0/* lload_2 */, 0/* lload_3 */, - 0/* fload_0 */, 0/* fload_1 */, 0/* fload_2 */, 0/* fload_3 */, 0/* dload_0 */, 0/* dload_1 */, 0/* dload_2 */, 0/* dload_3 */, 0/* aload_0 */, - 0/* aload_1 */, 0/* aload_2 */, 0/* aload_3 */, 0/* iaload */, 0/* laload */, 0/* faload */, 0/* daload */, 0/* aaload */, 0/* baload */, 0/* caload */, - 0/* saload */, 1/* istore */, 1/* lstore */, 1/* fstore */, 1/* dstore */, 1/* astore */, 0/* istore_0 */, 0/* istore_1 */, 0/* istore_2 */, - 0/* istore_3 */, 0/* lstore_0 */, 0/* lstore_1 */, 0/* lstore_2 */, 0/* lstore_3 */, 0/* fstore_0 */, 0/* fstore_1 */, 0/* fstore_2 */, 0/* fstore_3 */, - 0/* dstore_0 */, 0/* dstore_1 */, 0/* dstore_2 */, 0/* dstore_3 */, 0/* astore_0 */, 0/* astore_1 */, 0/* astore_2 */, 0/* astore_3 */, 0/* iastore */, - 0/* lastore */, 0/* fastore */, 0/* dastore */, 0/* aastore */, 0/* bastore */, 0/* castore */, 0/* sastore */, 0/* pop */, 0/* pop2 */, 0/* dup */, - 0/* dup_x1 */, 0/* dup_x2 */, 0/* dup2 */, 0/* dup2_x1 */, 0/* dup2_x2 */, 0/* swap */, 0/* iadd */, 0/* ladd */, 0/* fadd */, 0/* dadd */, 0/* isub */, - 0/* lsub */, 0/* fsub */, 0/* dsub */, 0/* imul */, 0/* lmul */, 0/* fmul */, 0/* dmul */, 0/* idiv */, 0/* ldiv */, 0/* fdiv */, 0/* ddiv */, - 0/* irem */, 0/* lrem */, 0/* frem */, 0/* drem */, 0/* ineg */, 0/* lneg */, 0/* fneg */, 0/* dneg */, 0/* ishl */, 0/* lshl */, 0/* ishr */, - 0/* lshr */, 0/* iushr */, 0/* lushr */, 0/* iand */, 0/* land */, 0/* ior */, 0/* lor */, 0/* ixor */, 0/* lxor */, 2/* iinc */, 0/* i2l */, - 0/* i2f */, 0/* i2d */, 0/* l2i */, 0/* l2f */, 0/* l2d */, 0/* f2i */, 0/* f2l */, 0/* f2d */, 0/* d2i */, 0/* d2l */, 0/* d2f */, 0/* i2b */, - 0/* i2c */, 0/* i2s */, 0/* lcmp */, 0/* fcmpl */, 0/* fcmpg */, 0/* dcmpl */, 0/* dcmpg */, 2/* ifeq */, 2/* ifne */, 2/* iflt */, 2/* ifge */, - 2/* ifgt */, 2/* ifle */, 2/* if_icmpeq */, 2/* if_icmpne */, 2/* if_icmplt */, 2/* if_icmpge */, 2/* if_icmpgt */, 2/* if_icmple */, 2/* if_acmpeq */, - 2/* if_acmpne */, 2/* goto */, 2/* jsr */, 1/* ret */, UNPREDICTABLE/* tableswitch */, UNPREDICTABLE/* lookupswitch */, 0/* ireturn */, 0/* lreturn */, - 0/* freturn */, 0/* dreturn */, 0/* areturn */, 0/* return */, 2/* getstatic */, 2/* putstatic */, 2/* getfield */, 2/* putfield */, - 2/* invokevirtual */, 2/* invokespecial */, 2/* invokestatic */, 4/* invokeinterface */, 4/* invokedynamic */, 2/* new */, 1/* newarray */, - 2/* anewarray */, 0/* arraylength */, 0/* athrow */, 2/* checkcast */, 2/* instanceof */, 0/* monitorenter */, 0/* monitorexit */, - UNPREDICTABLE/* wide */, 3/* multianewarray */, 2/* ifnull */, 2/* ifnonnull */, 4/* goto_w */, 4/* jsr_w */, 0/* breakpoint */, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, RESERVED/* impdep1 */, - RESERVED/* impdep2 */ + static final short[] NO_OF_OPERANDS = { 0/* nop */, 0/* aconst_null */, 0/* iconst_m1 */, 0/* iconst_0 */, 0/* iconst_1 */, 0/* iconst_2 */, + 0/* iconst_3 */, 0/* iconst_4 */, 0/* iconst_5 */, 0/* lconst_0 */, 0/* lconst_1 */, 0/* fconst_0 */, 0/* fconst_1 */, 0/* fconst_2 */, + 0/* dconst_0 */, 0/* dconst_1 */, 1/* bipush */, 2/* sipush */, 1/* ldc */, 2/* ldc_w */, 2/* ldc2_w */, 1/* iload */, 1/* lload */, 1/* fload */, + 1/* dload */, 1/* aload */, 0/* iload_0 */, 0/* iload_1 */, 0/* iload_2 */, 0/* iload_3 */, 0/* lload_0 */, 0/* lload_1 */, 0/* lload_2 */, + 0/* lload_3 */, 0/* fload_0 */, 0/* fload_1 */, 0/* fload_2 */, 0/* fload_3 */, 0/* dload_0 */, 0/* dload_1 */, 0/* dload_2 */, 0/* dload_3 */, + 0/* aload_0 */, 0/* aload_1 */, 0/* aload_2 */, 0/* aload_3 */, 0/* iaload */, 0/* laload */, 0/* faload */, 0/* daload */, 0/* aaload */, + 0/* baload */, 0/* caload */, 0/* saload */, 1/* istore */, 1/* lstore */, 1/* fstore */, 1/* dstore */, 1/* astore */, 0/* istore_0 */, + 0/* istore_1 */, 0/* istore_2 */, 0/* istore_3 */, 0/* lstore_0 */, 0/* lstore_1 */, 0/* lstore_2 */, 0/* lstore_3 */, 0/* fstore_0 */, + 0/* fstore_1 */, 0/* fstore_2 */, 0/* fstore_3 */, 0/* dstore_0 */, 0/* dstore_1 */, 0/* dstore_2 */, 0/* dstore_3 */, 0/* astore_0 */, + 0/* astore_1 */, 0/* astore_2 */, 0/* astore_3 */, 0/* iastore */, 0/* lastore */, 0/* fastore */, 0/* dastore */, 0/* aastore */, 0/* bastore */, + 0/* castore */, 0/* sastore */, 0/* pop */, 0/* pop2 */, 0/* dup */, 0/* dup_x1 */, 0/* dup_x2 */, 0/* dup2 */, 0/* dup2_x1 */, 0/* dup2_x2 */, + 0/* swap */, 0/* iadd */, 0/* ladd */, 0/* fadd */, 0/* dadd */, 0/* isub */, 0/* lsub */, 0/* fsub */, 0/* dsub */, 0/* imul */, 0/* lmul */, + 0/* fmul */, 0/* dmul */, 0/* idiv */, 0/* ldiv */, 0/* fdiv */, 0/* ddiv */, 0/* irem */, 0/* lrem */, 0/* frem */, 0/* drem */, 0/* ineg */, + 0/* lneg */, 0/* fneg */, 0/* dneg */, 0/* ishl */, 0/* lshl */, 0/* ishr */, 0/* lshr */, 0/* iushr */, 0/* lushr */, 0/* iand */, 0/* land */, + 0/* ior */, 0/* lor */, 0/* ixor */, 0/* lxor */, 2/* iinc */, 0/* i2l */, 0/* i2f */, 0/* i2d */, 0/* l2i */, 0/* l2f */, 0/* l2d */, 0/* f2i */, + 0/* f2l */, 0/* f2d */, 0/* d2i */, 0/* d2l */, 0/* d2f */, 0/* i2b */, 0/* i2c */, 0/* i2s */, 0/* lcmp */, 0/* fcmpl */, 0/* fcmpg */, + 0/* dcmpl */, 0/* dcmpg */, 2/* ifeq */, 2/* ifne */, 2/* iflt */, 2/* ifge */, 2/* ifgt */, 2/* ifle */, 2/* if_icmpeq */, 2/* if_icmpne */, + 2/* if_icmplt */, 2/* if_icmpge */, 2/* if_icmpgt */, 2/* if_icmple */, 2/* if_acmpeq */, 2/* if_acmpne */, 2/* goto */, 2/* jsr */, 1/* ret */, + UNPREDICTABLE/* tableswitch */, UNPREDICTABLE/* lookupswitch */, 0/* ireturn */, 0/* lreturn */, 0/* freturn */, 0/* dreturn */, 0/* areturn */, + 0/* return */, 2/* getstatic */, 2/* putstatic */, 2/* getfield */, 2/* putfield */, 2/* invokevirtual */, 2/* invokespecial */, + 2/* invokestatic */, 4/* invokeinterface */, 4/* invokedynamic */, 2/* new */, 1/* newarray */, 2/* anewarray */, 0/* arraylength */, 0/* athrow */, + 2/* checkcast */, 2/* instanceof */, 0/* monitorenter */, 0/* monitorexit */, UNPREDICTABLE/* wide */, 3/* multianewarray */, 2/* ifnull */, + 2/* ifnonnull */, 4/* goto_w */, 4/* jsr_w */, 0/* breakpoint */, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, RESERVED/* impdep1 */, RESERVED/* impdep2 */ }; /** - * How the byte code operands are to be interpreted for each opcode. Indexed by opcode. TYPE_OF_OPERANDS[ILOAD] = an - * array of shorts describing the data types for the instruction. - */ - static final short[][] TYPE_OF_OPERANDS = {{}/* nop */, {}/* aconst_null */, {}/* iconst_m1 */, {}/* iconst_0 */, {}/* iconst_1 */, - {}/* iconst_2 */, {}/* iconst_3 */, {}/* iconst_4 */, {}/* iconst_5 */, {}/* lconst_0 */, {}/* lconst_1 */, {}/* fconst_0 */, {}/* fconst_1 */, - {}/* fconst_2 */, {}/* dconst_0 */, {}/* dconst_1 */, {T_BYTE}/* bipush */, {T_SHORT}/* sipush */, {T_BYTE}/* ldc */, {T_SHORT}/* ldc_w */, - {T_SHORT}/* ldc2_w */, {T_BYTE}/* iload */, {T_BYTE}/* lload */, {T_BYTE}/* fload */, {T_BYTE}/* dload */, {T_BYTE}/* aload */, {}/* iload_0 */, - {}/* iload_1 */, {}/* iload_2 */, {}/* iload_3 */, {}/* lload_0 */, {}/* lload_1 */, {}/* lload_2 */, {}/* lload_3 */, {}/* fload_0 */, {}/* fload_1 */, - {}/* fload_2 */, {}/* fload_3 */, {}/* dload_0 */, {}/* dload_1 */, {}/* dload_2 */, {}/* dload_3 */, {}/* aload_0 */, {}/* aload_1 */, {}/* aload_2 */, - {}/* aload_3 */, {}/* iaload */, {}/* laload */, {}/* faload */, {}/* daload */, {}/* aaload */, {}/* baload */, {}/* caload */, {}/* saload */, - {T_BYTE}/* istore */, {T_BYTE}/* lstore */, {T_BYTE}/* fstore */, {T_BYTE}/* dstore */, {T_BYTE}/* astore */, {}/* istore_0 */, {}/* istore_1 */, - {}/* istore_2 */, {}/* istore_3 */, {}/* lstore_0 */, {}/* lstore_1 */, {}/* lstore_2 */, {}/* lstore_3 */, {}/* fstore_0 */, {}/* fstore_1 */, - {}/* fstore_2 */, {}/* fstore_3 */, {}/* dstore_0 */, {}/* dstore_1 */, {}/* dstore_2 */, {}/* dstore_3 */, {}/* astore_0 */, {}/* astore_1 */, - {}/* astore_2 */, {}/* astore_3 */, {}/* iastore */, {}/* lastore */, {}/* fastore */, {}/* dastore */, {}/* aastore */, {}/* bastore */, - {}/* castore */, {}/* sastore */, {}/* pop */, {}/* pop2 */, {}/* dup */, {}/* dup_x1 */, {}/* dup_x2 */, {}/* dup2 */, {}/* dup2_x1 */, - {}/* dup2_x2 */, {}/* swap */, {}/* iadd */, {}/* ladd */, {}/* fadd */, {}/* dadd */, {}/* isub */, {}/* lsub */, {}/* fsub */, {}/* dsub */, - {}/* imul */, {}/* lmul */, {}/* fmul */, {}/* dmul */, {}/* idiv */, {}/* ldiv */, {}/* fdiv */, {}/* ddiv */, {}/* irem */, {}/* lrem */, - {}/* frem */, {}/* drem */, {}/* ineg */, {}/* lneg */, {}/* fneg */, {}/* dneg */, {}/* ishl */, {}/* lshl */, {}/* ishr */, {}/* lshr */, - {}/* iushr */, {}/* lushr */, {}/* iand */, {}/* land */, {}/* ior */, {}/* lor */, {}/* ixor */, {}/* lxor */, {T_BYTE, T_BYTE}/* iinc */, {}/* i2l */, - {}/* i2f */, {}/* i2d */, {}/* l2i */, {}/* l2f */, {}/* l2d */, {}/* f2i */, {}/* f2l */, {}/* f2d */, {}/* d2i */, {}/* d2l */, {}/* d2f */, - {}/* i2b */, {}/* i2c */, {}/* i2s */, {}/* lcmp */, {}/* fcmpl */, {}/* fcmpg */, {}/* dcmpl */, {}/* dcmpg */, {T_SHORT}/* ifeq */, - {T_SHORT}/* ifne */, {T_SHORT}/* iflt */, {T_SHORT}/* ifge */, {T_SHORT}/* ifgt */, {T_SHORT}/* ifle */, {T_SHORT}/* if_icmpeq */, - {T_SHORT}/* if_icmpne */, {T_SHORT}/* if_icmplt */, {T_SHORT}/* if_icmpge */, {T_SHORT}/* if_icmpgt */, {T_SHORT}/* if_icmple */, - {T_SHORT}/* if_acmpeq */, {T_SHORT}/* if_acmpne */, {T_SHORT}/* goto */, {T_SHORT}/* jsr */, {T_BYTE}/* ret */, {}/* tableswitch */, - {}/* lookupswitch */, {}/* ireturn */, {}/* lreturn */, {}/* freturn */, {}/* dreturn */, {}/* areturn */, {}/* return */, {T_SHORT}/* getstatic */, - {T_SHORT}/* putstatic */, {T_SHORT}/* getfield */, {T_SHORT}/* putfield */, {T_SHORT}/* invokevirtual */, {T_SHORT}/* invokespecial */, - {T_SHORT}/* invokestatic */, {T_SHORT, T_BYTE, T_BYTE}/* invokeinterface */, {T_SHORT, T_BYTE, T_BYTE}/* invokedynamic */, {T_SHORT}/* new */, - {T_BYTE}/* newarray */, {T_SHORT}/* anewarray */, {}/* arraylength */, {}/* athrow */, {T_SHORT}/* checkcast */, {T_SHORT}/* instanceof */, - {}/* monitorenter */, {}/* monitorexit */, {T_BYTE}/* wide */, {T_SHORT, T_BYTE}/* multianewarray */, {T_SHORT}/* ifnull */, {T_SHORT}/* ifnonnull */, - {T_INT}/* goto_w */, {T_INT}/* jsr_w */, {}/* breakpoint */, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}/* impdep1 */, {}/* impdep2 */ + * How the byte code operands are to be interpreted for each opcode. Indexed by opcode. TYPE_OF_OPERANDS[ILOAD] = an array of shorts describing the data + * types for the instruction. + */ + static final short[][] TYPE_OF_OPERANDS = { {}/* nop */, {}/* aconst_null */, {}/* iconst_m1 */, {}/* iconst_0 */, {}/* iconst_1 */, {}/* iconst_2 */, + {}/* iconst_3 */, {}/* iconst_4 */, {}/* iconst_5 */, {}/* lconst_0 */, {}/* lconst_1 */, {}/* fconst_0 */, {}/* fconst_1 */, {}/* fconst_2 */, + {}/* dconst_0 */, {}/* dconst_1 */, { T_BYTE }/* bipush */, { T_SHORT }/* sipush */, { T_BYTE }/* ldc */, { T_SHORT }/* ldc_w */, + { T_SHORT }/* ldc2_w */, { T_BYTE }/* iload */, { T_BYTE }/* lload */, { T_BYTE }/* fload */, { T_BYTE }/* dload */, { T_BYTE }/* aload */, + {}/* iload_0 */, {}/* iload_1 */, {}/* iload_2 */, {}/* iload_3 */, {}/* lload_0 */, {}/* lload_1 */, {}/* lload_2 */, {}/* lload_3 */, + {}/* fload_0 */, {}/* fload_1 */, {}/* fload_2 */, {}/* fload_3 */, {}/* dload_0 */, {}/* dload_1 */, {}/* dload_2 */, {}/* dload_3 */, + {}/* aload_0 */, {}/* aload_1 */, {}/* aload_2 */, {}/* aload_3 */, {}/* iaload */, {}/* laload */, {}/* faload */, {}/* daload */, {}/* aaload */, + {}/* baload */, {}/* caload */, {}/* saload */, { T_BYTE }/* istore */, { T_BYTE }/* lstore */, { T_BYTE }/* fstore */, { T_BYTE }/* dstore */, + { T_BYTE }/* astore */, {}/* istore_0 */, {}/* istore_1 */, {}/* istore_2 */, {}/* istore_3 */, {}/* lstore_0 */, {}/* lstore_1 */, + {}/* lstore_2 */, {}/* lstore_3 */, {}/* fstore_0 */, {}/* fstore_1 */, {}/* fstore_2 */, {}/* fstore_3 */, {}/* dstore_0 */, {}/* dstore_1 */, + {}/* dstore_2 */, {}/* dstore_3 */, {}/* astore_0 */, {}/* astore_1 */, {}/* astore_2 */, {}/* astore_3 */, {}/* iastore */, {}/* lastore */, + {}/* fastore */, {}/* dastore */, {}/* aastore */, {}/* bastore */, {}/* castore */, {}/* sastore */, {}/* pop */, {}/* pop2 */, {}/* dup */, + {}/* dup_x1 */, {}/* dup_x2 */, {}/* dup2 */, {}/* dup2_x1 */, {}/* dup2_x2 */, {}/* swap */, {}/* iadd */, {}/* ladd */, {}/* fadd */, + {}/* dadd */, {}/* isub */, {}/* lsub */, {}/* fsub */, {}/* dsub */, {}/* imul */, {}/* lmul */, {}/* fmul */, {}/* dmul */, {}/* idiv */, + {}/* ldiv */, {}/* fdiv */, {}/* ddiv */, {}/* irem */, {}/* lrem */, {}/* frem */, {}/* drem */, {}/* ineg */, {}/* lneg */, {}/* fneg */, + {}/* dneg */, {}/* ishl */, {}/* lshl */, {}/* ishr */, {}/* lshr */, {}/* iushr */, {}/* lushr */, {}/* iand */, {}/* land */, {}/* ior */, + {}/* lor */, {}/* ixor */, {}/* lxor */, { T_BYTE, T_BYTE }/* iinc */, {}/* i2l */, {}/* i2f */, {}/* i2d */, {}/* l2i */, {}/* l2f */, {}/* l2d */, + {}/* f2i */, {}/* f2l */, {}/* f2d */, {}/* d2i */, {}/* d2l */, {}/* d2f */, {}/* i2b */, {}/* i2c */, {}/* i2s */, {}/* lcmp */, {}/* fcmpl */, + {}/* fcmpg */, {}/* dcmpl */, {}/* dcmpg */, { T_SHORT }/* ifeq */, { T_SHORT }/* ifne */, { T_SHORT }/* iflt */, { T_SHORT }/* ifge */, + { T_SHORT }/* ifgt */, { T_SHORT }/* ifle */, { T_SHORT }/* if_icmpeq */, { T_SHORT }/* if_icmpne */, { T_SHORT }/* if_icmplt */, + { T_SHORT }/* if_icmpge */, { T_SHORT }/* if_icmpgt */, { T_SHORT }/* if_icmple */, { T_SHORT }/* if_acmpeq */, { T_SHORT }/* if_acmpne */, + { T_SHORT }/* goto */, { T_SHORT }/* jsr */, { T_BYTE }/* ret */, {}/* tableswitch */, {}/* lookupswitch */, {}/* ireturn */, {}/* lreturn */, + {}/* freturn */, {}/* dreturn */, {}/* areturn */, {}/* return */, { T_SHORT }/* getstatic */, { T_SHORT }/* putstatic */, + { T_SHORT }/* getfield */, { T_SHORT }/* putfield */, { T_SHORT }/* invokevirtual */, { T_SHORT }/* invokespecial */, { T_SHORT }/* invokestatic */, + { T_SHORT, T_BYTE, T_BYTE }/* invokeinterface */, { T_SHORT, T_BYTE, T_BYTE }/* invokedynamic */, { T_SHORT }/* new */, { T_BYTE }/* newarray */, + { T_SHORT }/* anewarray */, {}/* arraylength */, {}/* athrow */, { T_SHORT }/* checkcast */, { T_SHORT }/* instanceof */, {}/* monitorenter */, + {}/* monitorexit */, { T_BYTE }/* wide */, { T_SHORT, T_BYTE }/* multianewarray */, { T_SHORT }/* ifnull */, { T_SHORT }/* ifnonnull */, + { T_INT }/* goto_w */, { T_INT }/* jsr_w */, {}/* breakpoint */, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}/* impdep1 */, + {}/* impdep2 */ }; /** * Names of opcodes. Indexed by opcode. OPCODE_NAMES[ALOAD] = "aload". */ - static final String[] OPCODE_NAMES = {"nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", - "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", - "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", - "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", - "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", "lstore_1", - "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", "astore_1", - "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", "dup_x1", - "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", "dmul", "idiv", - "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", "lushr", "iand", - "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", "i2b", "i2c", "i2s", - "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "if_icmpeq", "if_icmpne", "if_icmplt", "if_icmpge", - "if_icmpgt", "if_icmple", "if_acmpeq", "if_acmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", "lreturn", "freturn", "dreturn", - "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", "invokestatic", "invokeinterface", - "invokedynamic", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", "monitorenter", "monitorexit", "wide", - "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w", "breakpoint", ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, - ILLEGAL_OPCODE, ILLEGAL_OPCODE, "impdep1", "impdep2"}; - - /** + static final String[] OPCODE_NAMES = { "nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", + "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", + "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", + "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", + "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", + "lstore_1", "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", + "astore_1", "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", + "dup_x1", "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", + "dmul", "idiv", "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", + "lushr", "iand", "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", + "i2b", "i2c", "i2s", "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "if_icmpeq", "if_icmpne", + "if_icmplt", "if_icmpge", "if_icmpgt", "if_icmple", "if_acmpeq", "if_acmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", + "lreturn", "freturn", "dreturn", "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", + "invokestatic", "invokeinterface", "invokedynamic", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", + "monitorenter", "monitorexit", "wide", "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w", "breakpoint", ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, + ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, ILLEGAL_OPCODE, "impdep1", "impdep2" }; + + /** + * The length of the OPCODE_NAMES array. + * * @since 6.0 */ public static final int OPCODE_NAMES_LENGTH = OPCODE_NAMES.length; /** - * Number of words consumed on operand stack by instructions. Indexed by opcode. CONSUME_STACK[FALOAD] = number of words - * consumed from the stack by a faload instruction. - */ - static final int[] CONSUME_STACK = {0/* nop */, 0/* aconst_null */, 0/* iconst_m1 */, 0/* iconst_0 */, 0/* iconst_1 */, 0/* iconst_2 */, - 0/* iconst_3 */, 0/* iconst_4 */, 0/* iconst_5 */, 0/* lconst_0 */, 0/* lconst_1 */, 0/* fconst_0 */, 0/* fconst_1 */, 0/* fconst_2 */, 0/* dconst_0 */, - 0/* dconst_1 */, 0/* bipush */, 0/* sipush */, 0/* ldc */, 0/* ldc_w */, 0/* ldc2_w */, 0/* iload */, 0/* lload */, 0/* fload */, 0/* dload */, - 0/* aload */, 0/* iload_0 */, 0/* iload_1 */, 0/* iload_2 */, 0/* iload_3 */, 0/* lload_0 */, 0/* lload_1 */, 0/* lload_2 */, 0/* lload_3 */, - 0/* fload_0 */, 0/* fload_1 */, 0/* fload_2 */, 0/* fload_3 */, 0/* dload_0 */, 0/* dload_1 */, 0/* dload_2 */, 0/* dload_3 */, 0/* aload_0 */, - 0/* aload_1 */, 0/* aload_2 */, 0/* aload_3 */, 2/* iaload */, 2/* laload */, 2/* faload */, 2/* daload */, 2/* aaload */, 2/* baload */, 2/* caload */, - 2/* saload */, 1/* istore */, 2/* lstore */, 1/* fstore */, 2/* dstore */, 1/* astore */, 1/* istore_0 */, 1/* istore_1 */, 1/* istore_2 */, - 1/* istore_3 */, 2/* lstore_0 */, 2/* lstore_1 */, 2/* lstore_2 */, 2/* lstore_3 */, 1/* fstore_0 */, 1/* fstore_1 */, 1/* fstore_2 */, 1/* fstore_3 */, - 2/* dstore_0 */, 2/* dstore_1 */, 2/* dstore_2 */, 2/* dstore_3 */, 1/* astore_0 */, 1/* astore_1 */, 1/* astore_2 */, 1/* astore_3 */, 3/* iastore */, - 4/* lastore */, 3/* fastore */, 4/* dastore */, 3/* aastore */, 3/* bastore */, 3/* castore */, 3/* sastore */, 1/* pop */, 2/* pop2 */, 1/* dup */, - 2/* dup_x1 */, 3/* dup_x2 */, 2/* dup2 */, 3/* dup2_x1 */, 4/* dup2_x2 */, 2/* swap */, 2/* iadd */, 4/* ladd */, 2/* fadd */, 4/* dadd */, 2/* isub */, - 4/* lsub */, 2/* fsub */, 4/* dsub */, 2/* imul */, 4/* lmul */, 2/* fmul */, 4/* dmul */, 2/* idiv */, 4/* ldiv */, 2/* fdiv */, 4/* ddiv */, - 2/* irem */, 4/* lrem */, 2/* frem */, 4/* drem */, 1/* ineg */, 2/* lneg */, 1/* fneg */, 2/* dneg */, 2/* ishl */, 3/* lshl */, 2/* ishr */, - 3/* lshr */, 2/* iushr */, 3/* lushr */, 2/* iand */, 4/* land */, 2/* ior */, 4/* lor */, 2/* ixor */, 4/* lxor */, 0/* iinc */, 1/* i2l */, - 1/* i2f */, 1/* i2d */, 2/* l2i */, 2/* l2f */, 2/* l2d */, 1/* f2i */, 1/* f2l */, 1/* f2d */, 2/* d2i */, 2/* d2l */, 2/* d2f */, 1/* i2b */, - 1/* i2c */, 1/* i2s */, 4/* lcmp */, 2/* fcmpl */, 2/* fcmpg */, 4/* dcmpl */, 4/* dcmpg */, 1/* ifeq */, 1/* ifne */, 1/* iflt */, 1/* ifge */, - 1/* ifgt */, 1/* ifle */, 2/* if_icmpeq */, 2/* if_icmpne */, 2/* if_icmplt */, 2 /* if_icmpge */, 2/* if_icmpgt */, 2/* if_icmple */, 2/* if_acmpeq */, - 2/* if_acmpne */, 0/* goto */, 0/* jsr */, 0/* ret */, 1/* tableswitch */, 1/* lookupswitch */, 1/* ireturn */, 2/* lreturn */, 1/* freturn */, - 2/* dreturn */, 1/* areturn */, 0/* return */, 0/* getstatic */, UNPREDICTABLE/* putstatic */, 1/* getfield */, UNPREDICTABLE/* putfield */, - UNPREDICTABLE/* invokevirtual */, UNPREDICTABLE/* invokespecial */, UNPREDICTABLE/* invokestatic */, UNPREDICTABLE/* invokeinterface */, - UNPREDICTABLE/* invokedynamic */, 0/* new */, 1/* newarray */, 1/* anewarray */, 1/* arraylength */, 1/* athrow */, 1/* checkcast */, 1/* instanceof */, - 1/* monitorenter */, 1/* monitorexit */, 0/* wide */, UNPREDICTABLE/* multianewarray */, 1/* ifnull */, 1/* ifnonnull */, 0/* goto_w */, 0/* jsr_w */, - 0/* breakpoint */, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNPREDICTABLE/* impdep1 */, UNPREDICTABLE/* impdep2 */ + * Number of words consumed on operand stack by instructions. Indexed by opcode. CONSUME_STACK[FALOAD] = number of words consumed from the stack by a faload + * instruction. + */ + static final int[] CONSUME_STACK = { 0/* nop */, 0/* aconst_null */, 0/* iconst_m1 */, 0/* iconst_0 */, 0/* iconst_1 */, 0/* iconst_2 */, 0/* iconst_3 */, + 0/* iconst_4 */, 0/* iconst_5 */, 0/* lconst_0 */, 0/* lconst_1 */, 0/* fconst_0 */, 0/* fconst_1 */, 0/* fconst_2 */, 0/* dconst_0 */, + 0/* dconst_1 */, 0/* bipush */, 0/* sipush */, 0/* ldc */, 0/* ldc_w */, 0/* ldc2_w */, 0/* iload */, 0/* lload */, 0/* fload */, 0/* dload */, + 0/* aload */, 0/* iload_0 */, 0/* iload_1 */, 0/* iload_2 */, 0/* iload_3 */, 0/* lload_0 */, 0/* lload_1 */, 0/* lload_2 */, 0/* lload_3 */, + 0/* fload_0 */, 0/* fload_1 */, 0/* fload_2 */, 0/* fload_3 */, 0/* dload_0 */, 0/* dload_1 */, 0/* dload_2 */, 0/* dload_3 */, 0/* aload_0 */, + 0/* aload_1 */, 0/* aload_2 */, 0/* aload_3 */, 2/* iaload */, 2/* laload */, 2/* faload */, 2/* daload */, 2/* aaload */, 2/* baload */, + 2/* caload */, 2/* saload */, 1/* istore */, 2/* lstore */, 1/* fstore */, 2/* dstore */, 1/* astore */, 1/* istore_0 */, 1/* istore_1 */, + 1/* istore_2 */, 1/* istore_3 */, 2/* lstore_0 */, 2/* lstore_1 */, 2/* lstore_2 */, 2/* lstore_3 */, 1/* fstore_0 */, 1/* fstore_1 */, + 1/* fstore_2 */, 1/* fstore_3 */, 2/* dstore_0 */, 2/* dstore_1 */, 2/* dstore_2 */, 2/* dstore_3 */, 1/* astore_0 */, 1/* astore_1 */, + 1/* astore_2 */, 1/* astore_3 */, 3/* iastore */, 4/* lastore */, 3/* fastore */, 4/* dastore */, 3/* aastore */, 3/* bastore */, 3/* castore */, + 3/* sastore */, 1/* pop */, 2/* pop2 */, 1/* dup */, 2/* dup_x1 */, 3/* dup_x2 */, 2/* dup2 */, 3/* dup2_x1 */, 4/* dup2_x2 */, 2/* swap */, + 2/* iadd */, 4/* ladd */, 2/* fadd */, 4/* dadd */, 2/* isub */, 4/* lsub */, 2/* fsub */, 4/* dsub */, 2/* imul */, 4/* lmul */, 2/* fmul */, + 4/* dmul */, 2/* idiv */, 4/* ldiv */, 2/* fdiv */, 4/* ddiv */, 2/* irem */, 4/* lrem */, 2/* frem */, 4/* drem */, 1/* ineg */, 2/* lneg */, + 1/* fneg */, 2/* dneg */, 2/* ishl */, 3/* lshl */, 2/* ishr */, 3/* lshr */, 2/* iushr */, 3/* lushr */, 2/* iand */, 4/* land */, 2/* ior */, + 4/* lor */, 2/* ixor */, 4/* lxor */, 0/* iinc */, 1/* i2l */, 1/* i2f */, 1/* i2d */, 2/* l2i */, 2/* l2f */, 2/* l2d */, 1/* f2i */, 1/* f2l */, + 1/* f2d */, 2/* d2i */, 2/* d2l */, 2/* d2f */, 1/* i2b */, 1/* i2c */, 1/* i2s */, 4/* lcmp */, 2/* fcmpl */, 2/* fcmpg */, 4/* dcmpl */, + 4/* dcmpg */, 1/* ifeq */, 1/* ifne */, 1/* iflt */, 1/* ifge */, 1/* ifgt */, 1/* ifle */, 2/* if_icmpeq */, 2/* if_icmpne */, 2/* if_icmplt */, + 2 /* if_icmpge */, 2/* if_icmpgt */, 2/* if_icmple */, 2/* if_acmpeq */, 2/* if_acmpne */, 0/* goto */, 0/* jsr */, 0/* ret */, 1/* tableswitch */, + 1/* lookupswitch */, 1/* ireturn */, 2/* lreturn */, 1/* freturn */, 2/* dreturn */, 1/* areturn */, 0/* return */, 0/* getstatic */, + UNPREDICTABLE/* putstatic */, 1/* getfield */, UNPREDICTABLE/* putfield */, UNPREDICTABLE/* invokevirtual */, UNPREDICTABLE/* invokespecial */, + UNPREDICTABLE/* invokestatic */, UNPREDICTABLE/* invokeinterface */, UNPREDICTABLE/* invokedynamic */, 0/* new */, 1/* newarray */, + 1/* anewarray */, 1/* arraylength */, 1/* athrow */, 1/* checkcast */, 1/* instanceof */, 1/* monitorenter */, 1/* monitorexit */, 0/* wide */, + UNPREDICTABLE/* multianewarray */, 1/* ifnull */, 1/* ifnonnull */, 0/* goto_w */, 0/* jsr_w */, 0/* breakpoint */, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNPREDICTABLE/* impdep1 */, + UNPREDICTABLE/* impdep2 */ }; /** - * Number of words produced onto operand stack by instructions. Indexed by opcode. CONSUME_STACK[DALOAD] = number of - * words consumed from the stack by a daload instruction. - */ - static final int[] PRODUCE_STACK = {0/* nop */, 1/* aconst_null */, 1/* iconst_m1 */, 1/* iconst_0 */, 1/* iconst_1 */, 1/* iconst_2 */, - 1/* iconst_3 */, 1/* iconst_4 */, 1/* iconst_5 */, 2/* lconst_0 */, 2/* lconst_1 */, 1/* fconst_0 */, 1/* fconst_1 */, 1/* fconst_2 */, 2/* dconst_0 */, - 2/* dconst_1 */, 1/* bipush */, 1/* sipush */, 1/* ldc */, 1/* ldc_w */, 2/* ldc2_w */, 1/* iload */, 2/* lload */, 1/* fload */, 2/* dload */, - 1/* aload */, 1/* iload_0 */, 1/* iload_1 */, 1/* iload_2 */, 1/* iload_3 */, 2/* lload_0 */, 2/* lload_1 */, 2/* lload_2 */, 2/* lload_3 */, - 1/* fload_0 */, 1/* fload_1 */, 1/* fload_2 */, 1/* fload_3 */, 2/* dload_0 */, 2/* dload_1 */, 2/* dload_2 */, 2/* dload_3 */, 1/* aload_0 */, - 1/* aload_1 */, 1/* aload_2 */, 1/* aload_3 */, 1/* iaload */, 2/* laload */, 1/* faload */, 2/* daload */, 1/* aaload */, 1/* baload */, 1/* caload */, - 1/* saload */, 0/* istore */, 0/* lstore */, 0/* fstore */, 0/* dstore */, 0/* astore */, 0/* istore_0 */, 0/* istore_1 */, 0/* istore_2 */, - 0/* istore_3 */, 0/* lstore_0 */, 0/* lstore_1 */, 0/* lstore_2 */, 0/* lstore_3 */, 0/* fstore_0 */, 0/* fstore_1 */, 0/* fstore_2 */, 0/* fstore_3 */, - 0/* dstore_0 */, 0/* dstore_1 */, 0/* dstore_2 */, 0/* dstore_3 */, 0/* astore_0 */, 0/* astore_1 */, 0/* astore_2 */, 0/* astore_3 */, 0/* iastore */, - 0/* lastore */, 0/* fastore */, 0/* dastore */, 0/* aastore */, 0/* bastore */, 0/* castore */, 0/* sastore */, 0/* pop */, 0/* pop2 */, 2/* dup */, - 3/* dup_x1 */, 4/* dup_x2 */, 4/* dup2 */, 5/* dup2_x1 */, 6/* dup2_x2 */, 2/* swap */, 1/* iadd */, 2/* ladd */, 1/* fadd */, 2/* dadd */, 1/* isub */, - 2/* lsub */, 1/* fsub */, 2/* dsub */, 1/* imul */, 2/* lmul */, 1/* fmul */, 2/* dmul */, 1/* idiv */, 2/* ldiv */, 1/* fdiv */, 2/* ddiv */, - 1/* irem */, 2/* lrem */, 1/* frem */, 2/* drem */, 1/* ineg */, 2/* lneg */, 1/* fneg */, 2/* dneg */, 1/* ishl */, 2/* lshl */, 1/* ishr */, - 2/* lshr */, 1/* iushr */, 2/* lushr */, 1/* iand */, 2/* land */, 1/* ior */, 2/* lor */, 1/* ixor */, 2/* lxor */, 0/* iinc */, 2/* i2l */, - 1/* i2f */, 2/* i2d */, 1/* l2i */, 1/* l2f */, 2/* l2d */, 1/* f2i */, 2/* f2l */, 2/* f2d */, 1/* d2i */, 2/* d2l */, 1/* d2f */, 1/* i2b */, - 1/* i2c */, 1/* i2s */, 1/* lcmp */, 1/* fcmpl */, 1/* fcmpg */, 1/* dcmpl */, 1/* dcmpg */, 0/* ifeq */, 0/* ifne */, 0/* iflt */, 0/* ifge */, - 0/* ifgt */, 0/* ifle */, 0/* if_icmpeq */, 0/* if_icmpne */, 0/* if_icmplt */, 0/* if_icmpge */, 0/* if_icmpgt */, 0/* if_icmple */, 0/* if_acmpeq */, - 0/* if_acmpne */, 0/* goto */, 1/* jsr */, 0/* ret */, 0/* tableswitch */, 0/* lookupswitch */, 0/* ireturn */, 0/* lreturn */, 0/* freturn */, - 0/* dreturn */, 0/* areturn */, 0/* return */, UNPREDICTABLE/* getstatic */, 0/* putstatic */, UNPREDICTABLE/* getfield */, 0/* putfield */, - UNPREDICTABLE/* invokevirtual */, UNPREDICTABLE/* invokespecial */, UNPREDICTABLE/* invokestatic */, UNPREDICTABLE/* invokeinterface */, - UNPREDICTABLE/* invokedynamic */, 1/* new */, 1/* newarray */, 1/* anewarray */, 1/* arraylength */, 1/* athrow */, 1/* checkcast */, 1/* instanceof */, - 0/* monitorenter */, 0/* monitorexit */, 0/* wide */, 1/* multianewarray */, 0/* ifnull */, 0/* ifnonnull */, 0/* goto_w */, 1/* jsr_w */, - 0/* breakpoint */, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, - UNPREDICTABLE/* impdep1 */, UNPREDICTABLE/* impdep2 */ + * Number of words produced onto operand stack by instructions. Indexed by opcode. CONSUME_STACK[DALOAD] = number of words consumed from the stack by a + * daload instruction. + */ + static final int[] PRODUCE_STACK = { 0/* nop */, 1/* aconst_null */, 1/* iconst_m1 */, 1/* iconst_0 */, 1/* iconst_1 */, 1/* iconst_2 */, 1/* iconst_3 */, + 1/* iconst_4 */, 1/* iconst_5 */, 2/* lconst_0 */, 2/* lconst_1 */, 1/* fconst_0 */, 1/* fconst_1 */, 1/* fconst_2 */, 2/* dconst_0 */, + 2/* dconst_1 */, 1/* bipush */, 1/* sipush */, 1/* ldc */, 1/* ldc_w */, 2/* ldc2_w */, 1/* iload */, 2/* lload */, 1/* fload */, 2/* dload */, + 1/* aload */, 1/* iload_0 */, 1/* iload_1 */, 1/* iload_2 */, 1/* iload_3 */, 2/* lload_0 */, 2/* lload_1 */, 2/* lload_2 */, 2/* lload_3 */, + 1/* fload_0 */, 1/* fload_1 */, 1/* fload_2 */, 1/* fload_3 */, 2/* dload_0 */, 2/* dload_1 */, 2/* dload_2 */, 2/* dload_3 */, 1/* aload_0 */, + 1/* aload_1 */, 1/* aload_2 */, 1/* aload_3 */, 1/* iaload */, 2/* laload */, 1/* faload */, 2/* daload */, 1/* aaload */, 1/* baload */, + 1/* caload */, 1/* saload */, 0/* istore */, 0/* lstore */, 0/* fstore */, 0/* dstore */, 0/* astore */, 0/* istore_0 */, 0/* istore_1 */, + 0/* istore_2 */, 0/* istore_3 */, 0/* lstore_0 */, 0/* lstore_1 */, 0/* lstore_2 */, 0/* lstore_3 */, 0/* fstore_0 */, 0/* fstore_1 */, + 0/* fstore_2 */, 0/* fstore_3 */, 0/* dstore_0 */, 0/* dstore_1 */, 0/* dstore_2 */, 0/* dstore_3 */, 0/* astore_0 */, 0/* astore_1 */, + 0/* astore_2 */, 0/* astore_3 */, 0/* iastore */, 0/* lastore */, 0/* fastore */, 0/* dastore */, 0/* aastore */, 0/* bastore */, 0/* castore */, + 0/* sastore */, 0/* pop */, 0/* pop2 */, 2/* dup */, 3/* dup_x1 */, 4/* dup_x2 */, 4/* dup2 */, 5/* dup2_x1 */, 6/* dup2_x2 */, 2/* swap */, + 1/* iadd */, 2/* ladd */, 1/* fadd */, 2/* dadd */, 1/* isub */, 2/* lsub */, 1/* fsub */, 2/* dsub */, 1/* imul */, 2/* lmul */, 1/* fmul */, + 2/* dmul */, 1/* idiv */, 2/* ldiv */, 1/* fdiv */, 2/* ddiv */, 1/* irem */, 2/* lrem */, 1/* frem */, 2/* drem */, 1/* ineg */, 2/* lneg */, + 1/* fneg */, 2/* dneg */, 1/* ishl */, 2/* lshl */, 1/* ishr */, 2/* lshr */, 1/* iushr */, 2/* lushr */, 1/* iand */, 2/* land */, 1/* ior */, + 2/* lor */, 1/* ixor */, 2/* lxor */, 0/* iinc */, 2/* i2l */, 1/* i2f */, 2/* i2d */, 1/* l2i */, 1/* l2f */, 2/* l2d */, 1/* f2i */, 2/* f2l */, + 2/* f2d */, 1/* d2i */, 2/* d2l */, 1/* d2f */, 1/* i2b */, 1/* i2c */, 1/* i2s */, 1/* lcmp */, 1/* fcmpl */, 1/* fcmpg */, 1/* dcmpl */, + 1/* dcmpg */, 0/* ifeq */, 0/* ifne */, 0/* iflt */, 0/* ifge */, 0/* ifgt */, 0/* ifle */, 0/* if_icmpeq */, 0/* if_icmpne */, 0/* if_icmplt */, + 0/* if_icmpge */, 0/* if_icmpgt */, 0/* if_icmple */, 0/* if_acmpeq */, 0/* if_acmpne */, 0/* goto */, 1/* jsr */, 0/* ret */, 0/* tableswitch */, + 0/* lookupswitch */, 0/* ireturn */, 0/* lreturn */, 0/* freturn */, 0/* dreturn */, 0/* areturn */, 0/* return */, UNPREDICTABLE/* getstatic */, + 0/* putstatic */, UNPREDICTABLE/* getfield */, 0/* putfield */, UNPREDICTABLE/* invokevirtual */, UNPREDICTABLE/* invokespecial */, + UNPREDICTABLE/* invokestatic */, UNPREDICTABLE/* invokeinterface */, UNPREDICTABLE/* invokedynamic */, 1/* new */, 1/* newarray */, + 1/* anewarray */, 1/* arraylength */, 1/* athrow */, 1/* checkcast */, 1/* instanceof */, 0/* monitorenter */, 0/* monitorexit */, 0/* wide */, + 1/* multianewarray */, 0/* ifnull */, 0/* ifnonnull */, 0/* goto_w */, 1/* jsr_w */, 0/* breakpoint */, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, + UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNPREDICTABLE/* impdep1 */, UNPREDICTABLE/* impdep2 */ }; /** @@ -3092,111 +3118,219 @@ public final class Const { */ public static final byte ATTR_UNKNOWN = -1; + /** Attribute constant for SourceFile. */ public static final byte ATTR_SOURCE_FILE = 0; + /** Attribute constant for ConstantValue. */ public static final byte ATTR_CONSTANT_VALUE = 1; + /** Attribute constant for Code. */ public static final byte ATTR_CODE = 2; + /** Attribute constant for Exceptions. */ public static final byte ATTR_EXCEPTIONS = 3; + /** Attribute constant for LineNumberTable. */ public static final byte ATTR_LINE_NUMBER_TABLE = 4; + /** Attribute constant for LocalVariableTable. */ public static final byte ATTR_LOCAL_VARIABLE_TABLE = 5; + /** Attribute constant for InnerClasses. */ public static final byte ATTR_INNER_CLASSES = 6; + /** Attribute constant for Synthetic. */ public static final byte ATTR_SYNTHETIC = 7; + /** + * Attribute constant for Deprecated. + * + * @see JVM Specification: The Deprecated Attribute + */ public static final byte ATTR_DEPRECATED = 8; + /** Attribute constant for PMG. */ public static final byte ATTR_PMG = 9; + /** Attribute constant for Signature. */ public static final byte ATTR_SIGNATURE = 10; + /** Attribute constant for StackMap. */ public static final byte ATTR_STACK_MAP = 11; + + /** Attribute constant for RuntimeVisibleAnnotations. */ public static final byte ATTR_RUNTIME_VISIBLE_ANNOTATIONS = 12; + + /** Attribute constant for RuntimeInvisibleAnnotations. */ public static final byte ATTR_RUNTIME_INVISIBLE_ANNOTATIONS = 13; + + /** Attribute constant for RuntimeVisibleParameterAnnotations. */ public static final byte ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = 14; + + /** Attribute constant for RuntimeInvisibleParameterAnnotations. */ public static final byte ATTR_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = 15; + + /** Attribute constant for AnnotationDefault. */ public static final byte ATTR_ANNOTATION_DEFAULT = 16; + + /** Attribute constant for LocalVariableTypeTable. */ public static final byte ATTR_LOCAL_VARIABLE_TYPE_TABLE = 17; + + /** Attribute constant for EnclosingMethod. */ public static final byte ATTR_ENCLOSING_METHOD = 18; + + /** Attribute constant for StackMapTable. */ public static final byte ATTR_STACK_MAP_TABLE = 19; + + /** Attribute constant for BootstrapMethods. */ public static final byte ATTR_BOOTSTRAP_METHODS = 20; + + /** Attribute constant for MethodParameters. */ public static final byte ATTR_METHOD_PARAMETERS = 21; + + /** Attribute constant for Module. */ public static final byte ATTR_MODULE = 22; + + /** Attribute constant for ModulePackages. */ public static final byte ATTR_MODULE_PACKAGES = 23; + + /** Attribute constant for ModuleMainClass. */ public static final byte ATTR_MODULE_MAIN_CLASS = 24; + + /** Attribute constant for NestHost. */ public static final byte ATTR_NEST_HOST = 25; + + /** Attribute constant for NestMembers. */ public static final byte ATTR_NEST_MEMBERS = 26; + + /** Attribute constant for Record. */ public static final byte ATTR_RECORD = 27; - public static final short KNOWN_ATTRIBUTES = 28; // count of attributes - private static final String[] ATTRIBUTE_NAMES = {"SourceFile", "ConstantValue", "Code", "Exceptions", "LineNumberTable", "LocalVariableTable", - "InnerClasses", "Synthetic", "Deprecated", "PMGClass", "Signature", "StackMap", "RuntimeVisibleAnnotations", "RuntimeInvisibleAnnotations", - "RuntimeVisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "AnnotationDefault", "LocalVariableTypeTable", "EnclosingMethod", - "StackMapTable", "BootstrapMethods", "MethodParameters", "Module", "ModulePackages", "ModuleMainClass", "NestHost", "NestMembers", "Record"}; + /** + * Attribute constant for PermittedSubclasses. + * + * @since 6.13.0 + */ + public static final byte ATTR_PERMITTED_SUBCLASSES = 28; + + /** Count of known attributes. */ + public static final short KNOWN_ATTRIBUTES = 29; // count of attributes + + private static final String[] ATTRIBUTE_NAMES = { "SourceFile", "ConstantValue", "Code", "Exceptions", "LineNumberTable", "LocalVariableTable", + "InnerClasses", "Synthetic", "Deprecated", "PMGClass", "Signature", "StackMap", "RuntimeVisibleAnnotations", "RuntimeInvisibleAnnotations", + "RuntimeVisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "AnnotationDefault", "LocalVariableTypeTable", "EnclosingMethod", + "StackMapTable", "BootstrapMethods", "MethodParameters", "Module", "ModulePackages", "ModuleMainClass", "NestHost", "NestMembers", "Record", + "PermittedSubclasses" }; + /** * Constants used in the StackMap attribute. */ + /** Item type: Bogus. */ public static final byte ITEM_Bogus = 0; + + /** Item type: Integer. */ public static final byte ITEM_Integer = 1; + + /** Item type: Float. */ public static final byte ITEM_Float = 2; + + /** Item type: Double. */ public static final byte ITEM_Double = 3; + + /** Item type: Long. */ public static final byte ITEM_Long = 4; + + /** Item type: Null. */ public static final byte ITEM_Null = 5; + + /** Item type: InitObject. */ public static final byte ITEM_InitObject = 6; + + /** Item type: Object. */ public static final byte ITEM_Object = 7; + + /** Item type: NewObject. */ public static final byte ITEM_NewObject = 8; - private static final String[] ITEM_NAMES = {"Bogus", "Integer", "Float", "Double", "Long", "Null", "InitObject", "Object", "NewObject"}; + + private static final String[] ITEM_NAMES = { "Bogus", "Integer", "Float", "Double", "Long", "Null", "InitObject", "Object", "NewObject" }; /** - * Constants used to identify StackMapEntry types. - * - * For those types which can specify a range, the constant names the lowest value. + * Constants used to identify StackMapEntry types. For those types which can specify a range, the constant names the lowest value. */ + /** StackMapEntry type: SAME_FRAME. */ public static final int SAME_FRAME = 0; + /** StackMapEntry type: SAME_LOCALS_1_STACK_ITEM_FRAME. */ public static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; + /** StackMapEntry type: SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED. */ public static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; + /** StackMapEntry type: CHOP_FRAME. */ public static final int CHOP_FRAME = 248; + + /** StackMapEntry type: SAME_FRAME_EXTENDED. */ public static final int SAME_FRAME_EXTENDED = 251; + + /** StackMapEntry type: APPEND_FRAME. */ public static final int APPEND_FRAME = 252; + + /** StackMapEntry type: FULL_FRAME. */ public static final int FULL_FRAME = 255; /** * Constants that define the maximum value of those constants which store ranges. */ - + /** Maximum value for SAME_FRAME. */ public static final int SAME_FRAME_MAX = 63; + + /** Maximum value for SAME_LOCALS_1_STACK_ITEM_FRAME. */ public static final int SAME_LOCALS_1_STACK_ITEM_FRAME_MAX = 127; + + /** Maximum value for CHOP_FRAME. */ public static final int CHOP_FRAME_MAX = 250; + + /** Maximum value for APPEND_FRAME. */ public static final int APPEND_FRAME_MAX = 254; + + /** Reference kind: getField. */ public static final byte REF_getField = 1; + /** Reference kind: getStatic. */ public static final byte REF_getStatic = 2; + /** Reference kind: putField. */ public static final byte REF_putField = 3; + /** Reference kind: putStatic. */ public static final byte REF_putStatic = 4; + + /** Reference kind: invokeVirtual. */ public static final byte REF_invokeVirtual = 5; + + /** Reference kind: invokeStatic. */ public static final byte REF_invokeStatic = 6; + + /** Reference kind: invokeSpecial. */ public static final byte REF_invokeSpecial = 7; + + /** Reference kind: newInvokeSpecial. */ public static final byte REF_newInvokeSpecial = 8; + + /** Reference kind: invokeInterface. */ public static final byte REF_invokeInterface = 9; /** * The names of the reference_kinds of a CONSTANT_MethodHandle_info. */ - private static final String[] METHODHANDLE_NAMES = {"", "getField", "getStatic", "putField", "putStatic", "invokeVirtual", "invokeStatic", "invokeSpecial", - "newInvokeSpecial", "invokeInterface"}; + private static final String[] METHODHANDLE_NAMES = { "", "getField", "getStatic", "putField", "putStatic", "invokeVirtual", "invokeStatic", "invokeSpecial", + "newInvokeSpecial", "invokeInterface" }; /** + * Gets the access name at the given index. + * * @param index index into {@code ACCESS_NAMES}. - * @return the ACCESS_NAMES entry at the given index + * @return The ACCESS_NAMES entry at the given index. * @since 6.0 */ public static String getAccessName(final int index) { @@ -3204,9 +3338,10 @@ public static String getAccessName(final int index) { } /** + * Gets the attribute name at the given index. * * @param index index into {@code ACCESS_NAMES}. - * @return the attribute name + * @return The attribute name. * @since 6.0 */ public static String getAttributeName(final int index) { @@ -3214,10 +3349,10 @@ public static String getAttributeName(final int index) { } /** - * The primitive class names corresponding to the T_XX constants, e.g., CLASS_TYPE_NAMES[T_INT] = "java.lang.Integer" + * The primitive class names corresponding to the T_XX constants, for example, CLASS_TYPE_NAMES[T_INT] = "java.lang.Integer". * * @param index index into {@code CLASS_TYPE_NAMES}. - * @return the class name + * @return The class name. * @since 6.0 */ public static String getClassTypeName(final int index) { @@ -3225,21 +3360,22 @@ public static String getClassTypeName(final int index) { } /** + * Gets the constant name at the given index. * * @param index index into {@code CONSTANT_NAMES}. - * @return the CONSTANT_NAMES entry at the given index + * @return The CONSTANT_NAMES entry at the given index. * @since 6.0 */ public static String getConstantName(final int index) { return CONSTANT_NAMES[index]; } - // Constants defining the behavior of the Method Handles (JVMS 5.4.3.5) /** + * Gets the number of words consumed on operand stack. * * @param index index into {@code CONSUME_STACK}. - * @return Number of words consumed on operand stack + * @return Number of words consumed on operand stack. * @since 6.0 */ public static int getConsumeStack(final int index) { @@ -3247,6 +3383,9 @@ public static int getConsumeStack(final int index) { } /** + * Gets the interfaces implemented by arrays. + * + * @return The interfaces implemented by arrays. * @since 6.0 */ public static Iterable getInterfacesImplementedByArrays() { @@ -3254,9 +3393,10 @@ public static Iterable getInterfacesImplementedByArrays() { } /** + * Gets the item name at the given index. * * @param index index into {@code ITEM_NAMES}. - * @return the item name + * @return The item name. * @since 6.0 */ public static String getItemName(final int index) { @@ -3264,9 +3404,10 @@ public static String getItemName(final int index) { } /** + * Gets the method handle name at the given index. * * @param index index into {@code METHODHANDLE_NAMES}. - * @return the method handle name + * @return The method handle name. * @since 6.0 */ public static String getMethodHandleName(final int index) { @@ -3274,9 +3415,10 @@ public static String getMethodHandleName(final int index) { } /** + * Gets the number of byte code operands. * * @param index index into {@code NO_OF_OPERANDS}. - * @return Number of byte code operands + * @return Number of byte code operands. * @since 6.0 */ public static short getNoOfOperands(final int index) { @@ -3284,6 +3426,10 @@ public static short getNoOfOperands(final int index) { } /** + * Gets the opcode name at the given index. + * + * @param index The index. + * @return The opcode name. * @since 6.0 */ public static String getOpcodeName(final int index) { @@ -3291,6 +3437,11 @@ public static String getOpcodeName(final int index) { } /** + * Gets the operand type. + * + * @param opcode The opcode. + * @param index The index. + * @return The operand type. * @since 6.0 */ public static short getOperandType(final int opcode, final int index) { @@ -3298,6 +3449,10 @@ public static short getOperandType(final int opcode, final int index) { } /** + * Gets the operand type count. + * + * @param opcode The opcode. + * @return The operand type count. * @since 6.0 */ public static long getOperandTypeCount(final int opcode) { @@ -3305,9 +3460,10 @@ public static long getOperandTypeCount(final int opcode) { } /** + * Gets the number of words produced onto operand stack. * - * @param index - * @return Number of words produced onto operand stack + * @param index The index. + * @return Number of words produced onto operand stack. * @since 6.0 */ public static int getProduceStack(final int index) { @@ -3315,9 +3471,10 @@ public static int getProduceStack(final int index) { } /** + * Gets the short type name at the given index. * - * @param index - * @return the short type name + * @param index The index. + * @return The short type name. * @since 6.0 */ public static String getShortTypeName(final int index) { @@ -3325,10 +3482,10 @@ public static String getShortTypeName(final int index) { } /** - * The primitive type names corresponding to the T_XX constants, e.g., TYPE_NAMES[T_INT] = "int" + * The primitive type names corresponding to the T_XX constants, for example, TYPE_NAMES[T_INT] = "int". * - * @param index - * @return the type name + * @param index The index. + * @return The type name. * @since 6.0 */ public static String getTypeName(final int index) { @@ -3337,5 +3494,4 @@ public static String getTypeName(final int index) { private Const() { } // not instantiable - } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/ExceptionConst.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/ExceptionConst.java index 89cf3f835daf..423110c33d35 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/ExceptionConst.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/ExceptionConst.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -26,16 +26,30 @@ * Exception constants. * * @since 6.0 (intended to replace the InstructionConstant interface) - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class ExceptionConst { /** * Enum corresponding to the various Exception Class arrays, used by - * {@link ExceptionConst#createExceptions(EXCS, Class...)} + * {@link ExceptionConst#createExceptions(EXCS, Class...)}. */ public enum EXCS { - EXCS_CLASS_AND_INTERFACE_RESOLUTION, EXCS_FIELD_AND_METHOD_RESOLUTION, EXCS_INTERFACE_METHOD_RESOLUTION, EXCS_STRING_RESOLUTION, EXCS_ARRAY_EXCEPTION, + + /** Exception class and interface resolution. */ + EXCS_CLASS_AND_INTERFACE_RESOLUTION, + + /** Exception field and method resolution. */ + EXCS_FIELD_AND_METHOD_RESOLUTION, + + /** Exception interface method resolution. */ + EXCS_INTERFACE_METHOD_RESOLUTION, + + /** Exception string resolution. */ + EXCS_STRING_RESOLUTION, + + /** Exception array exception. */ + EXCS_ARRAY_EXCEPTION, } /** @@ -52,34 +66,71 @@ public enum EXCS { * Super class of any linking exception (aka Linkage Error) */ public static final Class LINKING_EXCEPTION = LinkageError.class; + + /** Exception class: ClassCircularityError. */ + public static final Class CLASS_CIRCULARITY_ERROR = ClassCircularityError.class; + /** - * Linking Exceptions + * Linking Exceptions. */ - public static final Class CLASS_CIRCULARITY_ERROR = ClassCircularityError.class; + + /** Exception class: ClassFormatError. */ public static final Class CLASS_FORMAT_ERROR = ClassFormatError.class; + + /** Exception class: ExceptionInInitializerError. */ public static final Class EXCEPTION_IN_INITIALIZER_ERROR = ExceptionInInitializerError.class; + + /** Exception class: IncompatibleClassChangeError. */ public static final Class INCOMPATIBLE_CLASS_CHANGE_ERROR = IncompatibleClassChangeError.class; + + /** Exception class: AbstractMethodError. */ public static final Class ABSTRACT_METHOD_ERROR = AbstractMethodError.class; + + /** Exception class: IllegalAccessError. */ public static final Class ILLEGAL_ACCESS_ERROR = IllegalAccessError.class; + + /** Exception class: InstantiationError. */ public static final Class INSTANTIATION_ERROR = InstantiationError.class; + + /** Exception class: NoSuchFieldError. */ public static final Class NO_SUCH_FIELD_ERROR = NoSuchFieldError.class; + + /** Exception class: NoSuchMethodError. */ public static final Class NO_SUCH_METHOD_ERROR = NoSuchMethodError.class; + + /** Exception class: NoClassDefFoundError. */ public static final Class NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class; + + /** Exception class: UnsatisfiedLinkError. */ public static final Class UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class; + /** Exception class: VerifyError. */ public static final Class VERIFY_ERROR = VerifyError.class; /* UnsupportedClassVersionError is new in JDK 1.2 */ // public static final Class UnsupportedClassVersionError = UnsupportedClassVersionError.class; + + /** Exception class: NullPointerException. */ + public static final Class NULL_POINTER_EXCEPTION = NullPointerException.class; + /** - * Run-Time Exceptions + * Run-Time Exceptions. */ - public static final Class NULL_POINTER_EXCEPTION = NullPointerException.class; + + /** Exception class: ArrayIndexOutOfBoundsException. */ public static final Class ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class; + + /** Exception class: ArithmeticException. */ public static final Class ARITHMETIC_EXCEPTION = ArithmeticException.class; + + /** Exception class: NegativeArraySizeException. */ public static final Class NEGATIVE_ARRAY_SIZE_EXCEPTION = NegativeArraySizeException.class; + + /** Exception class: ClassCastException. */ public static final Class CLASS_CAST_EXCEPTION = ClassCastException.class; + /** Exception class: IllegalMonitorStateException. */ public static final Class ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class; + /** * Pre-defined exception arrays according to chapters 5.1-5.4 of the Java Virtual Machine Specification */ @@ -104,9 +155,9 @@ public enum EXCS { /** * Creates a copy of the specified Exception Class array combined with any additional Exception classes. * - * @param type the basic array type - * @param extraClasses additional classes, if any - * @return the merged array + * @param type The basic array type. + * @param extraClasses additional classes, if any. + * @return The merged array. */ public static Class[] createExceptions(final EXCS type, final Class... extraClasses) { switch (type) { @@ -129,4 +180,9 @@ public static Class[] createExceptions(final EXCS type, final Class... ext private static Class[] mergeExceptions(final Class[] input, final Class... extraClasses) { return Utils.arraysAppend(input, extraClasses); } + + /** Private constructor - utility class. */ + public ExceptionConst() { + } + } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Repository.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Repository.java index 10f6a1a8ff43..3106b29b3dcd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Repository.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/Repository.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -24,13 +24,13 @@ import com.sun.org.apache.bcel.internal.util.SyntheticRepository; /** - * The repository maintains informations about class interdependencies, e.g., whether a class is a sub-class of another. + * The repository maintains informations about class interdependencies, for example, whether a class is a sub-class of another. * Delegates actual class loading to SyntheticRepository with current class path by default. * * @see com.sun.org.apache.bcel.internal.util.Repository * @see SyntheticRepository * - * @LastModified: Sept 2025 + * @LastModified: Oct 2026 */ public abstract class Repository { @@ -39,7 +39,8 @@ public abstract class Repository { /** * Adds clazz to repository if there isn't an equally named class already in there. * - * @return old entry in repository + * @param clazz The class to add. + * @return old entry in repository. */ public static JavaClass addClass(final JavaClass clazz) { final JavaClass old = repository.findClass(clazz.getClassName()); @@ -55,74 +56,104 @@ public static void clearCache() { } /** + * Gets all interfaces implemented by the class. + * + * @param clazz The class. * @return all interfaces implemented by class and its super classes and the interfaces that those interfaces extend, * and so on. (Some people call this a transitive hull). - * @throws ClassNotFoundException if any of the class's superclasses or superinterfaces can't be found + * @throws ClassNotFoundException Thrown if any of the class's superclasses or superinterfaces can't be found. */ public static JavaClass[] getInterfaces(final JavaClass clazz) throws ClassNotFoundException { return clazz.getAllInterfaces(); } /** + * Gets all interfaces implemented by the class. + * + * @param className The class name. * @return all interfaces implemented by class and its super classes and the interfaces that extend those interfaces, - * and so on - * @throws ClassNotFoundException if the named class can't be found, or if any of its superclasses or superinterfaces - * can't be found + * and so on. + * @throws ClassNotFoundException Thrown if the named class can't be found, or if any of its superclasses or superinterfaces + * can't be found. */ public static JavaClass[] getInterfaces(final String className) throws ClassNotFoundException { return getInterfaces(lookupClass(className)); } /** - * @return currently used repository instance + * Gets the currently used repository instance. + * + * @return currently used repository instance. */ public static com.sun.org.apache.bcel.internal.util.Repository getRepository() { return repository; } /** - * @return list of super classes of clazz in ascending order, i.e., Object is always the last element - * @throws ClassNotFoundException if any of the superclasses can't be found + * Gets the list of super classes. + * + * @param clazz The class. + * @return list of super classes of clazz in ascending order, that is, Object is always the last element. + * @throws ClassNotFoundException Thrown if any of the superclasses can't be found. */ public static JavaClass[] getSuperClasses(final JavaClass clazz) throws ClassNotFoundException { return clazz.getSuperClasses(); } /** - * @return list of super classes of clazz in ascending order, i.e., Object is always the last element. - * @throws ClassNotFoundException if the named class or any of its superclasses can't be found + * Gets the list of super classes. + * + * @param className The class name. + * @return list of super classes of clazz in ascending order, that is, Object is always the last element. + * @throws ClassNotFoundException Thrown if the named class or any of its superclasses can't be found. */ public static JavaClass[] getSuperClasses(final String className) throws ClassNotFoundException { return getSuperClasses(lookupClass(className)); } /** - * @return true, if clazz is an implementation of interface inter - * @throws ClassNotFoundException if any superclasses or superinterfaces of clazz can't be found + * Tests if clazz is an implementation of interface inter. + * + * @param clazz The class to test. + * @param inter The interface. + * @return true, if clazz is an implementation of interface inter. + * @throws ClassNotFoundException Thrown if any superclasses or superinterfaces of clazz can't be found. */ public static boolean implementationOf(final JavaClass clazz, final JavaClass inter) throws ClassNotFoundException { return clazz.implementationOf(inter); } /** - * @return true, if clazz is an implementation of interface inter - * @throws ClassNotFoundException if inter or any superclasses or superinterfaces of clazz can't be found + * Tests if clazz is an implementation of interface inter. + * + * @param clazz The class to test. + * @param inter The interface name. + * @return true, if clazz is an implementation of interface inter. + * @throws ClassNotFoundException Thrown if inter or any superclasses or superinterfaces of clazz can't be found. */ public static boolean implementationOf(final JavaClass clazz, final String inter) throws ClassNotFoundException { return implementationOf(clazz, lookupClass(inter)); } /** - * @return true, if clazz is an implementation of interface inter - * @throws ClassNotFoundException if clazz or any superclasses or superinterfaces of clazz can't be found + * Tests if clazz is an implementation of interface inter. + * + * @param clazz The class name to test. + * @param inter The interface. + * @return true, if clazz is an implementation of interface inter. + * @throws ClassNotFoundException Thrown if clazz or any superclasses or superinterfaces of clazz can't be found. */ public static boolean implementationOf(final String clazz, final JavaClass inter) throws ClassNotFoundException { return implementationOf(lookupClass(clazz), inter); } /** - * @return true, if clazz is an implementation of interface inter - * @throws ClassNotFoundException if clazz, inter, or any superclasses or superinterfaces of clazz can't be found + * Tests if clazz is an implementation of interface inter. + * + * @param clazz The class name to test. + * @param inter The interface name. + * @return true, if clazz is an implementation of interface inter. + * @throws ClassNotFoundException Thrown if clazz, inter, or any superclasses or superinterfaces of clazz can't be found. */ public static boolean implementationOf(final String clazz, final String inter) throws ClassNotFoundException { return implementationOf(lookupClass(clazz), lookupClass(inter)); @@ -131,32 +162,46 @@ public static boolean implementationOf(final String clazz, final String inter) t /** * Equivalent to runtime "instanceof" operator. * - * @return true, if clazz is an instance of superclass - * @throws ClassNotFoundException if any superclasses or superinterfaces of clazz can't be found + * @param clazz The class to test. + * @param superclass The superclass. + * @return true, if clazz is an instance of superclass. + * @throws ClassNotFoundException Thrown if any superclasses or superinterfaces of clazz can't be found. */ public static boolean instanceOf(final JavaClass clazz, final JavaClass superclass) throws ClassNotFoundException { return clazz.instanceOf(superclass); } /** - * @return true, if clazz is an instance of superclass - * @throws ClassNotFoundException if superclass can't be found + * Tests if clazz is an instance of superclass. + * + * @param clazz The class to test. + * @param superclass The superclass name. + * @return true, if clazz is an instance of superclass. + * @throws ClassNotFoundException Thrown if superclass can't be found. */ public static boolean instanceOf(final JavaClass clazz, final String superclass) throws ClassNotFoundException { return instanceOf(clazz, lookupClass(superclass)); } /** - * @return true, if clazz is an instance of superclass - * @throws ClassNotFoundException if clazz can't be found + * Tests if clazz is an instance of superclass. + * + * @param clazz The class name to test. + * @param superclass The superclass. + * @return true, if clazz is an instance of superclass. + * @throws ClassNotFoundException Thrown if clazz can't be found. */ public static boolean instanceOf(final String clazz, final JavaClass superclass) throws ClassNotFoundException { return instanceOf(lookupClass(clazz), superclass); } /** - * @return true, if clazz is an instance of superclass - * @throws ClassNotFoundException if either clazz or superclass can't be found + * Tests if clazz is an instance of superclass. + * + * @param clazz The class name to test. + * @param superclass The superclass name. + * @return true, if clazz is an instance of superclass. + * @throws ClassNotFoundException Thrown if either clazz or superclass can't be found. */ public static boolean instanceOf(final String clazz, final String superclass) throws ClassNotFoundException { return instanceOf(lookupClass(clazz), lookupClass(superclass)); @@ -165,19 +210,21 @@ public static boolean instanceOf(final String clazz, final String superclass) th /** * Tries to find class source using the internal repository instance. * + * @param clazz The class. * @see Class - * @return JavaClass object for given runtime class - * @throws ClassNotFoundException if the class could not be found or parsed correctly + * @return JavaClass object for given runtime class. + * @throws ClassNotFoundException Thrown if the class could not be found or parsed correctly. */ public static JavaClass lookupClass(final Class clazz) throws ClassNotFoundException { return repository.loadClass(clazz); } /** - * Lookups class somewhere found on your CLASSPATH, or whereever the repository instance looks for it. + * Lookups class somewhere found on your CLASSPATH, or wherever the repository instance looks for it. * - * @return class object for given fully qualified class name - * @throws ClassNotFoundException if the class could not be found or parsed correctly + * @param className The class name. + * @return class object for given fully qualified class name. + * @throws ClassNotFoundException Thrown if the class could not be found or parsed correctly. */ public static JavaClass lookupClass(final String className) throws ClassNotFoundException { return repository.loadClass(className); @@ -185,6 +232,8 @@ public static JavaClass lookupClass(final String className) throws ClassNotFound /** * Removes given class from repository. + * + * @param clazz The class to remove. */ public static void removeClass(final JavaClass clazz) { repository.removeClass(clazz); @@ -192,15 +241,25 @@ public static void removeClass(final JavaClass clazz) { /** * Removes class with given (fully qualified) name from repository. + * + * @param clazz The class name to remove. */ public static void removeClass(final String clazz) { repository.removeClass(repository.findClass(clazz)); } /** - * Sets repository instance to be used for class loading + * Sets repository instance to be used for class loading. + * + * @param rep The repository instance. */ public static void setRepository(final com.sun.org.apache.bcel.internal.util.Repository rep) { repository = rep; } + + /** + * Constructs a new Repository. + */ + public Repository() { + } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AccessFlags.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AccessFlags.java index f1d350894c9b..f4ef52771d9c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AccessFlags.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AccessFlags.java @@ -22,10 +22,7 @@ import com.sun.org.apache.bcel.internal.Const; /** - * Super class for all objects that have modifiers like private, final, ... I.e. - * classes, fields, and methods. - * - * @LastModified: Sept 2025 + * Super class for all objects that have modifiers like private, final, ... I.e. classes, fields, and methods. */ public abstract class AccessFlags { @@ -105,6 +102,7 @@ public final boolean isAnnotation() { public final void isAnnotation(final boolean flag) { setFlag(Const.ACC_ANNOTATION, flag); } + /** * Tests whether the enum bit is on. * @@ -388,7 +386,7 @@ public final void setModifiers(final int accessFlags) { /** * Tests whether the bit is on. * - * @param test the bit to test. + * @param test The bit to test. * @return whether the bit is on. */ private boolean test(final short test) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationDefault.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationDefault.java index 40bbfb6eae0c..05191d9cfe86 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationDefault.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationDefault.java @@ -37,10 +37,10 @@ public class AnnotationDefault extends Attribute { private ElementValue defaultValue; /** - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. */ AnnotationDefault(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (ElementValue) null, constantPool); @@ -48,10 +48,12 @@ public class AnnotationDefault extends Attribute { } /** - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param defaultValue the annotation's default value - * @param constantPool Array of constants + * Constructs an AnnotationDefault attribute. + * + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param defaultValue The annotation's default value. + * @param constantPool Array of constants. */ public AnnotationDefault(final int nameIndex, final int length, final ElementValue defaultValue, final ConstantPool constantPool) { super(Const.ATTR_ANNOTATION_DEFAULT, nameIndex, length, constantPool); @@ -62,7 +64,7 @@ public AnnotationDefault(final int nameIndex, final int length, final ElementVal * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -81,14 +83,18 @@ public final void dump(final DataOutputStream dos) throws IOException { } /** - * @return the default value + * Gets the default value. + * + * @return The default value. */ public final ElementValue getDefaultValue() { return defaultValue; } /** - * @param defaultValue the default value of this methodinfo's annotation + * Sets the default value of this methodinfo's annotation. + * + * @param defaultValue The default value of this methodinfo's annotation. */ public final void setDefaultValue(final ElementValue defaultValue) { this.defaultValue = defaultValue; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationElementValue.java index 8d618258d532..03b54267fccc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationElementValue.java @@ -25,12 +25,21 @@ import java.io.IOException; /** + * Represents an annotation element value. + * * @since 6.0 */ public class AnnotationElementValue extends ElementValue { // For annotation element values, this is the annotation private final AnnotationEntry annotationEntry; + /** + * Constructs an AnnotationElementValue. + * + * @param type The type. + * @param annotationEntry The annotation entry. + * @param cpool The constant pool. + */ public AnnotationElementValue(final int type, final AnnotationEntry annotationEntry, final ConstantPool cpool) { super(type, cpool); if (type != ANNOTATION) { @@ -45,6 +54,11 @@ public void dump(final DataOutputStream dos) throws IOException { annotationEntry.dump(dos); } + /** + * Gets the annotation entry. + * + * @return The annotation entry. + */ public AnnotationEntry getAnnotationEntry() { return annotationEntry; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationEntry.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationEntry.java index c9503332a6f4..5192fb562d39 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationEntry.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AnnotationEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -26,18 +26,29 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; + +import com.sun.org.apache.bcel.internal.util.Args; import jdk.xml.internal.Utils; /** * Represents one annotation in the annotation table * * @since 6.0 - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class AnnotationEntry implements Node { + /** + * Empty array of AnnotationEntry objects. + */ public static final AnnotationEntry[] EMPTY_ARRAY = {}; + /** + * Creates annotation entries from attributes. + * + * @param attributes The attributes. + * @return The annotation entries. + */ public static AnnotationEntry[] createAnnotationEntries(final Attribute[] attributes) { // Find attributes that contain annotation data return Utils.streamOfIfNonNull(attributes).filter(Annotations.class::isInstance).flatMap(e -> Stream.of(((Annotations) e).getAnnotationEntries())) @@ -45,20 +56,36 @@ public static AnnotationEntry[] createAnnotationEntries(final Attribute[] attrib } /** - * Factory method to create an AnnotionEntry from a DataInput + * Factory method to create an AnnotionEntry from a DataInput. * - * @param input - * @param constantPool - * @param isRuntimeVisible - * @return the entry - * @throws IOException if an I/O error occurs. + * @param input The input stream. + * @param constantPool The constant pool. + * @param isRuntimeVisible whether the annotation is runtime visible. + * @return The entry. + * @throws IOException Thrown if an I/O error occurs. */ public static AnnotationEntry read(final DataInput input, final ConstantPool constantPool, final boolean isRuntimeVisible) throws IOException { + return read(input, constantPool, isRuntimeVisible, 0); + } + + /** + * Factory method to create an AnnotionEntry from a DataInput, carrying the nesting depth of the enclosing element values so that + * {@link ElementValue#readElementValue(DataInput, ConstantPool, boolean, int)} can bound the combined annotation/array nesting depth. + * + * @param input The input stream. + * @param constantPool The constant pool. + * @param isRuntimeVisible whether the annotation is runtime visible. + * @param nesting the current element value nesting level. + * @return The entry. + * @throws IOException Thrown if an I/O error occurs. + */ + static AnnotationEntry read(final DataInput input, final ConstantPool constantPool, final boolean isRuntimeVisible, final int nesting) + throws IOException { final AnnotationEntry annotationEntry = new AnnotationEntry(input.readUnsignedShort(), constantPool, isRuntimeVisible); final int numElementValuePairs = input.readUnsignedShort(); for (int i = 0; i < numElementValuePairs; i++) { - annotationEntry.elementValuePairs - .add(new ElementValuePair(input.readUnsignedShort(), ElementValue.readElementValue(input, constantPool), constantPool)); + annotationEntry.elementValuePairs.add( + new ElementValuePair(input.readUnsignedShort(), ElementValue.readElementValue(input, constantPool, isRuntimeVisible, nesting), constantPool)); } return annotationEntry; } @@ -71,6 +98,13 @@ public static AnnotationEntry read(final DataInput input, final ConstantPool con private final List elementValuePairs; + /** + * Constructs an AnnotationEntry. + * + * @param typeIndex The type index. + * @param constantPool The constant pool. + * @param isRuntimeVisible whether the annotation is runtime visible. + */ public AnnotationEntry(final int typeIndex, final ConstantPool constantPool, final boolean isRuntimeVisible) { this.typeIndex = typeIndex; this.constantPool = constantPool; @@ -82,20 +116,31 @@ public AnnotationEntry(final int typeIndex, final ConstantPool constantPool, fin * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { v.visitAnnotationEntry(this); } + /** + * Adds an element name value pair. + * + * @param elementNameValuePair The element name value pair. + */ public void addElementNameValuePair(final ElementValuePair elementNameValuePair) { elementValuePairs.add(elementNameValuePair); } + /** + * Dumps this annotation entry to a DataOutputStream. + * + * @param dos The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(typeIndex); // u2 index of type name in cpool - dos.writeShort(elementValuePairs.size()); // u2 element_value pair + dos.writeShort(Args.requireU2(elementValuePairs.size(), "elementValuePairs.size()")); // u2 element_value pair // count for (final ElementValuePair envp : elementValuePairs) { envp.dump(dos); @@ -103,25 +148,36 @@ public void dump(final DataOutputStream dos) throws IOException { } /** - * @return the annotation type name + * Gets the annotation type name. + * + * @return The annotation type name. */ public String getAnnotationType() { return constantPool.getConstantUtf8(typeIndex).getBytes(); } /** - * @return the annotation type index + * Gets the annotation type index. + * + * @return The annotation type index. */ public int getAnnotationTypeIndex() { return typeIndex; } + /** + * Gets the constant pool. + * + * @return The constant pool. + */ public ConstantPool getConstantPool() { return constantPool; } /** - * @return the element value pairs in this annotation entry + * Gets the element value pairs in this annotation entry. + * + * @return The element value pairs in this annotation entry. */ public ElementValuePair[] getElementValuePairs() { // TODO return List @@ -129,20 +185,37 @@ public ElementValuePair[] getElementValuePairs() { } /** - * @return the number of element value pairs in this annotation entry + * Gets the number of element value pairs in this annotation entry. + * + * @return The number of element value pairs in this annotation entry. */ public final int getNumElementValuePairs() { return elementValuePairs.size(); } + /** + * Gets the type index. + * + * @return The type index. + */ public int getTypeIndex() { return typeIndex; } + /** + * Gets whether this annotation is runtime visible. + * + * @return true if this annotation is runtime visible. + */ public boolean isRuntimeVisible() { return isRuntimeVisible; } + /** + * Gets a short string representation of this annotation. + * + * @return A short string representation of this annotation. + */ public String toShortString() { final StringBuilder result = new StringBuilder(); result.append("@"); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Annotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Annotations.java index 6ff9b4a046f0..20776cd749d8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Annotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Annotations.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * base class for annotations @@ -42,12 +43,12 @@ public abstract class Annotations extends Attribute implements IterableCode - * @param length Content length in bytes - * @param annotationTable the actual annotations - * @param constantPool Array of constants - * @param isRuntimeVisible whether this Annotation visible at runtime + * @param annotationType The subclass type of the annotation. + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param annotationTable The actual annotations. + * @param constantPool Array of constants. + * @param isRuntimeVisible whether this Annotation visible at runtime. */ public Annotations(final byte annotationType, final int nameIndex, final int length, final AnnotationEntry[] annotationTable, final ConstantPool constantPool, final boolean isRuntimeVisible) { @@ -59,13 +60,13 @@ public Annotations(final byte annotationType, final int nameIndex, final int len /** * Constructs an instance. * - * @param annotationType the subclass type of the annotation - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @param isRuntimeVisible whether this Annotation visible at runtime - * @throws IOException if an I/O error occurs. + * @param annotationType The subclass type of the annotation. + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @param isRuntimeVisible whether this Annotation visible at runtime. + * @throws IOException Thrown if an I/O error occurs. */ Annotations(final byte annotationType, final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool, final boolean isRuntimeVisible) throws IOException { @@ -82,7 +83,7 @@ public Annotations(final byte annotationType, final int nameIndex, final int len * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -96,7 +97,9 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Gets the array of annotation entries in this annotation + * Gets the array of annotation entries in this annotation. + * + * @return The array of annotation entries in this annotation. */ public AnnotationEntry[] getAnnotationEntries() { return annotationTable; @@ -105,12 +108,17 @@ public AnnotationEntry[] getAnnotationEntries() { /** * Gets the number of annotation entries in this annotation. * - * @return the number of annotation entries in this annotation + * @return The number of annotation entries in this annotation. */ public final int getNumAnnotations() { return annotationTable.length; } + /** + * Gets whether this annotation is runtime visible. + * + * @return true if this annotation is runtime visible. + */ public boolean isRuntimeVisible() { return isRuntimeVisible; } @@ -123,7 +131,7 @@ public Iterator iterator() { /** * Sets the entries to set in this annotation. * - * @param annotationTable the entries to set in this annotation + * @param annotationTable The entries to set in this annotation. */ public final void setAnnotationTable(final AnnotationEntry[] annotationTable) { this.annotationTable = annotationTable != null ? annotationTable : AnnotationEntry.EMPTY_ARRAY; @@ -132,7 +140,7 @@ public final void setAnnotationTable(final AnnotationEntry[] annotationTable) { /** * Converts to a String representation. * - * @return String representation + * @return String representation. */ @Override public final String toString() { @@ -147,8 +155,14 @@ public final String toString() { return buf.toString(); } + /** + * Writes the annotations to a DataOutputStream. + * + * @param dos The data output stream. + * @throws IOException Thrown if an I/O error occurs. + */ protected void writeAnnotations(final DataOutputStream dos) throws IOException { - dos.writeShort(annotationTable.length); + dos.writeShort(Args.requireU2(annotationTable.length, "annotationTable.length")); for (final AnnotationEntry element : annotationTable) { element.dump(dos); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ArrayElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ArrayElementValue.java index 35d0412f57a1..447fd4322585 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ArrayElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ArrayElementValue.java @@ -24,13 +24,24 @@ import java.io.DataOutputStream; import java.io.IOException; +import com.sun.org.apache.bcel.internal.util.Args; + /** + * Represents an array element value in an annotation. + * * @since 6.0 */ public class ArrayElementValue extends ElementValue { // For array types, this is the array private final ElementValue[] elementValues; + /** + * Constructs an ArrayElementValue. + * + * @param type The type. + * @param elementValues The element values. + * @param cpool The constant pool. + */ public ArrayElementValue(final int type, final ElementValue[] elementValues, final ConstantPool cpool) { super(type, cpool); if (type != ARRAY) { @@ -42,16 +53,26 @@ public ArrayElementValue(final int type, final ElementValue[] elementValues, fin @Override public void dump(final DataOutputStream dos) throws IOException { dos.writeByte(super.getType()); // u1 type of value (ARRAY == '[') - dos.writeShort(elementValues.length); + dos.writeShort(Args.requireU2(elementValues.length, "elementValues.length")); for (final ElementValue evalue : elementValues) { evalue.dump(dos); } } + /** + * Gets the element values array. + * + * @return The element values array. + */ public ElementValue[] getElementValuesArray() { return elementValues; } + /** + * Gets the element values array size. + * + * @return The element values array size. + */ public int getElementValuesArraySize() { return elementValues.length; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Attribute.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Attribute.java index cd03615cbc0f..d1e512760614 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Attribute.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Attribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -41,6 +41,12 @@ * u1 info[attribute_length]; * } *
+ *

+ * The default maximum number of attribute nesting levels in {@link #readAttribute(DataInput, ConstantPool)} is {@code 64} before throwing a + * {@link ClassFormatException}. Attributes may + * legitimately nest (for example, a Code attribute carries its own attribute table, and Record components carry theirs), but a malicious + * class file can nest such attributes deeply enough to overflow the parser's stack. + *

* * @see ConstantValue * @see SourceFile @@ -53,10 +59,23 @@ * @see Synthetic * @see Deprecated * @see Signature - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public abstract class Attribute implements Cloneable, Node { - private static final boolean debug = false; + + private static final boolean debug = false; // Debugging on/off + + /** + * Limits recursive attribute parsing in readAttribute() to prevent + * stack overflow when reading deeply nested class-file attributes. + * XSLTC's generation of attributes does not use this parsing path. + */ + private static final int MAX_NESTING_DEPTH = 64; + + /** + * The per-thread attribute nesting depth of {@link #readAttribute(DataInput, ConstantPool)}. + */ + private static final ThreadLocal NESTING_DEPTH = ThreadLocal.withInitial(() -> Integer.valueOf(0)); private static final Map READERS = new HashMap<>(); @@ -78,6 +97,11 @@ public static void addAttributeReader(final String name, final UnknownAttributeR READERS.put(name, unknownAttributeReader); } + /** + * Prints a message to stderr if debug mode is enabled. + * + * @param msg The message to print. + */ protected static void println(final String msg) { if (debug) { System.err.println(msg); @@ -90,14 +114,51 @@ protected static void println(final String msg) { * * @see Field * @see Method - * - * @param dataInput Input stream - * @param constantPool Array of constants - * @return Attribute - * @throws IOException if an I/O error occurs. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @return Attribute. + * @throws IOException Thrown if an I/O error occurs. * @since 6.0 */ public static Attribute readAttribute(final DataInput dataInput, final ConstantPool constantPool) throws IOException { + // Track the nesting depth to guard against malicious class files that nest attributes (for example, a Code attribute inside a Code attribute, or + // mutually recursive Record component attributes) deeply enough to overflow the parser's stack (CWE-674). + final int depth = NESTING_DEPTH.get().intValue() + 1; + if (depth > MAX_NESTING_DEPTH) { + throw new ClassFormatException("Attributes are nested more than " + MAX_NESTING_DEPTH + " levels deep; if this is a valid class file, raise the" + + " limit with the system property " + Attribute.class.getCanonicalName() + ".maxNestingDepth."); + } + NESTING_DEPTH.set(Integer.valueOf(depth)); + try { + return readAttribute0(dataInput, constantPool); + } finally { + if (depth == 1) { + NESTING_DEPTH.remove(); + } else { + NESTING_DEPTH.set(Integer.valueOf(depth - 1)); + } + } + } + + /** + * Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It + * is called by the Field and Method constructor methods. + * + * @see Field + * @see Method + * @param dataInputStream Input stream. + * @param constantPool Array of constants. + * @return Attribute. + * @throws IOException Thrown if an I/O error occurs. + */ + public static Attribute readAttribute(final DataInputStream dataInputStream, final ConstantPool constantPool) throws IOException { + return readAttribute((DataInput) dataInputStream, constantPool); + } + + /** + * Reads one attribute without tracking the nesting depth; only to be called by {@link #readAttribute(DataInput, ConstantPool)}. + */ + private static Attribute readAttribute0(final DataInput dataInput, final ConstantPool constantPool) throws IOException { byte tag = Const.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via 'name_index' indirection final int nameIndex = dataInput.readUnsignedShort(); @@ -183,60 +244,46 @@ public static Attribute readAttribute(final DataInput dataInput, final ConstantP return new NestMembers(nameIndex, length, dataInput, constantPool); case Const.ATTR_RECORD: return new Record(nameIndex, length, dataInput, constantPool); + case Const.ATTR_PERMITTED_SUBCLASSES: + return new PermittedSubclasses(nameIndex, length, dataInput, constantPool); default: // Never reached throw new IllegalStateException("Unrecognized attribute type tag parsed: " + tag); } } - /** - * Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It - * is called by the Field and Method constructor methods. - * - * @see Field - * @see Method - * - * @param dataInputStream Input stream - * @param constantPool Array of constants - * @return Attribute - * @throws IOException if an I/O error occurs. - */ - public static Attribute readAttribute(final DataInputStream dataInputStream, final ConstantPool constantPool) throws IOException { - return readAttribute((DataInput) dataInputStream, constantPool); - } - /** * Remove attribute reader * - * @param name the name of the attribute as stored in the class file + * @param name The name of the attribute as stored in the class file. */ public static void removeAttributeReader(final String name) { READERS.remove(name); } /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected int name_index; // Points to attribute name in constant pool TODO make private (has getter & setter) /** - * @deprecated (since 6.0) (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated - protected int length; // Content length of attribute field TODO make private (has getter & setter) + protected int length; // Content length of attribute field TODO make private (has getter & setter). /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated - protected byte tag; // Tag to distinguish subclasses TODO make private & final; supposed to be immutable + protected byte tag; // Tag to distinguish subclasses TODO make private & final; supposed to be immutable. /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated - protected ConstantPool constant_pool; // TODO make private (has getter & setter) + protected ConstantPool constant_pool; // TODO make private (has getter & setter). /** * Constructs an instance. @@ -265,15 +312,15 @@ protected Attribute(final byte tag, final int nameIndex, final int length, final * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public abstract void accept(Visitor v); /** - * Use copy() if you want to have a deep copy(), i.e., with all references copied correctly. + * Use copy() if you want to have a deep copy(), that is, with all references copied correctly. * - * @return shallow copy of this attribute + * @return shallow copy of this attribute. */ @Override public Object clone() { @@ -287,6 +334,8 @@ public Object clone() { } /** + * Creates a deep copy of this attribute. + * * @param constantPool constant pool to save. * @return deep copy of this attribute. */ @@ -295,8 +344,8 @@ public Object clone() { /** * Dumps attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(name_index); @@ -304,6 +353,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the constant pool used by this object. + * * @return Constant pool used by this object. * @see ConstantPool */ @@ -312,6 +363,8 @@ public final ConstantPool getConstantPool() { } /** + * Gets the length of attribute field in bytes. + * * @return Length of attribute field in bytes. */ public final int getLength() { @@ -319,7 +372,9 @@ public final int getLength() { } /** - * @return Name of attribute + * Gets the name of attribute. + * + * @return Name of attribute. * @since 6.0 */ public String getName() { @@ -327,6 +382,8 @@ public String getName() { } /** + * Gets the name index in constant pool of attribute name. + * * @return Name index in constant pool of attribute name. */ public final int getNameIndex() { @@ -334,13 +391,17 @@ public final int getNameIndex() { } /** - * @return Tag of attribute, i.e., its type. Value may not be altered, thus there is no setTag() method. + * Gets the tag of attribute, that is, its type. + * + * @return Tag of attribute, that is, its type. Value may not be altered, thus there is no setTag() method. */ public final byte getTag() { return tag; } /** + * Sets the constant pool to be used for this object. + * * @param constantPool Constant pool to be used for this object. * @see ConstantPool */ @@ -349,6 +410,8 @@ public final void setConstantPool(final ConstantPool constantPool) { } /** + * Sets the length in bytes. + * * @param length length in bytes. */ public final void setLength(final int length) { @@ -356,6 +419,8 @@ public final void setLength(final int length) { } /** + * Sets the name index of attribute. + * * @param nameIndex of attribute. */ public final void setNameIndex(final int nameIndex) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AttributeReader.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AttributeReader.java index 6d4891f953f1..b90a88ddf79e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AttributeReader.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/AttributeReader.java @@ -26,8 +26,7 @@ * Attribute.addAttributeReader method. These factory objects should implement this interface. * * @see Attribute - * - * @deprecated Use UnknownAttributeReader instead + * @deprecated Use {@link UnknownAttributeReader} instead. */ @java.lang.Deprecated public interface AttributeReader { @@ -38,18 +37,14 @@ public interface AttributeReader { * name of the attributes it is constructing. * * @param nameIndex An index into the constant pool, indexing a ConstantUtf8 that represents the name of the attribute. - * * @param length The length of the data contained in the attribute. This is written into the constant pool and should * agree with what the factory expects the length to be. - * * @param file This is the data input stream that the factory needs to read its data from. - * * @param constantPool This is the constant pool associated with the Attribute that we are constructing. - * * @return The user-defined AttributeReader should take this data and use it to construct an attribute. In the case of * errors, a null can be returned which will cause the parsing of the class file to fail. * - * @see Attribute#addAttributeReader( String, AttributeReader ) + * @see Attribute#addAttributeReader(String,AttributeReader) */ Attribute createAttribute(int nameIndex, int length, java.io.DataInputStream file, ConstantPool constantPool); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethod.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethod.java index 224e0df6b940..44934f755e8b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethod.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -26,16 +26,17 @@ import java.util.Arrays; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; import jdk.xml.internal.Utils; /** - * This class represents a bootstrap method attribute, i.e., the bootstrap method ref, the number of bootstrap arguments + * This class represents a bootstrap method attribute, that is, the bootstrap method ref, the number of bootstrap arguments * and an array of the bootstrap arguments. * * @see The class File Format : * The BootstrapMethods Attribute * @since 6.0 - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class BootstrapMethod implements Cloneable { @@ -53,14 +54,14 @@ public class BootstrapMethod implements Cloneable { * @param c Source to copy. */ public BootstrapMethod(final BootstrapMethod c) { - this(c.getBootstrapMethodRef(), c.getBootstrapArguments()); + this(c.getBootstrapMethodRef(), c.getBootstrapArguments().clone()); } /** * Constructs object from input stream. * - * @param input Input stream - * @throws IOException if an I/O error occurs. + * @param input Input stream. + * @throws IOException Thrown if an I/O error occurs. */ BootstrapMethod(final DataInput input) throws IOException { this(input.readUnsignedShort(), input.readUnsignedShort()); @@ -76,8 +77,10 @@ private BootstrapMethod(final int bootstrapMethodRef, final int numBootstrapArgu } /** - * @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle - * @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info + * Constructs a BootstrapMethod. + * + * @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle. + * @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info. */ public BootstrapMethod(final int bootstrapMethodRef, final int[] bootstrapArguments) { this.bootstrapMethodRef = bootstrapMethodRef; @@ -85,11 +88,15 @@ public BootstrapMethod(final int bootstrapMethodRef, final int[] bootstrapArgume } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public BootstrapMethod copy() { try { - return (BootstrapMethod) clone(); + final BootstrapMethod c = (BootstrapMethod) clone(); + c.bootstrapArguments = bootstrapArguments.clone(); + return c; } catch (final CloneNotSupportedException ignore) { // TODO should this throw? } @@ -97,55 +104,67 @@ public BootstrapMethod copy() { } /** - * Dump object to file stream in binary format. + * Dumps object to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public final void dump(final DataOutputStream file) throws IOException { file.writeShort(bootstrapMethodRef); - file.writeShort(bootstrapArguments.length); + file.writeShort(Args.requireU2(bootstrapArguments.length, "bootstrapArguments.length")); for (final int bootstrapArgument : bootstrapArguments) { file.writeShort(bootstrapArgument); } } /** - * @return int[] of bootstrap_method indices into constant_pool of CONSTANT_[type]_info + * Gets the bootstrap arguments. + * + * @return int[] of bootstrap_method indices into constant_pool of CONSTANT_[type]_info. */ public int[] getBootstrapArguments() { return bootstrapArguments; } /** - * @return index into constant_pool of bootstrap_method + * Gets the bootstrap method reference. + * + * @return index into constant_pool of bootstrap_method. */ public int getBootstrapMethodRef() { return bootstrapMethodRef; } /** - * @return count of number of boostrap arguments + * Gets the count of number of bootstrap arguments. + * + * @return count of number of bootstrap arguments. */ public int getNumBootstrapArguments() { return bootstrapArguments.length; } /** - * @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info + * Sets the bootstrap arguments. + * + * @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info. */ public void setBootstrapArguments(final int[] bootstrapArguments) { this.bootstrapArguments = Utils.createEmptyArrayIfNull(bootstrapArguments); } /** - * @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle + * Sets the bootstrap method reference. + * + * @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle. */ public void setBootstrapMethodRef(final int bootstrapMethodRef) { this.bootstrapMethodRef = bootstrapMethodRef; } /** + * Gets a string representation. + * * @return String representation. */ @Override @@ -154,7 +173,10 @@ public final String toString() { } /** - * @return Resolved string representation + * Gets a resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public final String toString(final ConstantPool constantPool) { final StringBuilder buf = new StringBuilder(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethods.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethods.java index ef2475e18569..b113de8867e8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethods.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/BootstrapMethods.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * This class represents a BootstrapMethods attribute. @@ -51,10 +52,12 @@ public BootstrapMethods(final BootstrapMethods c) { } /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param bootstrapMethods array of bootstrap methods - * @param constantPool Array of constants + * Constructs a BootstrapMethods attribute. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param bootstrapMethods array of bootstrap methods. + * @param constantPool Array of constants. */ public BootstrapMethods(final int nameIndex, final int length, final BootstrapMethod[] bootstrapMethods, final ConstantPool constantPool) { super(Const.ATTR_BOOTSTRAP_METHODS, nameIndex, length, constantPool); @@ -64,11 +67,11 @@ public BootstrapMethods(final int nameIndex, final int length, final BootstrapMe /** * Constructs object from Input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ BootstrapMethods(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (BootstrapMethod[]) null, constantPool); @@ -81,7 +84,9 @@ public BootstrapMethods(final int nameIndex, final int length, final BootstrapMe } /** - * @param v Visitor object + * Accepts a visitor. + * + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -89,7 +94,10 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * Creates a deep copy of this attribute. + * + * @param constantPool The constant pool. + * @return deep copy of this attribute. */ @Override public BootstrapMethods copy(final ConstantPool constantPool) { @@ -104,23 +112,25 @@ public BootstrapMethods copy(final ConstantPool constantPool) { } /** - * Dump bootstrap methods attribute to file stream in binary format. + * Dumps bootstrap methods attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public final void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(bootstrapMethods.length); + file.writeShort(Args.requireU2(bootstrapMethods.length, "bootstrapMethods.length")); for (final BootstrapMethod bootstrapMethod : bootstrapMethods) { bootstrapMethod.dump(file); } } /** - * @return array of bootstrap method "records" + * Gets the array of bootstrap method records. + * + * @return array of bootstrap method records. */ public final BootstrapMethod[] getBootstrapMethods() { return bootstrapMethods; @@ -132,7 +142,9 @@ public Iterator iterator() { } /** - * @param bootstrapMethods the array of bootstrap methods + * Sets the bootstrap methods. + * + * @param bootstrapMethods The array of bootstrap methods. */ public final void setBootstrapMethods(final BootstrapMethod[] bootstrapMethods) { this.bootstrapMethods = bootstrapMethods != null ? bootstrapMethods : BootstrapMethod.EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassElementValue.java index 3df0eb986537..f9dab667a96b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassElementValue.java @@ -25,6 +25,8 @@ import java.io.IOException; /** + * Represents a class element value in an annotation. + * * @since 6.0 */ public class ClassElementValue extends ElementValue { @@ -33,6 +35,13 @@ public class ClassElementValue extends ElementValue { // For 'class' this points to the class entry in the cpool private final int idx; + /** + * Constructs a ClassElementValue. + * + * @param type The type. + * @param idx The index. + * @param cpool The constant pool. + */ public ClassElementValue(final int type, final int idx, final ConstantPool cpool) { super(type, cpool); this.idx = idx; @@ -44,10 +53,20 @@ public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(idx); } + /** + * Gets the class string. + * + * @return The class string. + */ public String getClassString() { return super.getConstantPool().getConstantUtf8(idx).getBytes(); } + /** + * Gets the index. + * + * @return The index. + */ public int getIndex() { return idx; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassFormatException.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassFormatException.java index 037f3908379e..084682072397 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassFormatException.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassFormatException.java @@ -39,7 +39,7 @@ public ClassFormatException() { * Constructs a new instance with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * - * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + * @param message The detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method. */ public ClassFormatException(final String message) { super(message); @@ -48,8 +48,8 @@ public ClassFormatException(final String message) { /** * Constructs a new instance with the specified detail message and cause. * - * @param message the detail message (which is saved for later retrieval by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that + * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method). + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that * the cause is nonexistent or unknown. * @since 6.0 */ @@ -61,7 +61,7 @@ public ClassFormatException(final String message, final Throwable cause) { * Constructs a new instance with the specified cause and a detail message of {@code (cause==null ? null : cause.toString())} (which typically contains the * class and detail message of {@code cause}). This constructor is useful for runtime exceptions that are little more than wrappers for other throwables. * - * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that the + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that the * cause is nonexistent or unknown. * @since 6.7.0 */ diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassParser.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassParser.java index 0dbda722ec49..efb18a373976 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassParser.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ClassParser.java @@ -1,6 +1,5 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -22,6 +21,7 @@ package com.sun.org.apache.bcel.internal.classfile; import java.io.BufferedInputStream; +import java.io.DataInput; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; @@ -39,10 +39,22 @@ * The structure and the names comply, except for a few conveniences, exactly with the * JVM specification 1.0. See this paper for further details about * the structure of a bytecode file. + * + * @LastModified: Nov 2026 */ public final class ClassParser { private static final int BUFSIZE = 8192; + + static int[] readU2U2Table(final DataInput dataInput) throws IOException { + final int count = dataInput.readUnsignedShort(); + final int[] table = new int[count]; + for (int i = 0; i < count; i++) { + table[i] = dataInput.readUnsignedShort(); + } + return table; + } + private DataInputStream dataInputStream; private final boolean fileOwned; private final String fileName; @@ -54,16 +66,17 @@ public final class ClassParser { private int accessFlags; // Access rights of parsed class private int[] interfaces; // Names of implemented interfaces private ConstantPool constantPool; // collection of constants - private Field[] fields; // class fields, i.e., its variables + private Field[] fields; // class fields, that is, its variables private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class + private final boolean isZip; // Loaded from ZIP file /** * Parses class from the given stream. * - * @param inputStream Input stream - * @param fileName File name + * @param inputStream Input stream. + * @param fileName File name. */ public ClassParser(final InputStream inputStream, final String fileName) { this.fileName = fileName; @@ -80,7 +93,7 @@ public ClassParser(final InputStream inputStream, final String fileName) { /** * Parses class from given .class file. * - * @param fileName file name + * @param fileName file name. */ public ClassParser(final String fileName) { this.isZip = false; @@ -91,8 +104,8 @@ public ClassParser(final String fileName) { /** * Parses class from given .class file in a ZIP-archive * - * @param zipFile ZIP file name - * @param fileName file name + * @param zipFile ZIP file name. + * @param fileName file name. */ public ClassParser(final String zipFile, final String fileName) { this.isZip = true; @@ -102,13 +115,13 @@ public ClassParser(final String zipFile, final String fileName) { } /** - * Parses the given Java class file and return an object that represents the contained data, i.e., constants, methods, + * Parses the given Java class file and return an object that represents the contained data, that is, constants, methods, * fields and commands. A ClassFormatException is raised, if the file is not a valid .class file. (This does * not include verification of the byte code as it is performed by the Java interpreter). * - * @return Class object representing the parsed class file - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @return Class object representing the parsed class file. + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ public JavaClass parse() throws IOException, ClassFormatException { ZipFile zip = null; @@ -127,22 +140,22 @@ public JavaClass parse() throws IOException, ClassFormatException { dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName), BUFSIZE)); } } - /****************** Read headers ********************************/ + // -- Read headers -- // Check magic tag of class file readID(); // Get compiler version readVersion(); - /****************** Read constant pool and related **************/ + // -- Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); - // Get interface information, i.e., implemented interfaces + // Get interface information, that is, implemented interfaces readInterfaces(); - /****************** Read class fields and methods ***************/ - // Read class fields, i.e., the variables of the class + // -- Read class fields and methods -- + // Read class fields, that is, the variables of the class readFields(); - // Read class methods, i.e., the functions in the class + // Read class methods, that is, the functions in the class readMethods(); // Read class attributes readAttributes(); @@ -162,21 +175,12 @@ public JavaClass parse() throws IOException, ClassFormatException { // } } finally { // Read everything of interest, so close the file - if (fileOwned) { - try { - if (dataInputStream != null) { - dataInputStream.close(); - } - } catch (final IOException ignored) { - // ignore close exceptions - } - } try { - if (zip != null) { - zip.close(); + if (fileOwned && dataInputStream != null) { + dataInputStream.close(); } - } catch (final IOException ignored) { - // ignore close exceptions + if (zip != null) zip.close(); + } catch (IOException ignored) { } } // Return the information we have gathered in a new object @@ -187,8 +191,8 @@ public JavaClass parse() throws IOException, ClassFormatException { /** * Reads information about the attributes of the class. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readAttributes() throws IOException, ClassFormatException { final int attributesCount = dataInputStream.readUnsignedShort(); @@ -201,8 +205,8 @@ private void readAttributes() throws IOException, ClassFormatException { /** * Reads information about the class and its super class. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readClassInfo() throws IOException, ClassFormatException { accessFlags = dataInputStream.readUnsignedShort(); @@ -222,18 +226,18 @@ private void readClassInfo() throws IOException, ClassFormatException { /** * Reads constant pool entries. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readConstantPool() throws IOException, ClassFormatException { constantPool = new ConstantPool(dataInputStream); } /** - * Reads information about the fields of the class, i.e., its variables. + * Reads information about the fields of the class, that is, its variables. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readFields() throws IOException, ClassFormatException { final int fieldsCount = dataInputStream.readUnsignedShort(); @@ -243,12 +247,11 @@ private void readFields() throws IOException, ClassFormatException { } } - /******************** Private utility methods **********************/ /** * Checks whether the header of the file is ok. Of course, this has to be the first action on successive file reads. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readID() throws IOException, ClassFormatException { if (dataInputStream.readInt() != Const.JVM_CLASSFILE_MAGIC) { @@ -259,22 +262,18 @@ private void readID() throws IOException, ClassFormatException { /** * Reads information about the interfaces implemented by this class. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readInterfaces() throws IOException, ClassFormatException { - final int interfacesCount = dataInputStream.readUnsignedShort(); - interfaces = new int[interfacesCount]; - for (int i = 0; i < interfacesCount; i++) { - interfaces[i] = dataInputStream.readUnsignedShort(); - } + interfaces = readU2U2Table(dataInputStream); } /** * Reads information about the methods of the class. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readMethods() throws IOException { final int methodsCount = dataInputStream.readUnsignedShort(); @@ -287,8 +286,8 @@ private void readMethods() throws IOException { /** * Reads major and minor version of compiler which created the file. * - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ private void readVersion() throws IOException, ClassFormatException { minor = dataInputStream.readUnsignedShort(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Code.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Code.java index 7573a5412e73..d38b060eb94c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Code.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Code.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -56,11 +56,12 @@ * attribute_info attributes[attributes_count]; * } *
+ * * @see Attribute * @see CodeException * @see LineNumberTable * @see LocalVariableTable - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class Code extends Attribute { @@ -82,50 +83,56 @@ public Code(final Code code) { } /** - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param file Input stream - * @param constantPool Array of constants + * Constructs a Code attribute object from a DataInput. + * + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param dataInput Data input. + * @param constantPool Array of constants. + * @throws ClassFormatException Thrown if the code array read from {@code file} is greater than {@link Const#MAX_CODE_SIZE}. */ - Code(final int nameIndex, final int length, final DataInput file, final ConstantPool constantPool) throws IOException { + Code(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { // Initialize with some default values which will be overwritten later - this(nameIndex, length, file.readUnsignedShort(), file.readUnsignedShort(), (byte[]) null, (CodeException[]) null, (Attribute[]) null, constantPool); - final int codeLength = Args.requireU4(file.readInt(), 1, "Code length attribute"); + this(nameIndex, length, dataInput.readUnsignedShort(), dataInput.readUnsignedShort(), (byte[]) null, (CodeException[]) null, (Attribute[]) null, + constantPool); + final int codeLength = Args.requireU4(dataInput.readInt(), 0, Const.MAX_CODE_SIZE, "Code length attribute"); code = new byte[codeLength]; // Read byte code - file.readFully(code); + dataInput.readFully(code); /* - * Read exception table that contains all regions where an exception handler is active, i.e., a try { ... } catch () - * block. + * Read exception table that contains all regions where an exception handler is active, that is, a try { ... } catch () block. */ - final int exceptionTableLength = file.readUnsignedShort(); + final int exceptionTableLength = dataInput.readUnsignedShort(); exceptionTable = new CodeException[exceptionTableLength]; for (int i = 0; i < exceptionTableLength; i++) { - exceptionTable[i] = new CodeException(file); + exceptionTable[i] = new CodeException(dataInput); } /* * Read all attributes, currently 'LineNumberTable' and 'LocalVariableTable' */ - final int attributesCount = file.readUnsignedShort(); + final int attributesCount = dataInput.readUnsignedShort(); attributes = new Attribute[attributesCount]; for (int i = 0; i < attributesCount; i++) { - attributes[i] = readAttribute(file, constantPool); + attributes[i] = readAttribute(dataInput, constantPool); } /* - * Adjust length, because of setAttributes in this(), s.b. length is incorrect, because it didn't take the internal - * attributes into account yet! Very subtle bug, fixed in 3.1.1. + * Adjust length, because of setAttributes in this(), s.b. length is incorrect, because it didn't take the internal attributes into account yet! Very + * subtle bug, fixed in 3.1.1. */ super.setLength(length); } /** - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param maxStack Maximum size of stack - * @param maxLocals Number of local variables - * @param code Actual byte code - * @param exceptionTable of handled exceptions - * @param attributes Attributes of code: LineNumber or LocalVariable - * @param constantPool Array of constants + * Constructs a Code attribute. + * + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param maxStack Maximum size of stack. + * @param maxLocals Number of local variables. + * @param code Actual byte code. + * @param exceptionTable of handled exceptions. + * @param attributes Attributes of code: LineNumber or LocalVariable. + * @param constantPool Array of constants. + * @throws ClassFormatException Thrown if the code array is greater than {@link Const#MAX_CODE_SIZE}. */ public Code(final int nameIndex, final int length, final int maxStack, final int maxLocals, final byte[] code, final CodeException[] exceptionTable, final Attribute[] attributes, final ConstantPool constantPool) { @@ -133,6 +140,7 @@ public Code(final int nameIndex, final int length, final int maxStack, final int this.maxStack = Args.requireU2(maxStack, "maxStack"); this.maxLocals = Args.requireU2(maxLocals, "maxLocals"); this.code = Utils.createEmptyArrayIfNull(code); + Args.requireU4(this.code.length, 0, Const.MAX_CODE_SIZE, "Code length attribute"); this.exceptionTable = Utils.createEmptyArrayIfNull(exceptionTable, CodeException[].class); Args.requireU2(this.exceptionTable.length, "exceptionTable.length"); this.attributes = attributes != null ? attributes : EMPTY_ARRAY; @@ -141,9 +149,9 @@ public Code(final int nameIndex, final int length, final int maxStack, final int /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. - * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. + * That is, the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -151,8 +159,7 @@ public void accept(final Visitor v) { } /** - * @return the full size of this code attribute, minus its first 6 bytes, including the size of all its contained - * attributes + * @return The full size of this code attribute, minus its first 6 bytes, including the size of all its contained attributes. */ private int calculateLength() { int len = 0; @@ -165,9 +172,10 @@ private int calculateLength() { } /** - * @return deep copy of this attribute + * Creates a deep copy of this attribute. * - * @param constantPool the constant pool to duplicate + * @param constantPool The constant pool to duplicate. + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -184,10 +192,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump code attribute to file stream in binary format. + * Dumps code attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -196,17 +204,19 @@ public void dump(final DataOutputStream file) throws IOException { file.writeShort(maxLocals); file.writeInt(code.length); file.write(code, 0, code.length); - file.writeShort(exceptionTable.length); + file.writeShort(Args.requireU2(exceptionTable.length, "exceptionTable.length")); for (final CodeException exception : exceptionTable) { exception.dump(file); } - file.writeShort(attributes.length); + file.writeShort(Args.requireU2(attributes.length, "attributes.length")); for (final Attribute attribute : attributes) { attribute.dump(file); } } /** + * Gets the collection of code attributes. + * * @return Collection of code attributes. * @see Attribute */ @@ -215,6 +225,8 @@ public Attribute[] getAttributes() { } /** + * Gets the actual byte code of the method. + * * @return Actual byte code of the method. */ public byte[] getCode() { @@ -222,6 +234,8 @@ public byte[] getCode() { } /** + * Gets the table of handled exceptions. + * * @return Table of handled exceptions. * @see CodeException */ @@ -230,7 +244,9 @@ public CodeException[] getExceptionTable() { } /** - * @return the internal length of this code attribute (minus the first 6 bytes) and excluding all its attributes + * Gets the internal length of this code attribute (minus the first 6 bytes) and excluding all its attributes. + * + * @return The internal length of this code attribute (minus the first 6 bytes) and excluding all its attributes. */ private int getInternalLength() { return 2 /* maxStack */ + 2 /* maxLocals */ + 4 /* code length */ @@ -241,7 +257,9 @@ private int getInternalLength() { } /** - * @return LineNumberTable of Code, if it has one + * Gets the LineNumberTable of Code, if it has one. + * + * @return LineNumberTable of Code, if it has one. */ public LineNumberTable getLineNumberTable() { for (final Attribute attribute : attributes) { @@ -253,7 +271,9 @@ public LineNumberTable getLineNumberTable() { } /** - * @return LocalVariableTable of Code, if it has one + * Gets the LocalVariableTable of Code, if it has one. + * + * @return LocalVariableTable of Code, if it has one. */ public LocalVariableTable getLocalVariableTable() { for (final Attribute attribute : attributes) { @@ -266,6 +286,7 @@ public LocalVariableTable getLocalVariableTable() { /** * Gets the local variable type table attribute {@link LocalVariableTypeTable}. + * * @return LocalVariableTypeTable of Code, if it has one, null otherwise. * @since 6.10.0 */ @@ -279,6 +300,8 @@ public LocalVariableTypeTable getLocalVariableTypeTable() { } /** + * Gets the number of local variables. + * * @return Number of local variables. */ public int getMaxLocals() { @@ -286,6 +309,8 @@ public int getMaxLocals() { } /** + * Gets the maximum size of stack used by this method. + * * @return Maximum size of stack used by this method. */ public int getMaxStack() { @@ -294,6 +319,7 @@ public int getMaxStack() { /** * Finds the attribute of {@link StackMap} instance. + * * @return StackMap of Code, if it has one, else null. * @since 6.8.0 */ @@ -307,7 +333,9 @@ public StackMap getStackMap() { } /** - * @param attributes the attributes to set for this Code + * Sets the attributes for this Code. + * + * @param attributes The attributes to set for this Code. */ public void setAttributes(final Attribute[] attributes) { this.attributes = attributes != null ? attributes : EMPTY_ARRAY; @@ -315,30 +343,41 @@ public void setAttributes(final Attribute[] attributes) { } /** - * @param code byte code + * Sets the byte code. + * + * @param code byte code. + * @throws ClassFormatException Thrown if the code array is greater than {@link Const#MAX_CODE_SIZE}. */ public void setCode(final byte[] code) { this.code = Utils.createEmptyArrayIfNull(code); + Args.requireU4(this.code.length, 0, Const.MAX_CODE_SIZE, "Code length attribute"); super.setLength(calculateLength()); // Adjust length } /** - * @param exceptionTable exception table + * Sets the exception table. + * + * @param exceptionTable exception table. */ public void setExceptionTable(final CodeException[] exceptionTable) { this.exceptionTable = exceptionTable != null ? exceptionTable : CodeException.EMPTY_ARRAY; + Args.requireU2(this.exceptionTable.length, "exceptionTable.length"); super.setLength(calculateLength()); // Adjust length } /** - * @param maxLocals maximum number of local variables + * Sets the maximum number of local variables. + * + * @param maxLocals maximum number of local variables. */ public void setMaxLocals(final int maxLocals) { this.maxLocals = maxLocals; } /** - * @param maxStack maximum stack size + * Sets the maximum stack size. + * + * @param maxStack maximum stack size. */ public void setMaxStack(final int maxStack) { this.maxStack = maxStack; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/CodeException.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/CodeException.java index b8bf109239ee..2cea30256178 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/CodeException.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/CodeException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -52,7 +52,7 @@ * * * @see Code - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class CodeException implements Cloneable, Node { @@ -68,7 +68,7 @@ public final class CodeException implements Cloneable, Node { private int endPc; /** - * Starting address of exception handler, i.e., an offset from start of code. + * Starting address of exception handler, that is, an offset from start of code. */ private int handlerPc; @@ -89,8 +89,8 @@ public CodeException(final CodeException c) { /** * Constructs a new instance from a DataInput. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ CodeException(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort()); @@ -99,9 +99,9 @@ public CodeException(final CodeException c) { /** * Constructs a new instance. * - * @param startPc Range in the code the exception handler is active, startPc is inclusive while - * @param endPc is exclusive - * @param handlerPc Starting address of exception handler, i.e., an offset from start of code. + * @param startPc Range in the code the exception handler is active, startPc is inclusive while. + * @param endPc is exclusive. + * @param handlerPc Starting address of exception handler, that is, an offset from start of code. * @param catchType If zero the handler catches any exception, otherwise it points to the exception class which is to be * caught. */ @@ -116,7 +116,7 @@ public CodeException(final int startPc, final int endPc, final int handlerPc, fi * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -124,7 +124,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public CodeException copy() { try { @@ -138,8 +140,8 @@ public CodeException copy() { /** * Dumps code exception to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(startPc); @@ -149,6 +151,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the type of exception that is caught. + * * @return 0, if the handler catches any exception, otherwise it points to the exception class which is to be caught. */ public int getCatchType() { @@ -156,6 +160,8 @@ public int getCatchType() { } /** + * Gets the exclusive end index of the region where the handler is active. + * * @return Exclusive end index of the region where the handler is active. */ public int getEndPC() { @@ -163,6 +169,8 @@ public int getEndPC() { } /** + * Gets the starting address of exception handler, relative to the code. + * * @return Starting address of exception handler, relative to the code. */ public int getHandlerPC() { @@ -170,6 +178,8 @@ public int getHandlerPC() { } /** + * Gets the inclusive start index of the region where the handler is active. + * * @return Inclusive start index of the region where the handler is active. */ public int getStartPC() { @@ -177,34 +187,44 @@ public int getStartPC() { } /** - * @param catchType the type of exception that is caught + * Sets the type of exception that is caught. + * + * @param catchType The type of exception that is caught. */ public void setCatchType(final int catchType) { this.catchType = catchType; } /** - * @param endPc end of handled block + * Sets the end of handled block. + * + * @param endPc end of handled block. */ public void setEndPC(final int endPc) { this.endPc = endPc; } /** - * @param handlerPc where the actual code is + * Sets where the actual code is. + * + * @param handlerPc where the actual code is. */ public void setHandlerPC(final int handlerPc) { // TODO unused this.handlerPc = handlerPc; } /** - * @param startPc start of handled block + * Sets the start of handled block. + * + * @param startPc start of handled block. */ public void setStartPC(final int startPc) { // TODO unused this.startPc = startPc; } /** + * Gets a string representation. + * * @return String representation. */ @Override @@ -212,17 +232,25 @@ public String toString() { return "CodeException(startPc = " + startPc + ", endPc = " + endPc + ", handlerPc = " + handlerPc + ", catchType = " + catchType + ")"; } + /** + * Gets a string representation with constant pool. + * + * @param cp constant pool source. + * @return String representation. + */ public String toString(final ConstantPool cp) { return toString(cp, true); } /** + * Gets a string representation with constant pool. + * * @param cp constant pool source. * @param verbose Output more if true. * @return String representation. */ public String toString(final ConstantPool cp, final boolean verbose) { - String str; + final String str; if (catchType == 0) { str = "(0)"; } else { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Constant.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Constant.java index 9b3d6f31e171..ac57cfec2af9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Constant.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Constant.java @@ -28,11 +28,8 @@ import com.sun.org.apache.bcel.internal.util.BCELComparator; /** - * Abstract superclass for classes to represent the different constant types - * in the constant pool of a class file. The classes keep closely to - * the JVM specification. - * - * @LastModified: Sept 2025 + * Abstract superclass for classes to represent the different constant types in the constant pool of a class file. The + * classes keep closely to the JVM specification. */ public abstract class Constant implements Cloneable, Node { @@ -52,6 +49,8 @@ public int hashCode(final Constant o) { }; /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -61,10 +60,10 @@ public static BCELComparator getComparator() { /** * Reads one constant from the given input, the type depends on a tag byte. * - * @param dataInput Input stream - * @return Constant object - * @throws IOException if an I/O error occurs reading from the given {@code dataInput}. - * @throws ClassFormatException if the next byte is not recognized + * @param dataInput Input stream. + * @return Constant object. + * @throws IOException Thrown if an I/O error occurs reading from the given {@code dataInput}. + * @throws ClassFormatException Thrown if the next byte is not recognized * @since 6.0 made public */ public static Constant readConstant(final DataInput dataInput) throws IOException, ClassFormatException { @@ -110,21 +109,24 @@ public static Constant readConstant(final DataInput dataInput) throws IOExceptio } /** - * @param comparator Comparison strategy object + * Sets the comparison strategy object. + * + * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { bcelComparator = comparator; } /* - * In fact this tag is redundant since we can distinguish different 'Constant' objects by their type, i.e., via + * In fact this tag is redundant since we can distinguish different 'Constant' objects by their type, that is, via * 'instanceof'. In some places we will use the tag for switch()es anyway. * * First, we want match the specification as closely as possible. Second we need the tag as an index to select the * corresponding class name from the 'CONSTANT_NAMES' array. */ + /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected byte tag; // TODO should be private & final @@ -137,7 +139,7 @@ public static void setComparator(final BCELComparator comparator) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public abstract void accept(Visitor v); @@ -152,7 +154,9 @@ public Object clone() { } /** - * @return deep copy of this constant + * Creates a deep copy of this constant. + * + * @return deep copy of this constant. */ public Constant copy() { try { @@ -163,6 +167,12 @@ public Constant copy() { return null; } + /** + * Dumps constant to file stream in binary format. + * + * @param file The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ public abstract void dump(DataOutputStream file) throws IOException; /** @@ -177,7 +187,9 @@ public boolean equals(final Object obj) { } /** - * @return Tag of constant, i.e., its type. No setTag() method to avoid confusion. + * Gets the tag of constant. + * + * @return Tag of constant, that is, its type. No setTag() method to avoid confusion. */ public final byte getTag() { return tag; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantCP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantCP.java index 51113a1aeaa2..92ad914de665 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantCP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantCP.java @@ -32,7 +32,6 @@ * @see ConstantMethodref * @see ConstantInterfaceMethodref * @see ConstantInvokeDynamic - * @LastModified: Sept 2025 */ public abstract class ConstantCP extends Constant { @@ -41,15 +40,16 @@ public abstract class ConstantCP extends Constant { */ // Note that this field is used to store the // bootstrap_method_attr_index of a ConstantInvokeDynamic. + /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected int class_index; // TODO make private (has getter & setter) // This field has the same meaning for all subclasses. /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected int name_and_type_index; // TODO make private (has getter & setter) @@ -57,17 +57,20 @@ public abstract class ConstantCP extends Constant { /** * Initialize instance from file data. * - * @param tag Constant type tag - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param tag Constant type tag. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantCP(final byte tag, final DataInput file) throws IOException { this(tag, file.readUnsignedShort(), file.readUnsignedShort()); } /** - * @param classIndex Reference to the class containing the field - * @param nameAndTypeIndex and the field signature + * Constructs a ConstantCP. + * + * @param tag The constant type tag. + * @param classIndex Reference to the class containing the field. + * @param nameAndTypeIndex and the field signature. */ protected ConstantCP(final byte tag, final int classIndex, final int nameAndTypeIndex) { super(tag); @@ -85,10 +88,10 @@ public ConstantCP(final ConstantCP c) { } /** - * Dump constant field reference to file stream in binary format. + * Dumps constant field reference to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public final void dump(final DataOutputStream file) throws IOException { @@ -98,6 +101,9 @@ public final void dump(final DataOutputStream file) throws IOException { } /** + * Gets the class this field belongs to. + * + * @param cp The constant pool. * @return Class this field belongs to. */ public String getClass(final ConstantPool cp) { @@ -105,6 +111,8 @@ public String getClass(final ConstantPool cp) { } /** + * Gets the reference (index) to class this constant refers to. + * * @return Reference (index) to class this constant refers to. */ public final int getClassIndex() { @@ -112,6 +120,8 @@ public final int getClassIndex() { } /** + * Gets the reference (index) to signature of the field. + * * @return Reference (index) to signature of the field. */ public final int getNameAndTypeIndex() { @@ -119,14 +129,18 @@ public final int getNameAndTypeIndex() { } /** - * @param classIndex points to Constant_class + * Sets the class index. + * + * @param classIndex points to Constant_class. */ public final void setClassIndex(final int classIndex) { this.class_index = classIndex; } /** - * @param nameAndTypeIndex points to Constant_NameAndType + * Sets the name and type index. + * + * @param nameAndTypeIndex points to Constant_NameAndType. */ public final void setNameAndTypeIndex(final int nameAndTypeIndex) { this.name_and_type_index = nameAndTypeIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantClass.java index 9361a5d572f9..19926310dbec 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantClass.java @@ -48,14 +48,16 @@ public ConstantClass(final ConstantClass c) { /** * Constructs an instance from file data. * - * @param dataInput Input stream - * @throws IOException if an I/O error occurs reading from the given {@code dataInput}. + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O error occurs reading from the given {@code dataInput}. */ ConstantClass(final DataInput dataInput) throws IOException { this(dataInput.readUnsignedShort()); } /** + * Constructs a ConstantClass. + * * @param nameIndex Name index in constant pool. Should refer to a ConstantUtf8. */ public ConstantClass(final int nameIndex) { @@ -67,7 +69,7 @@ public ConstantClass(final int nameIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -77,8 +79,8 @@ public void accept(final Visitor v) { /** * Dumps constant class to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs writing to the DataOutputStream. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs writing to the DataOutputStream. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,14 +89,20 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return dereferenced string + * Gets the dereferenced string. + * + * @param cp The constant pool. + * @return dereferenced string. */ public String getBytes(final ConstantPool cp) { return (String) getConstantValue(cp); } /** - * @return String object + * Gets the String object. + * + * @param cp The constant pool. + * @return String object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -102,6 +110,8 @@ public Object getConstantValue(final ConstantPool cp) { } /** + * Gets the name index in constant pool of class name. + * * @return Name index in constant pool of class name. */ public int getNameIndex() { @@ -109,7 +119,9 @@ public int getNameIndex() { } /** - * @param nameIndex the name index in the constant pool of this Constant Class + * Sets the name index in the constant pool. + * + * @param nameIndex The name index in the constant pool of this Constant Class. */ public void setNameIndex(final int nameIndex) { this.nameIndex = nameIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDouble.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDouble.java index 14b43937c929..df68211aaf96 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDouble.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDouble.java @@ -30,7 +30,6 @@ * This class is derived from the abstract {@link Constant} and represents a reference to a Double object. * * @see Constant - * @LastModified: Sept 2025 */ public final class ConstantDouble extends Constant implements ConstantObject { @@ -48,15 +47,17 @@ public ConstantDouble(final ConstantDouble c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantDouble(final DataInput file) throws IOException { this(file.readDouble()); } /** - * @param bytes Data + * Constructs a ConstantDouble. + * + * @param bytes Data. */ public ConstantDouble(final double bytes) { super(Const.CONSTANT_Double); @@ -67,7 +68,7 @@ public ConstantDouble(final double bytes) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,10 +76,10 @@ public void accept(final Visitor v) { } /** - * Dump constant double to file stream in binary format. + * Dumps constant double to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,14 +88,19 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return data, i.e., 8 bytes. + * Gets the data. + * + * @return data, that is, 8 bytes. */ public double getBytes() { return bytes; } /** - * @return Double object + * Gets the Double object. + * + * @param cp The constant pool (not used). + * @return Double object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -102,7 +108,9 @@ public Object getConstantValue(final ConstantPool cp) { } /** - * @param bytes the raw bytes that represent the double value + * Sets the raw bytes that represent the double value. + * + * @param bytes The raw bytes that represent the double value. */ public void setBytes(final double bytes) { this.bytes = bytes; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDynamic.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDynamic.java index d51d2707137b..0237ec7bb124 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDynamic.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantDynamic.java @@ -49,13 +49,19 @@ public ConstantDynamic(final ConstantDynamic c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantDynamic(final DataInput file) throws IOException { - this(file.readShort(), file.readShort()); + this(file.readUnsignedShort(), file.readUnsignedShort()); } + /** + * Constructs a ConstantDynamic. + * + * @param bootstrapMethodAttrIndex Index to the bootstrap method. + * @param nameAndTypeIndex Index to the name and type. + */ public ConstantDynamic(final int bootstrapMethodAttrIndex, final int nameAndTypeIndex) { super(Const.CONSTANT_Dynamic, bootstrapMethodAttrIndex, nameAndTypeIndex); } @@ -64,7 +70,7 @@ public ConstantDynamic(final int bootstrapMethodAttrIndex, final int nameAndType * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -72,6 +78,8 @@ public void accept(final Visitor v) { } /** + * Gets the reference (index) to bootstrap method this constant refers to. + * * @return Reference (index) to bootstrap method this constant refers to. * * Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic. @@ -82,7 +90,7 @@ public int getBootstrapMethodAttrIndex() { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFieldref.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFieldref.java index 32bd750bed4e..2681fc41ea17 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFieldref.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFieldref.java @@ -43,16 +43,18 @@ public ConstantFieldref(final ConstantFieldref c) { /** * Initialize instance from input data. * - * @param input input stream - * @throws IOException if an I/O error occurs. + * @param input input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantFieldref(final DataInput input) throws IOException { super(Const.CONSTANT_Fieldref, input); } /** - * @param classIndex Reference to the class containing the Field - * @param nameAndTypeIndex and the Field signature + * Constructs a ConstantFieldref. + * + * @param classIndex Reference to the class containing the Field. + * @param nameAndTypeIndex and the Field signature. */ public ConstantFieldref(final int classIndex, final int nameAndTypeIndex) { super(Const.CONSTANT_Fieldref, classIndex, nameAndTypeIndex); @@ -62,7 +64,7 @@ public ConstantFieldref(final int classIndex, final int nameAndTypeIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of Fields, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFloat.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFloat.java index e86bbb94e662..5c62f46ccb2b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFloat.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantFloat.java @@ -30,7 +30,6 @@ * This class is derived from the abstract {@link Constant} and represents a reference to a float object. * * @see Constant - * @LastModified: Sept 2025 */ public final class ConstantFloat extends Constant implements ConstantObject { @@ -49,15 +48,17 @@ public ConstantFloat(final ConstantFloat c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantFloat(final DataInput file) throws IOException { this(file.readFloat()); } /** - * @param bytes Data + * Constructs a ConstantFloat. + * + * @param bytes Data. */ public ConstantFloat(final float bytes) { super(Const.CONSTANT_Float); @@ -68,7 +69,7 @@ public ConstantFloat(final float bytes) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -76,10 +77,10 @@ public void accept(final Visitor v) { } /** - * Dump constant float to file stream in binary format. + * Dumps constant float to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -88,14 +89,19 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return data, i.e., 4 bytes. + * Gets the data. + * + * @return data, that is, 4 bytes. */ public float getBytes() { return bytes; } /** - * @return Float object + * Gets the Float object. + * + * @param cp The constant pool (not used). + * @return Float object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -103,7 +109,9 @@ public Object getConstantValue(final ConstantPool cp) { } /** - * @param bytes the raw bytes that represent this float + * Sets the raw bytes that represent the float value. + * + * @param bytes The raw bytes that represent the float value. */ public void setBytes(final float bytes) { this.bytes = bytes; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInteger.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInteger.java index 20c0717acb6d..6c4abcbc2f05 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInteger.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInteger.java @@ -30,7 +30,6 @@ * This class is derived from the abstract {@link Constant} and represents a reference to an int object. * * @see Constant - * @LastModified: Sept 2025 */ public final class ConstantInteger extends Constant implements ConstantObject { @@ -48,15 +47,17 @@ public ConstantInteger(final ConstantInteger c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantInteger(final DataInput file) throws IOException { this(file.readInt()); } /** - * @param bytes Data + * Constructs a ConstantInteger. + * + * @param bytes Data. */ public ConstantInteger(final int bytes) { super(Const.CONSTANT_Integer); @@ -67,7 +68,7 @@ public ConstantInteger(final int bytes) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,10 +76,10 @@ public void accept(final Visitor v) { } /** - * Dump constant integer to file stream in binary format. + * Dumps constant integer to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,14 +88,19 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return data, i.e., 4 bytes. + * Gets the data. + * + * @return data, that is, 4 bytes. */ public int getBytes() { return bytes; } /** - * @return Integer object + * Gets the Integer object. + * + * @param cp The constant pool (not used). + * @return Integer object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -102,7 +108,9 @@ public Object getConstantValue(final ConstantPool cp) { } /** - * @param bytes the raw bytes that represent this integer + * Sets the raw bytes that represent the integer value. + * + * @param bytes The raw bytes that represent the integer value. */ public void setBytes(final int bytes) { this.bytes = bytes; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInterfaceMethodref.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInterfaceMethodref.java index 14cac5b9000c..7c2db32c9f77 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInterfaceMethodref.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInterfaceMethodref.java @@ -43,16 +43,18 @@ public ConstantInterfaceMethodref(final ConstantInterfaceMethodref c) { /** * Initialize instance from input data. * - * @param input input stream - * @throws IOException if an I/O error occurs. + * @param input input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantInterfaceMethodref(final DataInput input) throws IOException { super(Const.CONSTANT_InterfaceMethodref, input); } /** - * @param classIndex Reference to the class containing the method - * @param nameAndTypeIndex and the method signature + * Constructs a ConstantInterfaceMethodref. + * + * @param classIndex Reference to the class containing the method. + * @param nameAndTypeIndex and the method signature. */ public ConstantInterfaceMethodref(final int classIndex, final int nameAndTypeIndex) { super(Const.CONSTANT_InterfaceMethodref, classIndex, nameAndTypeIndex); @@ -62,7 +64,7 @@ public ConstantInterfaceMethodref(final int classIndex, final int nameAndTypeInd * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInvokeDynamic.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInvokeDynamic.java index b4154edd5a47..e225a5235373 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInvokeDynamic.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantInvokeDynamic.java @@ -48,13 +48,19 @@ public ConstantInvokeDynamic(final ConstantInvokeDynamic c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantInvokeDynamic(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort()); } + /** + * Constructs a ConstantInvokeDynamic. + * + * @param bootstrapMethodAttrIndex Index to the bootstrap method. + * @param nameAndTypeIndex Index to the name and type. + */ public ConstantInvokeDynamic(final int bootstrapMethodAttrIndex, final int nameAndTypeIndex) { super(Const.CONSTANT_InvokeDynamic, bootstrapMethodAttrIndex, nameAndTypeIndex); } @@ -63,7 +69,7 @@ public ConstantInvokeDynamic(final int bootstrapMethodAttrIndex, final int nameA * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -71,6 +77,8 @@ public void accept(final Visitor v) { } /** + * Gets the reference (index) to bootstrap method this constant refers to. + * * @return Reference (index) to bootstrap method this constant refers to. * * Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic. @@ -81,7 +89,7 @@ public int getBootstrapMethodAttrIndex() { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantLong.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantLong.java index 6936162c2642..ed636254837a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantLong.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantLong.java @@ -30,7 +30,6 @@ * This class is derived from the abstract {@link Constant} and represents a reference to a long object. * * @see Constant - * @LastModified: Sept 2025 */ public final class ConstantLong extends Constant implements ConstantObject { @@ -48,15 +47,17 @@ public ConstantLong(final ConstantLong c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantLong(final DataInput file) throws IOException { this(file.readLong()); } /** - * @param bytes Data + * Constructs a ConstantLong. + * + * @param bytes Data. */ public ConstantLong(final long bytes) { super(Const.CONSTANT_Long); @@ -67,7 +68,7 @@ public ConstantLong(final long bytes) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,10 +76,10 @@ public void accept(final Visitor v) { } /** - * Dump constant long to file stream in binary format. + * Dumps constant long to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,14 +88,19 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return data, i.e., 8 bytes. + * Gets the data. + * + * @return data, that is, 8 bytes. */ public long getBytes() { return bytes; } /** - * @return Long object + * Gets the Long object. + * + * @param cp The constant pool (not used). + * @return Long object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -102,7 +108,9 @@ public Object getConstantValue(final ConstantPool cp) { } /** - * @param bytes the raw bytes that represent this long + * Sets the raw bytes that represent the long value. + * + * @param bytes The raw bytes that represent the long value. */ public void setBytes(final long bytes) { this.bytes = bytes; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodHandle.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodHandle.java index 40dfc8fe64a4..484070a8ceef 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodHandle.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodHandle.java @@ -50,13 +50,19 @@ public ConstantMethodHandle(final ConstantMethodHandle c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantMethodHandle(final DataInput file) throws IOException { this(file.readUnsignedByte(), file.readUnsignedShort()); } + /** + * Constructs a ConstantMethodHandle. + * + * @param referenceKind Kind of method reference. + * @param referenceIndex Index to the method reference. + */ public ConstantMethodHandle(final int referenceKind, final int referenceIndex) { super(Const.CONSTANT_MethodHandle); this.referenceKind = referenceKind; @@ -67,7 +73,7 @@ public ConstantMethodHandle(final int referenceKind, final int referenceIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,10 +81,10 @@ public void accept(final Visitor v) { } /** - * Dump method kind and index to file stream in binary format. + * Dumps method kind and index to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,24 +93,44 @@ public void dump(final DataOutputStream file) throws IOException { file.writeShort(referenceIndex); } + /** + * Gets the reference index. + * + * @return The reference index. + */ public int getReferenceIndex() { return referenceIndex; } + /** + * Gets the reference kind. + * + * @return The reference kind. + */ public int getReferenceKind() { return referenceKind; } + /** + * Sets the reference index. + * + * @param referenceIndex The reference index. + */ public void setReferenceIndex(final int referenceIndex) { this.referenceIndex = referenceIndex; } + /** + * Sets the reference kind. + * + * @param referenceKind The reference kind. + */ public void setReferenceKind(final int referenceKind) { this.referenceKind = referenceKind; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodType.java index 654d801709c2..48956e4b93da 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodType.java @@ -49,13 +49,18 @@ public ConstantMethodType(final ConstantMethodType c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantMethodType(final DataInput file) throws IOException { this(file.readUnsignedShort()); } + /** + * Constructs a ConstantMethodType. + * + * @param descriptorIndex Index to the method descriptor. + */ public ConstantMethodType(final int descriptorIndex) { super(Const.CONSTANT_MethodType); this.descriptorIndex = descriptorIndex; @@ -65,7 +70,7 @@ public ConstantMethodType(final int descriptorIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -73,10 +78,10 @@ public void accept(final Visitor v) { } /** - * Dump name and signature index to file stream in binary format. + * Dumps name and signature index to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -84,16 +89,26 @@ public void dump(final DataOutputStream file) throws IOException { file.writeShort(descriptorIndex); } + /** + * Gets the descriptor index. + * + * @return The descriptor index. + */ public int getDescriptorIndex() { return descriptorIndex; } + /** + * Sets the descriptor index. + * + * @param descriptorIndex The descriptor index. + */ public void setDescriptorIndex(final int descriptorIndex) { this.descriptorIndex = descriptorIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodref.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodref.java index cd914092c4f5..a39e9e745368 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodref.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantMethodref.java @@ -43,16 +43,18 @@ public ConstantMethodref(final ConstantMethodref c) { /** * Initialize instance from input data. * - * @param input input stream - * @throws IOException if an I/O error occurs. + * @param input input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantMethodref(final DataInput input) throws IOException { super(Const.CONSTANT_Methodref, input); } /** - * @param classIndex Reference to the class containing the method - * @param nameAndTypeIndex and the method signature + * Constructs a ConstantMethodref. + * + * @param classIndex Reference to the class containing the method. + * @param nameAndTypeIndex and the method signature. */ public ConstantMethodref(final int classIndex, final int nameAndTypeIndex) { super(Const.CONSTANT_Methodref, classIndex, nameAndTypeIndex); @@ -61,8 +63,8 @@ public ConstantMethodref(final int classIndex, final int nameAndTypeIndex) { /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. - * - * @param v Visitor object + *. + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantModule.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantModule.java index 06754b9676eb..22b8fc6978cc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantModule.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantModule.java @@ -53,14 +53,16 @@ public ConstantModule(final ConstantModule c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantModule(final DataInput file) throws IOException { this(file.readUnsignedShort()); } /** + * Constructs a ConstantModule. + * * @param nameIndex Name index in constant pool. Should refer to a ConstantUtf8. */ public ConstantModule(final int nameIndex) { @@ -72,7 +74,7 @@ public ConstantModule(final int nameIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -80,10 +82,10 @@ public void accept(final Visitor v) { } /** - * Dump constant module to file stream in binary format. + * Dumps constant module to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -92,14 +94,20 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return dereferenced string + * Gets the dereferenced string. + * + * @param cp The constant pool. + * @return dereferenced string. */ public String getBytes(final ConstantPool cp) { return (String) getConstantValue(cp); } /** - * @return String object + * Gets the String object. + * + * @param cp The constant pool. + * @return String object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -107,6 +115,8 @@ public Object getConstantValue(final ConstantPool cp) { } /** + * Gets the name index in constant pool of module name. + * * @return Name index in constant pool of module name. */ public int getNameIndex() { @@ -114,7 +124,9 @@ public int getNameIndex() { } /** - * @param nameIndex the name index in the constant pool of this Constant Module + * Sets the name index in the constant pool. + * + * @param nameIndex The name index in the constant pool of this Constant Module. */ public void setNameIndex(final int nameIndex) { this.nameIndex = nameIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantNameAndType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantNameAndType.java index fbf09c9794cd..2a0c18f65e47 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantNameAndType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantNameAndType.java @@ -50,16 +50,18 @@ public ConstantNameAndType(final ConstantNameAndType c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantNameAndType(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort()); } /** - * @param nameIndex Name of field/method - * @param signatureIndex and its signature + * Constructs a ConstantNameAndType. + * + * @param nameIndex Name of field/method. + * @param signatureIndex and its signature. */ public ConstantNameAndType(final int nameIndex, final int signatureIndex) { super(Const.CONSTANT_NameAndType); @@ -71,7 +73,7 @@ public ConstantNameAndType(final int nameIndex, final int signatureIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -79,10 +81,10 @@ public void accept(final Visitor v) { } /** - * Dump name and signature index to file stream in binary format. + * Dumps name and signature index to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -92,13 +94,18 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return name + * Gets the name. + * + * @param cp The constant pool. + * @return name. */ public String getName(final ConstantPool cp) { return cp.constantToString(getNameIndex(), Const.CONSTANT_Utf8); } /** + * Gets the name index in constant pool of field/method name. + * * @return Name index in constant pool of field/method name. */ public int getNameIndex() { @@ -106,13 +113,18 @@ public int getNameIndex() { } /** - * @return signature + * Gets the signature. + * + * @param cp The constant pool. + * @return signature. */ public String getSignature(final ConstantPool cp) { return cp.constantToString(getSignatureIndex(), Const.CONSTANT_Utf8); } /** + * Gets the index in constant pool of field/method signature. + * * @return Index in constant pool of field/method signature. */ public int getSignatureIndex() { @@ -120,21 +132,25 @@ public int getSignatureIndex() { } /** - * @param nameIndex the name index of this constant + * Sets the name index. + * + * @param nameIndex The name index of this constant. */ public void setNameIndex(final int nameIndex) { this.nameIndex = nameIndex; } /** - * @param signatureIndex the signature index in the constant pool of this type + * Sets the signature index. + * + * @param signatureIndex The signature index in the constant pool of this type. */ public void setSignatureIndex(final int signatureIndex) { this.signatureIndex = signatureIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantObject.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantObject.java index ab187b7e4f89..8b3d1957d3d7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantObject.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantObject.java @@ -22,17 +22,17 @@ package com.sun.org.apache.bcel.internal.classfile; /** - * This interface denotes those constants that have a "natural" value, such as ConstantLong, ConstantString, etc.. + * This interface denotes those constants that have a "natural" value, such as ConstantLong, ConstantString, and so on. * * @see Constant */ public interface ConstantObject { /** - * Gets the object representing the constant, e.g., Long for ConstantLong. + * Gets the object representing the constant, for example, Long for ConstantLong. * - * @param constantPool the constant. - * @return object representing the constant, e.g., Long for ConstantLong. + * @param constantPool The constant. + * @return object representing the constant, for example, Long for ConstantLong. */ Object getConstantValue(ConstantPool constantPool); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPackage.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPackage.java index 2e8c7215016e..075a9b7cdae9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPackage.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPackage.java @@ -53,14 +53,16 @@ public ConstantPackage(final ConstantPackage c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantPackage(final DataInput file) throws IOException { this(file.readUnsignedShort()); } /** + * Constructs a ConstantPackage. + * * @param nameIndex Name index in constant pool. Should refer to a ConstantUtf8. */ public ConstantPackage(final int nameIndex) { @@ -72,7 +74,7 @@ public ConstantPackage(final int nameIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -80,10 +82,10 @@ public void accept(final Visitor v) { } /** - * Dump constant package to file stream in binary format. + * Dumps constant package to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -92,14 +94,20 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return dereferenced string + * Gets the dereferenced string. + * + * @param cp The constant pool. + * @return dereferenced string. */ public String getBytes(final ConstantPool cp) { return (String) getConstantValue(cp); } /** - * @return String object + * Gets the String object. + * + * @param cp The constant pool. + * @return String object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -107,6 +115,8 @@ public Object getConstantValue(final ConstantPool cp) { } /** + * Gets the name index in constant pool of package name. + * * @return Name index in constant pool of package name. */ public int getNameIndex() { @@ -114,7 +124,9 @@ public int getNameIndex() { } /** - * @param nameIndex the name index in the constant pool of this Constant Package + * Sets the name index in the constant pool. + * + * @param nameIndex The name index in the constant pool of this Constant Package. */ public void setNameIndex(final int nameIndex) { this.nameIndex = nameIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPool.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPool.java index ae1e3977c99b..695fd8132aff 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPool.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantPool.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -29,13 +29,13 @@ import com.sun.org.apache.bcel.internal.Const; /** - * This class represents the constant pool, i.e., a table of constants, of a parsed classfile. It may contain null references, due to the JVM specification that + * This class represents the constant pool, that is, a table of constants, of a parsed classfile. It may contain null references, due to the JVM specification that * skips an entry after an 8-byte constant (double, long) entry. Those interested in generating constant pools programmatically should see * ConstantPoolGen. * * @see Constant * @see com.sun.org.apache.bcel.internal.generic.ConstantPoolGen - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class ConstantPool implements Cloneable, Node, Iterable { @@ -70,17 +70,19 @@ private static String escape(final String str) { private Constant[] constantPool; /** - * @param constantPool Array of constants + * Constructs a ConstantPool. + * + * @param constantPool Array of constants. */ - public ConstantPool(final Constant[] constantPool) { + public ConstantPool(final Constant... constantPool) { setConstantPool(constantPool); } /** * Reads constants from given input stream. * - * @param input Input stream - * @throws IOException if problem in readUnsignedShort or readConstant + * @param input Input stream. + * @throws IOException Thrown if problem in readUnsignedShort or readConstant. */ public ConstantPool(final DataInput input) throws IOException { byte tag; @@ -109,7 +111,7 @@ public ConstantPool(final DataInput input) throws IOException { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., the hierarchy of methods, fields, * attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -119,13 +121,13 @@ public void accept(final Visitor v) { /** * Resolves constant to a string representation. * - * @param c Constant to be printed - * @return String representation - * @throws IllegalArgumentException if c is unknown constant type + * @param c Constant to be printed. + * @return String representation. + * @throws IllegalArgumentException Thrown if c is unknown constant type. */ public String constantToString(Constant c) throws IllegalArgumentException { - String str; - int i; + final String str; + final int i; final byte tag = c.getTag(); switch (tag) { case Const.CONSTANT_Class: @@ -167,8 +169,16 @@ public String constantToString(Constant c) throws IllegalArgumentException { // Note that the ReferenceIndex may point to a Fieldref, Methodref or // InterfaceMethodref - so we need to peek ahead to get the actual type. final ConstantMethodHandle cmh = (ConstantMethodHandle) c; - str = Const.getMethodHandleName(cmh.getReferenceKind()) + " " - + constantToString(cmh.getReferenceIndex(), getConstant(cmh.getReferenceIndex()).getTag()); + final byte referenceTag = getConstant(cmh.getReferenceIndex()).getTag(); + // JVMS 4.4.8: the reference_index of a CONSTANT_MethodHandle must point to a CONSTANT_Fieldref, + // CONSTANT_Methodref or CONSTANT_InterfaceMethodref entry. Anything else is malformed; in particular, a + // CONSTANT_MethodHandle referencing another CONSTANT_MethodHandle (such as itself) would otherwise make + // this method recurse without bound until a StackOverflowError. + if (referenceTag != Const.CONSTANT_Fieldref && referenceTag != Const.CONSTANT_Methodref && referenceTag != Const.CONSTANT_InterfaceMethodref) { + throw new ClassFormatException( + "Constant pool at index " + cmh.getReferenceIndex() + " has an invalid tag " + referenceTag + " for a CONSTANT_MethodHandle reference"); + } + str = Const.getMethodHandleName(cmh.getReferenceKind()) + " " + constantToString(cmh.getReferenceIndex(), referenceTag); break; case Const.CONSTANT_MethodType: final ConstantMethodType cmt = (ConstantMethodType) c; @@ -201,16 +211,18 @@ public String constantToString(Constant c) throws IllegalArgumentException { /** * Retrieves constant at 'index' from constant pool and resolve it to a string representation. * - * @param index of constant in constant pool - * @param tag expected type - * @return String representation + * @param index of constant in constant pool. + * @param tag expected type. + * @return String representation. */ public String constantToString(final int index, final byte tag) { return constantToString(getConstant(index, tag)); } /** - * @return deep copy of this constant pool + * Creates a deep copy of this constant pool. + * + * @return deep copy of this constant pool. */ public ConstantPool copy() { ConstantPool c = null; @@ -229,10 +241,10 @@ public ConstantPool copy() { } /** - * Dump constant pool to file stream in binary format. + * Dumps constant pool to file stream in binary format. * - * @param file Output file stream - * @throws IOException if problem in writeShort or dump + * @param file Output file stream. + * @throws IOException Thrown if problem in writeShort or dump */ public void dump(final DataOutputStream file) throws IOException { /* @@ -253,10 +265,11 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets constant from constant pool. * - * @param index Index in constant pool - * @return Constant value + * @param The type of the constant. + * @param index Index in constant pool. + * @return Constant value. * @see Constant - * @throws ClassFormatException if index is invalid + * @throws ClassFormatException Thrown if index is invalid. */ @SuppressWarnings("unchecked") public T getConstant(final int index) throws ClassFormatException { @@ -266,11 +279,12 @@ public T getConstant(final int index) throws ClassFormatExc /** * Gets constant from constant pool and check whether it has the expected type. * - * @param index Index in constant pool - * @param tag Tag of expected constant, i.e., its type - * @return Constant value + * @param The type of the constant. + * @param index Index in constant pool. + * @param tag Tag of expected constant, that is, its type. + * @return Constant value. * @see Constant - * @throws ClassFormatException if constant type does not match tag + * @throws ClassFormatException Thrown if constant type does not match tag. */ @SuppressWarnings("unchecked") public T getConstant(final int index, final byte tag) throws ClassFormatException { @@ -280,11 +294,13 @@ public T getConstant(final int index, final byte tag) throw /** * Gets constant from constant pool and check whether it has the expected type. * - * @param index Index in constant pool - * @param tag Tag of expected constant, i.e., its type - * @return Constant value + * @param The type of the constant. + * @param index Index in constant pool. + * @param tag Tag of expected constant, that is, its type. + * @param castTo The class to cast to. + * @return Constant value. * @see Constant - * @throws ClassFormatException if constant type does not match tag + * @throws ClassFormatException Thrown if constant type does not match tag. * @since 6.6.0 */ public T getConstant(final int index, final byte tag, final Class castTo) throws ClassFormatException { @@ -298,16 +314,16 @@ public T getConstant(final int index, final byte tag, final /** * Gets constant from constant pool. * - * @param A {@link Constant} subclass - * @param index Index in constant pool + * @param A {@link Constant} subclass. + * @param index Index in constant pool. * @param castTo The {@link Constant} subclass to cast to. - * @return Constant value + * @return Constant value. + * @throws ClassFormatException Thrown if index is invalid. * @see Constant - * @throws ClassFormatException if index is invalid * @since 6.6.0 */ public T getConstant(final int index, final Class castTo) throws ClassFormatException { - if (index >= constantPool.length || index < 0) { + if (index >= constantPool.length || index < 1) { throw new ClassFormatException("Invalid constant pool reference using index: " + index + ". Constant pool size is: " + constantPool.length); } if (constantPool[index] != null && !castTo.isAssignableFrom(constantPool[index].getClass())) { @@ -332,16 +348,18 @@ public T getConstant(final int index, final Class castTo /** * Gets constant from constant pool and check whether it has the expected type. * - * @param index Index in constant pool - * @return ConstantInteger value + * @param index Index in constant pool. + * @return ConstantInteger value. + * @throws ClassFormatException Thrown if constant type does not match tag. * @see ConstantInteger - * @throws ClassFormatException if constant type does not match tag */ public ConstantInteger getConstantInteger(final int index) { return getConstant(index, Const.CONSTANT_Integer, ConstantInteger.class); } /** + * Gets the array of constants. + * * @return Array of constants. * @see Constant */ @@ -353,15 +371,15 @@ public Constant[] getConstantPool() { * Gets string from constant pool and bypass the indirection of 'ConstantClass' and 'ConstantString' objects. I.e. these classes have an index field that * points to another entry of the constant pool of type 'ConstantUtf8' which contains the real data. * - * @param index Index in constant pool - * @param tag Tag of expected constant, either ConstantClass or ConstantString - * @return Contents of string reference + * @param index Index in constant pool. + * @param tag Tag of expected constant, either ConstantClass or ConstantString. + * @return Contents of string reference. + * @throws IllegalArgumentException Thrown if tag is invalid. * @see ConstantClass * @see ConstantString - * @throws IllegalArgumentException if tag is invalid */ public String getConstantString(final int index, final byte tag) throws IllegalArgumentException { - int i; + final int i; /* * This switch() is not that elegant, since the four classes have the same contents, they just differ in the name of the index field variable. But we * want to stick to the JVM naming conventions closely though we could have solved these more elegantly by using the same variable name or by @@ -392,16 +410,18 @@ public String getConstantString(final int index, final byte tag) throws IllegalA /** * Gets constant from constant pool and check whether it has the expected type. * - * @param index Index in constant pool - * @return ConstantUtf8 value + * @param index Index in constant pool. + * @return ConstantUtf8 value. + * @throws ClassFormatException Thrown if constant type does not match tag. * @see ConstantUtf8 - * @throws ClassFormatException if constant type does not match tag */ public ConstantUtf8 getConstantUtf8(final int index) throws ClassFormatException { return getConstant(index, Const.CONSTANT_Utf8, ConstantUtf8.class); } /** + * Gets the length of constant pool. + * * @return Length of constant pool. */ public int getLength() { @@ -414,14 +434,19 @@ public Iterator iterator() { } /** - * @param constant Constant to set + * Sets a constant at the specified index. + * + * @param index The index in the constant pool. + * @param constant Constant to set. */ public void setConstant(final int index, final Constant constant) { constantPool[index] = constant; } /** - * @param constantPool + * Sets the constant pool. + * + * @param constantPool The constant pool array. */ public void setConstantPool(final Constant[] constantPool) { this.constantPool = constantPool != null ? constantPool : Constant.EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantString.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantString.java index 287e092b9aa6..1cd0b87af066 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantString.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantString.java @@ -48,15 +48,17 @@ public ConstantString(final ConstantString c) { /** * Initialize instance from file data. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantString(final DataInput file) throws IOException { this(file.readUnsignedShort()); } /** - * @param stringIndex Index of Constant_Utf8 in constant pool + * Constructs a ConstantString. + * + * @param stringIndex Index of Constant_Utf8 in constant pool. */ public ConstantString(final int stringIndex) { super(Const.CONSTANT_String); @@ -67,7 +69,7 @@ public ConstantString(final int stringIndex) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,10 +77,10 @@ public void accept(final Visitor v) { } /** - * Dump constant field reference to file stream in binary format. + * Dumps constant field reference to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -87,14 +89,20 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return dereferenced string + * Gets the dereferenced string. + * + * @param cp The constant pool. + * @return dereferenced string. */ public String getBytes(final ConstantPool cp) { return (String) getConstantValue(cp); } /** - * @return String object + * Gets the String object. + * + * @param cp The constant pool. + * @return String object. */ @Override public Object getConstantValue(final ConstantPool cp) { @@ -102,6 +110,8 @@ public Object getConstantValue(final ConstantPool cp) { } /** + * Gets the index in constant pool of the string. + * * @return Index in constant pool of the string (ConstantUtf8). */ public int getStringIndex() { @@ -109,7 +119,9 @@ public int getStringIndex() { } /** - * @param stringIndex the index into the constant of the string value + * Sets the string index. + * + * @param stringIndex The index into the constant of the string value. */ public void setStringIndex(final int stringIndex) { this.stringIndex = stringIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantUtf8.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantUtf8.java index 90e45c807e5b..2cee2b350608 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantUtf8.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantUtf8.java @@ -65,7 +65,7 @@ public final class ConstantUtf8 extends Constant { private static final class Cache { private static final boolean BCEL_STATISTICS = false; - private static final int MAX_ENTRIES = 20000; + private static final int MAX_ENTRIES = 0; // default value in 6.13.0 private static final int INITIAL_CAPACITY = (int) (MAX_ENTRIES / 0.75); private static final HashMap CACHE = new LinkedHashMap(INITIAL_CAPACITY, 0.75f, true) { @@ -87,6 +87,7 @@ static boolean isEnabled() { } + private static final Object LOCK = new Object(); // TODO these should perhaps be AtomicInt? private static volatile int considered; private static volatile int created; @@ -108,8 +109,10 @@ static boolean isEnabled() { * * @since 6.4.0 */ - public static synchronized void clearCache() { - Cache.CACHE.clear(); + public static void clearCache() { + synchronized (LOCK) { + Cache.CACHE.clear(); + } } // for access by test code @@ -118,7 +121,7 @@ static synchronized void clearStats() { } // Avoid Spotbugs complaint about Write to static field - private static void countCreated() { + private static synchronized void countCreated() { created++; } @@ -128,25 +131,27 @@ private static void countCreated() { * See {@link ConstantUtf8} class Javadoc for details. *

* - * @param value the value. - * @return a new or cached instance of the given value. + * @param value The value. + * @return A new or cached instance of the given value. * @since 6.0 */ public static ConstantUtf8 getCachedInstance(final String value) { - if (value.length() > Cache.MAX_ENTRY_SIZE) { - skipped++; - return new ConstantUtf8(value); - } - considered++; - synchronized (ConstantUtf8.class) { // might be better with a specific lock object - ConstantUtf8 result = Cache.CACHE.get(value); - if (result != null) { - hits++; + synchronized (LOCK) { + if (value.length() > Cache.MAX_ENTRY_SIZE) { + skipped++; + return new ConstantUtf8(value); + } + considered++; + synchronized (ConstantUtf8.class) { // might be better with a specific lock object + ConstantUtf8 result = Cache.CACHE.get(value); + if (result != null) { + hits++; + return result; + } + result = new ConstantUtf8(value); + Cache.CACHE.put(value, result); return result; } - result = new ConstantUtf8(value); - Cache.CACHE.put(value, result); - return result; } } @@ -156,9 +161,9 @@ public static ConstantUtf8 getCachedInstance(final String value) { * See {@link ConstantUtf8} class Javadoc for details. *

* - * @param dataInput the value. - * @return a new or cached instance of the given value. - * @throws IOException if an I/O error occurs. + * @param dataInput The value. + * @return A new or cached instance of the given value. + * @throws IOException Thrown if an I/O error occurs. * @since 6.0 */ public static ConstantUtf8 getInstance(final DataInput dataInput) throws IOException { @@ -171,8 +176,8 @@ public static ConstantUtf8 getInstance(final DataInput dataInput) throws IOExcep * See {@link ConstantUtf8} class Javadoc for details. *

* - * @param value the value. - * @return a new or cached instance of the given value. + * @param value The value. + * @return A new or cached instance of the given value. * @since 6.0 */ public static ConstantUtf8 getInstance(final String value) { @@ -193,7 +198,7 @@ static void printStats() { /** * Initializes from another object. * - * @param constantUtf8 the value. + * @param constantUtf8 The value. */ public ConstantUtf8(final ConstantUtf8 constantUtf8) { this(constantUtf8.getBytes()); @@ -202,8 +207,8 @@ public ConstantUtf8(final ConstantUtf8 constantUtf8) { /** * Initializes instance from file data. * - * @param dataInput Input stream - * @throws IOException if an I/O error occurs. + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O error occurs. */ ConstantUtf8(final DataInput dataInput) throws IOException { super(Const.CONSTANT_Utf8); @@ -212,7 +217,9 @@ public ConstantUtf8(final ConstantUtf8 constantUtf8) { } /** - * @param value Data + * Constructs a ConstantUtf8. + * + * @param value Data. */ public ConstantUtf8(final String value) { super(Const.CONSTANT_Utf8); @@ -224,7 +231,7 @@ public ConstantUtf8(final String value) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -234,8 +241,8 @@ public void accept(final Visitor v) { /** * Dumps String in Utf8 format to file stream. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -244,6 +251,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the data converted to string. + * * @return Data converted to string. */ public String getBytes() { @@ -251,7 +260,7 @@ public String getBytes() { } /** - * @param bytes the raw bytes of this UTF-8 + * @param bytes The raw bytes of this UTF-8. * @deprecated (since 6.0) */ @java.lang.Deprecated @@ -260,7 +269,7 @@ public void setBytes(final String bytes) { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantValue.java index 143c2a255448..11119799b10e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ConstantValue.java @@ -29,7 +29,7 @@ import com.sun.org.apache.bcel.internal.util.Args; /** - * This class is derived from Attribute and represents a constant value, i.e., a default value for initializing + * This class is derived from Attribute and represents a constant value, that is, a default value for initializing * a class field. This class is instantiated by the Attribute.readAttribute() method. * *
@@ -39,6 +39,7 @@
  *   u2 constantvalue_index;
  * }
  * 
+ * * @see Attribute */ public final class ConstantValue extends Attribute { @@ -58,21 +59,23 @@ public ConstantValue(final ConstantValue c) { /** * Constructs object from input stream. * - * @param nameIndex Name index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Name index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ ConstantValue(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, input.readUnsignedShort(), constantPool); } /** - * @param nameIndex Name index in constant pool - * @param length Content length in bytes - * @param constantValueIndex Index in constant pool - * @param constantPool Array of constants + * Constructs a ConstantValue. + * + * @param nameIndex Name index in constant pool. + * @param length Content length in bytes. + * @param constantValueIndex Index in constant pool. + * @param constantPool Array of constants. */ public ConstantValue(final int nameIndex, final int length, final int constantValueIndex, final ConstantPool constantPool) { super(Const.ATTR_CONSTANT_VALUE, nameIndex, Args.require(length, 2, "ConstantValue attribute length"), constantPool); @@ -83,7 +86,7 @@ public ConstantValue(final int nameIndex, final int length, final int constantVa * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -91,7 +94,10 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * Creates a deep copy of this attribute. + * + * @param constantPool The constant pool. + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -101,10 +107,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump constant value attribute to file stream on binary format. + * Dumps constant value attribute to file stream on binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -113,6 +119,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the index in constant pool of constant value. + * * @return Index in constant pool of constant value. */ public int getConstantValueIndex() { @@ -120,7 +128,9 @@ public int getConstantValueIndex() { } /** - * @param constantValueIndex the index info the constant pool of this constant value + * Sets the constant value index. + * + * @param constantValueIndex The index info the constant pool of this constant value. */ public void setConstantValueIndex(final int constantValueIndex) { this.constantValueIndex = constantValueIndex; @@ -132,8 +142,8 @@ public void setConstantValueIndex(final int constantValueIndex) { @Override public String toString() { Constant c = super.getConstantPool().getConstant(constantValueIndex); - String buf; - int i; + final String buf; + final int i; // Print constant to string depending on its type switch (c.getTag()) { case Const.CONSTANT_Long: diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Deprecated.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Deprecated.java index c561afe33c53..611a76268b81 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Deprecated.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Deprecated.java @@ -1,6 +1,5 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -21,25 +20,30 @@ package com.sun.org.apache.bcel.internal.classfile; import java.io.DataInput; -import java.io.DataOutputStream; import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.util.Args; /** - * This class is derived from Attribute and denotes that this is a deprecated method. It is instantiated from - * the Attribute.readAttribute() method. + * This class is derived from Attribute and denotes that this is a deprecated method. It is instantiated from the Attribute.readAttribute() + * method. + * + *
+ * Deprecated_attribute {
+ *     u2 attribute_name_index;
+ *     u4 attribute_length;
+ * }
+ * 
* * @see Attribute + * @see JVM Specification: The Deprecated Attribute + * @LastModified: Nov 2026 */ public final class Deprecated extends Attribute { - private byte[] bytes; - /** - * Initialize from another object. Note that both objects use the same references (shallow copy). Use clone() for a - * physical copy. + * Initialize from another object. Note that both objects use the same references (shallow copy). Use clone() for a physical copy. * * @param c Source to copy. */ @@ -48,39 +52,37 @@ public Deprecated(final Deprecated c) { } /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param bytes Attribute contents - * @param constantPool Array of constants + * Constructs a Deprecated attribute. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length JVM Specification: "The value of the attribute_length item must be zero.". + * @param bytes Attribute contents. + * @param constantPool Array of constants. + * @see JVM Specification: The Deprecated Attribute */ public Deprecated(final int nameIndex, final int length, final byte[] bytes, final ConstantPool constantPool) { super(Const.ATTR_DEPRECATED, nameIndex, Args.require0(length, "Deprecated attribute length"), constantPool); - this.bytes = bytes; } /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length JVM Specification: "The value of the attribute_length item must be zero.". + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. + * @see JVM Specification: The Deprecated Attribute */ Deprecated(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (byte[]) null, constantPool); - if (length > 0) { - bytes = new byte[length]; - input.readFully(bytes); - println("Deprecated attribute with length > 0"); - } } /** - * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. - * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. + * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. That is, the hierarchy of methods, + * fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -88,48 +90,37 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { final Deprecated c = (Deprecated) clone(); - if (bytes != null) { - c.bytes = bytes.clone(); - } c.setConstantPool(constantPool); return c; } /** - * Dump source file attribute to file stream in binary format. + * Gets the data bytes. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. - */ - @Override - public void dump(final DataOutputStream file) throws IOException { - super.dump(file); - if (super.getLength() > 0) { - file.write(bytes, 0, super.getLength()); - } - } - - /** * @return data bytes. */ public byte[] getBytes() { - return bytes; + return Const.EMPTY_BYTE_ARRAY; } /** - * @param bytes the raw bytes that represents this byte array + * Sets the data bytes. + * + * @param bytes The raw bytes that represents this byte array. */ public void setBytes(final byte[] bytes) { - this.bytes = bytes; + if (bytes != null) { + Args.require0(bytes.length, "Deprecated attribute length"); + } } /** - * @return attribute name + * @return attribute name. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/DescendingVisitor.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/DescendingVisitor.java index 934b608d6ac7..dc3470914920 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/DescendingVisitor.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/DescendingVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -22,13 +22,14 @@ import java.util.Objects; import java.util.Stack; import java.util.stream.Stream; + import jdk.xml.internal.Utils; /** * Traverses a JavaClass with another Visitor object 'piggy-backed' that is applied to all components of a JavaClass * object. I.e. this class supplies the traversal strategy, other classes can make use of it. * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class DescendingVisitor implements Visitor { private final JavaClass clazz; @@ -38,8 +39,10 @@ public class DescendingVisitor implements Visitor { private final Stack stack = new Stack<>(); /** - * @param clazz Class to traverse - * @param visitor visitor object to apply to all components + * Constructs a DescendingVisitor. + * + * @param clazz Class to traverse. + * @param visitor visitor object to apply to all components. */ public DescendingVisitor(final JavaClass clazz, final Visitor visitor) { this.clazz = clazz; @@ -51,22 +54,28 @@ private void accept(final E[] node) { } /** - * @return current object + * Gets the current object. + * + * @return current object. */ public Object current() { return stack.peek(); } /** - * @return container of current entitity, i.e., predecessor during traversal + * Gets the container of current entity, that is, predecessor during traversal. + * + * @return container of current entity, that is, predecessor during traversal. */ public Object predecessor() { return predecessor(0); } /** - * @param level nesting level, i.e., 0 returns the direct predecessor - * @return container of current entitity, i.e., predecessor during traversal + * Gets the container of current entity, that is, predecessor during traversal. + * + * @param level nesting level, that is, 0 returns the direct predecessor. + * @return container of current entity, that is, predecessor during traversal. */ public Object predecessor(final int level) { final int size = stack.size(); @@ -508,6 +517,14 @@ public void visitParameterAnnotationEntry(final ParameterAnnotationEntry obj) { stack.pop(); } + /** @since 6.13.0 */ + @Override + public void visitPermittedSubclasses(final PermittedSubclasses obj) { + stack.push(obj); + obj.accept(visitor); + stack.pop(); + } + @Override public void visitRecord(final Record record) { stack.push(record); @@ -556,7 +573,8 @@ public void visitStackMapEntry(final StackMapEntry var) { /** * Visits a {@link StackMapType} object. - * @param var object to visit + * + * @param var object to visit. * @since 6.8.0 */ @Override diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValue.java index d87307c0e7db..291e9c4083ef 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValue.java @@ -49,24 +49,51 @@ * } value; *} * + * * @since 6.0 - * @LastModified: Sept 2025 */ public abstract class ElementValue { + /** Element value type: string. */ public static final byte STRING = 's'; + + /** Element value type: enum constant. */ public static final byte ENUM_CONSTANT = 'e'; + + /** Element value type: class. */ public static final byte CLASS = 'c'; + + /** Element value type: annotation. */ public static final byte ANNOTATION = '@'; + + /** Element value type: array. */ public static final byte ARRAY = '['; + + /** Element value type: primitive int. */ public static final byte PRIMITIVE_INT = 'I'; + + /** Element value type: primitive byte. */ public static final byte PRIMITIVE_BYTE = 'B'; + + /** Element value type: primitive char. */ public static final byte PRIMITIVE_CHAR = 'C'; + + /** Element value type: primitive double. */ public static final byte PRIMITIVE_DOUBLE = 'D'; + + /** Element value type: primitive float. */ public static final byte PRIMITIVE_FLOAT = 'F'; + + /** Element value type: primitive long. */ public static final byte PRIMITIVE_LONG = 'J'; + + /** Element value type: primitive short. */ public static final byte PRIMITIVE_SHORT = 'S'; + + /** Element value type: primitive boolean. */ public static final byte PRIMITIVE_BOOLEAN = 'Z'; + + /** Empty array constant. */ static final ElementValue[] EMPTY_ARRAY = {}; /** @@ -74,24 +101,14 @@ public abstract class ElementValue { * * @param input Raw data input. * @param cpool Constant pool. - * @return a new ElementValue. - * @throws IOException if an I/O error occurs. + * @return A new ElementValue. + * @throws IOException Thrown if an I/O error occurs. */ public static ElementValue readElementValue(final DataInput input, final ConstantPool cpool) throws IOException { return readElementValue(input, cpool, 0); } - /** - * Reads an {@code element_value} as an {@code ElementValue}. - * - * @param input Raw data input. - * @param cpool Constant pool. - * @param arrayNesting level of current array nesting. - * @return a new ElementValue. - * @throws IOException if an I/O error occurs. - * @since 6.7.0 - */ - public static ElementValue readElementValue(final DataInput input, final ConstantPool cpool, int arrayNesting) + static ElementValue readElementValue(final DataInput input, final ConstantPool cpool, final boolean isRuntimeVisible, int arrayNesting) throws IOException { final byte tag = input.readByte(); switch (tag) { @@ -113,8 +130,15 @@ public static ElementValue readElementValue(final DataInput input, final Constan return new ClassElementValue(CLASS, input.readUnsignedShort(), cpool); case ANNOTATION: - // TODO isRuntimeVisible - return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read(input, cpool, false), cpool); + arrayNesting++; + if (arrayNesting > Const.MAX_ARRAY_DIMENSIONS) { + // Annotation element values may legitimately nest (annotations whose members are annotations or arrays thereof), but a malicious class file + // can alternate annotation and array nesting to recurse without limit. Count both kinds of nesting against the same JVM spec 4.4.1 bound so + // the depth cannot be reset by wrapping an array in an annotation (CWE-674). + throw new ClassFormatException( + String.format("Annotation element values are only valid if they nest %,d or fewer levels.", Const.MAX_ARRAY_DIMENSIONS)); + } + return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read(input, cpool, isRuntimeVisible, arrayNesting), cpool); case ARRAY: arrayNesting++; @@ -125,7 +149,7 @@ public static ElementValue readElementValue(final DataInput input, final Constan final int numArrayVals = input.readUnsignedShort(); final ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { - evalues[j] = readElementValue(input, cpool, arrayNesting); + evalues[j] = readElementValue(input, cpool, isRuntimeVisible, arrayNesting); } return new ArrayElementValue(ARRAY, evalues, cpool); @@ -135,43 +159,100 @@ public static ElementValue readElementValue(final DataInput input, final Constan } /** - * @deprecated (since 6.0) will be made private and final; do not access directly, use getter + * Reads an {@code element_value} as an {@code ElementValue}. + * + * @param input Raw data input. + * @param cpool Constant pool. + * @param arrayNesting level of current array nesting. + * @return A new ElementValue. + * @throws IOException Thrown if an I/O error occurs. + * @since 6.7.0 + */ + public static ElementValue readElementValue(final DataInput input, final ConstantPool cpool, final int arrayNesting) throws IOException { + return readElementValue(input, cpool, false, arrayNesting); + } + + /** + * @deprecated (since 6.0) will be made private and final; do not access directly, use getter. */ @java.lang.Deprecated protected int type; // TODO should be final + /** - * @deprecated (since 6.0) will be made private and final; do not access directly, use getter + * @deprecated (since 6.0) will be made private and final; do not access directly, use getter. */ @java.lang.Deprecated protected ConstantPool cpool; // TODO should be final + /** + * Constructs an ElementValue. + * + * @param type The element value type. + * @param cpool The constant pool. + */ protected ElementValue(final int type, final ConstantPool cpool) { this.type = type; this.cpool = cpool; } + /** + * Dumps this element value to a DataOutputStream. + * + * @param dos The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ public abstract void dump(DataOutputStream dos) throws IOException; - /** @since 6.0 */ + /** + * Gets the constant pool. + * + * @return The constant pool. + * @since 6.0 + */ final ConstantPool getConstantPool() { return cpool; } + /** + * Gets the element value type. + * + * @return The element value type. + */ public int getElementValueType() { return type; } - /** @since 6.0 */ + /** + * Gets the type. + * + * @return The type. + * @since 6.0 + */ final int getType() { return type; } + /** + * Returns a string representation of the element value. + * + * @return A string representation of the element value. + */ public abstract String stringifyValue(); + /** + * Returns a short string representation of the element value. + * + * @return A short string representation of the element value. + */ public String toShortString() { return stringifyValue(); } + /** + * Returns a string representation of the element value. + * + * @return A string representation of the element value. + */ @Override public String toString() { return stringifyValue(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValuePair.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValuePair.java index 8a2e67060346..0f35caa2ba29 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValuePair.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ElementValuePair.java @@ -39,29 +39,62 @@ public class ElementValuePair { private final int elementNameIndex; + /** + * Constructs an ElementValuePair. + * + * @param elementNameIndex The element name index. + * @param elementValue The element value. + * @param constantPool The constant pool. + */ public ElementValuePair(final int elementNameIndex, final ElementValue elementValue, final ConstantPool constantPool) { this.elementValue = elementValue; this.elementNameIndex = elementNameIndex; this.constantPool = constantPool; } + /** + * Dumps this element value pair to a DataOutputStream. + * + * @param dos The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ protected void dump(final DataOutputStream dos) throws IOException { dos.writeShort(elementNameIndex); // u2 name of the element elementValue.dump(dos); } + /** + * Gets the name index. + * + * @return The name index. + */ public int getNameIndex() { return elementNameIndex; } + /** + * Gets the name string. + * + * @return The name string. + */ public String getNameString() { return constantPool.getConstantUtf8(elementNameIndex).getBytes(); } + /** + * Gets the value. + * + * @return The element value. + */ public final ElementValue getValue() { return elementValue; } + /** + * Gets a short string representation. + * + * @return A short string representation. + */ public String toShortString() { final StringBuilder result = new StringBuilder(); result.append(getNameString()).append("=").append(getValue().toShortString()); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EmptyVisitor.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EmptyVisitor.java index db33c8716569..4a59de3c3e1f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EmptyVisitor.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EmptyVisitor.java @@ -22,12 +22,14 @@ package com.sun.org.apache.bcel.internal.classfile; /** - * Visitor with empty method bodies, can be extended and used in conjunction with the DescendingVisitor class, e.g. By + * Visitor with empty method bodies, can be extended and used in conjunction with the DescendingVisitor class, for example. By * courtesy of David Spencer. * * @see DescendingVisitor */ public class EmptyVisitor implements Visitor { + + /** Constructs an EmptyVisitor. */ protected EmptyVisitor() { } @@ -299,6 +301,11 @@ public void visitParameterAnnotation(final ParameterAnnotations obj) { public void visitParameterAnnotationEntry(final ParameterAnnotationEntry parameterAnnotationEntry) { } + /** @since 6.13.0 */ + @Override + public void visitPermittedSubclasses(final PermittedSubclasses obj) { + } + @Override public void visitSignature(final Signature obj) { } @@ -317,7 +324,8 @@ public void visitStackMapEntry(final StackMapEntry obj) { /** * Visits a {@link StackMapType} object. - * @param obj object to visit + * + * @param obj object to visit. * @since 6.8.0 */ @Override diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnclosingMethod.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnclosingMethod.java index 326e77738b0a..f3af53c26a19 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnclosingMethod.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnclosingMethod.java @@ -77,15 +77,29 @@ public final void dump(final DataOutputStream file) throws IOException { file.writeShort(methodIndex); } + /** + * Gets the enclosing class. + * + * @return The enclosing class. + */ public final ConstantClass getEnclosingClass() { return super.getConstantPool().getConstant(classIndex, Const.CONSTANT_Class, ConstantClass.class); } - // Accessors + /** + * Gets the enclosing class index. + * + * @return The enclosing class index. + */ public final int getEnclosingClassIndex() { return classIndex; } + /** + * Gets the enclosing method. + * + * @return The enclosing method. + */ public final ConstantNameAndType getEnclosingMethod() { if (methodIndex == 0) { return null; @@ -93,14 +107,29 @@ public final ConstantNameAndType getEnclosingMethod() { return super.getConstantPool().getConstant(methodIndex, Const.CONSTANT_NameAndType, ConstantNameAndType.class); } + /** + * Gets the enclosing method index. + * + * @return The enclosing method index. + */ public final int getEnclosingMethodIndex() { return methodIndex; } + /** + * Sets the enclosing class index. + * + * @param idx The index. + */ public final void setEnclosingClassIndex(final int idx) { classIndex = idx; } + /** + * Sets the enclosing method index. + * + * @param idx The index. + */ public final void setEnclosingMethodIndex(final int idx) { methodIndex = idx; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnumElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnumElementValue.java index 0a8163ededa7..51cf97d246fe 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnumElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/EnumElementValue.java @@ -25,6 +25,8 @@ import java.io.IOException; /** + * Represents an enum element value in an annotation. + * * @since 6.0 */ public class EnumElementValue extends ElementValue { @@ -33,6 +35,14 @@ public class EnumElementValue extends ElementValue { private final int valueIdx; + /** + * Constructs an EnumElementValue. + * + * @param type The element value type. + * @param typeIdx The type index. + * @param valueIdx The value index. + * @param cpool The constant pool. + */ public EnumElementValue(final int type, final int typeIdx, final int valueIdx, final ConstantPool cpool) { super(type, cpool); if (type != ENUM_CONSTANT) { @@ -49,18 +59,38 @@ public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(valueIdx); // u2 } + /** + * Gets the enum type string. + * + * @return The enum type string. + */ public String getEnumTypeString() { return super.getConstantPool().getConstantUtf8(typeIdx).getBytes(); } + /** + * Gets the enum value string. + * + * @return The enum value string. + */ public String getEnumValueString() { return super.getConstantPool().getConstantUtf8(valueIdx).getBytes(); } + /** + * Gets the type index. + * + * @return The type index. + */ public int getTypeIndex() { return typeIdx; } + /** + * Gets the value index. + * + * @return The value index. + */ public int getValueIndex() { return valueIdx; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ExceptionTable.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ExceptionTable.java index 1b6004b37409..094cc1078132 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ExceptionTable.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ExceptionTable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -43,8 +43,9 @@ * u2 exception_index_table[number_of_exceptions]; * } * + * * @see Code - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class ExceptionTable extends Attribute { @@ -63,26 +64,24 @@ public ExceptionTable(final ExceptionTable c) { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ ExceptionTable(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (int[]) null, constantPool); - final int exceptionCount = input.readUnsignedShort(); - exceptionIndexTable = new int[exceptionCount]; - for (int i = 0; i < exceptionCount; i++) { - exceptionIndexTable[i] = input.readUnsignedShort(); - } + exceptionIndexTable = ClassParser.readU2U2Table(input); } /** - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param exceptionIndexTable Table of indices in constant pool - * @param constantPool Array of constants + * Constructs an ExceptionTable. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param exceptionIndexTable Table of indices in constant pool. + * @param constantPool Array of constants. */ public ExceptionTable(final int nameIndex, final int length, final int[] exceptionIndexTable, final ConstantPool constantPool) { super(Const.ATTR_EXCEPTIONS, nameIndex, length, constantPool); @@ -92,9 +91,9 @@ public ExceptionTable(final int nameIndex, final int length, final int[] excepti /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. - * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. + * That is, the hierarchy of methods, fields, attributes, and so on spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -102,7 +101,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * Creates a deep copy of this attribute. + * + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -115,21 +116,23 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump exceptions attribute to file stream in binary format. + * Dumps exceptions attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(exceptionIndexTable.length); + file.writeShort(Args.requireU2(exceptionIndexTable.length, "exceptionIndexTable.length")); for (final int index : exceptionIndexTable) { file.writeShort(index); } } /** + * Gets the array of indices into constant pool of thrown exceptions. + * * @return Array of indices into constant pool of thrown exceptions. */ public int[] getExceptionIndexTable() { @@ -137,7 +140,9 @@ public int[] getExceptionIndexTable() { } /** - * @return class names of thrown exceptions + * Gets the class names of thrown exceptions. + * + * @return class names of thrown exceptions. */ public String[] getExceptionNames() { final String[] names = new String[exceptionIndexTable.length]; @@ -146,6 +151,8 @@ public String[] getExceptionNames() { } /** + * Gets the length of exception table. + * * @return Length of exception table. */ public int getNumberOfExceptions() { @@ -153,7 +160,9 @@ public int getNumberOfExceptions() { } /** - * @param exceptionIndexTable the list of exception indexes Also redefines number_of_exceptions according to table + * Sets the exception index table. + * + * @param exceptionIndexTable The list of exception indexes Also redefines number_of_exceptions according to table * length. */ public void setExceptionIndexTable(final int[] exceptionIndexTable) { @@ -161,7 +170,7 @@ public void setExceptionIndexTable(final int[] exceptionIndexTable) { } /** - * @return String representation, i.e., a list of thrown exceptions. + * @return String representation, that is, a list of thrown exceptions. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Field.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Field.java index 8ffc796a0eaf..fa6d46038e42 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Field.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Field.java @@ -30,7 +30,7 @@ import com.sun.org.apache.bcel.internal.util.BCELComparator; /** - * This class represents the field info structure, i.e., the representation for a variable in the class. See JVM + * This class represents the field info structure, that is, the representation for a variable in the class. See JVM * specification for details. */ public final class Field extends FieldOrMethod { @@ -56,6 +56,8 @@ public int hashCode(final Field o) { }; /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -63,6 +65,8 @@ public static BCELComparator getComparator() { } /** + * Sets the comparison strategy object. + * * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { @@ -73,6 +77,7 @@ public static void setComparator(final BCELComparator comparator) { * Constructs object from file stream. * * @param file Input stream. + * @param constantPool The constant pool. */ Field(final DataInput file, final ConstantPool constantPool) throws IOException, ClassFormatException { super(file, constantPool); @@ -89,11 +94,13 @@ public Field(final Field c) { } /** - * @param accessFlags Access rights of field - * @param nameIndex Points to field name in constant pool - * @param signatureIndex Points to encoded signature - * @param attributes Collection of attributes - * @param constantPool Array of constants + * Constructs a Field. + * + * @param accessFlags Access rights of field. + * @param nameIndex Points to field name in constant pool. + * @param signatureIndex Points to encoded signature. + * @param attributes Collection of attributes. + * @param constantPool Array of constants. */ public Field(final int accessFlags, final int nameIndex, final int signatureIndex, final Attribute[] attributes, final ConstantPool constantPool) { super(accessFlags, nameIndex, signatureIndex, attributes, constantPool); @@ -103,7 +110,7 @@ public Field(final int accessFlags, final int nameIndex, final int signatureInde * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -111,7 +118,10 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this field + * Creates a deep copy of this field. + * + * @param constantPool The constant pool. + * @return deep copy of this field. */ public Field copy(final ConstantPool constantPool) { return (Field) copy_(constantPool); @@ -129,7 +139,9 @@ public boolean equals(final Object obj) { } /** - * @return constant value associated with this field (may be null) + * Gets the constant value associated with this field. + * + * @return constant value associated with this field (may be null). */ public ConstantValue getConstantValue() { for (final Attribute attribute : super.getAttributes()) { @@ -143,7 +155,7 @@ public ConstantValue getConstantValue() { /** * See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.2.2 * - * @return type of field + * @return type of field. */ public Type getType() { return Type.getType(getSignature()); @@ -161,21 +173,17 @@ public int hashCode() { } /** - * Return string representation close to declaration format, 'public static final short MAX = 100', e.g.. + * Return string representation close to declaration format, for example: 'public static final short MAX = 100'. * * @return String representation of field, including the signature. */ @Override public String toString() { - String name; - String signature; - String access; // Short cuts to constant pool - // Get names from constant pool - access = Utility.accessToString(super.getAccessFlags()); + String access = Utility.accessToString(super.getAccessFlags()); access = access.isEmpty() ? "" : access + " "; - signature = Utility.signatureToString(getSignature()); - name = getName(); + final String signature = Utility.signatureToString(getSignature()); + final String name = getName(); final StringBuilder buf = new StringBuilder(64); // CHECKSTYLE IGNORE MagicNumber buf.append(access).append(signature).append(" ").append(name); final ConstantValue cv = getConstantValue(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/FieldOrMethod.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/FieldOrMethod.java index 679d5a9eb7cb..ac97831b16b9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/FieldOrMethod.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/FieldOrMethod.java @@ -25,27 +25,27 @@ import java.io.IOException; import java.util.Arrays; +import com.sun.org.apache.bcel.internal.util.Args; + /** * Abstract super class for fields and methods. - * - * @LastModified: Sept 2025 */ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, Node { /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected int name_index; // Points to field name in constant pool /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected int signature_index; // Points to encoded signature /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected Attribute[] attributes; // Collection of attributes @@ -60,7 +60,7 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No private AnnotationEntry[] annotationEntries; // annotations defined on the field or method /** - * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter + * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter. */ @java.lang.Deprecated protected ConstantPool constant_pool; @@ -74,8 +74,9 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @param constantPool The constant pool. + * @throws IOException Thrown if an I/O error occurs. */ protected FieldOrMethod(final DataInput file, final ConstantPool constantPool) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), null, constantPool); @@ -90,8 +91,9 @@ protected FieldOrMethod(final DataInput file, final ConstantPool constantPool) t /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @param constantPool The constant pool. + * @throws IOException Thrown if an I/O error occurs. * @deprecated (6.0) Use {@link #FieldOrMethod(java.io.DataInput, ConstantPool)} instead. */ @java.lang.Deprecated @@ -110,11 +112,13 @@ protected FieldOrMethod(final FieldOrMethod c) { } /** - * @param accessFlags Access rights of method - * @param nameIndex Points to field name in constant pool - * @param signatureIndex Points to encoded signature - * @param attributes Collection of attributes - * @param constantPool Array of constants + * Constructs a FieldOrMethod. + * + * @param accessFlags Access rights of method. + * @param nameIndex Points to field name in constant pool. + * @param signatureIndex Points to encoded signature. + * @param attributes Collection of attributes. + * @param constantPool Array of constants. */ protected FieldOrMethod(final int accessFlags, final int nameIndex, final int signatureIndex, final Attribute[] attributes, final ConstantPool constantPool) { @@ -126,7 +130,10 @@ protected FieldOrMethod(final int accessFlags, final int nameIndex, final int si } /** - * @return deep copy of this field + * Creates a deep copy of this field. + * + * @param constantPool The constant pool. + * @return deep copy of this field. */ protected FieldOrMethod copy_(final ConstantPool constantPool) { try { @@ -142,23 +149,25 @@ protected FieldOrMethod copy_(final ConstantPool constantPool) { } /** - * Dump object to file stream on binary format. + * Dumps object to file stream on binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public final void dump(final DataOutputStream file) throws IOException { file.writeShort(super.getAccessFlags()); file.writeShort(name_index); file.writeShort(signature_index); - file.writeShort(attributes_count); + file.writeShort(Args.requireU2(attributes_count, "attributes_count")); for (final Attribute attribute : attributes) { attribute.dump(file); } } /** - * @return Annotations on the field or method + * Gets annotations on the field or method. + * + * @return Annotations on the field or method. * @since 6.0 */ public AnnotationEntry[] getAnnotationEntries() { @@ -171,6 +180,9 @@ public AnnotationEntry[] getAnnotationEntries() { /** * Gets attribute for given tag. + * + * @param The attribute type. + * @param tag The attribute tag. * @return Attribute for given tag, null if not found. * Refer to {@link com.sun.org.apache.bcel.internal.Const#ATTR_UNKNOWN} constants named ATTR_* for possible values. * @since 6.10.0 @@ -186,6 +198,8 @@ public final T getAttribute(final byte tag) { } /** + * Gets the collection of object attributes. + * * @return Collection of object attributes. */ public final Attribute[] getAttributes() { @@ -193,6 +207,8 @@ public final Attribute[] getAttributes() { } /** + * Gets the constant pool used by this object. + * * @return Constant pool used by this object. */ public final ConstantPool getConstantPool() { @@ -204,6 +220,7 @@ public final ConstantPool getConstantPool() { * (Ljava/util/Vector;)V the signature attribute may in fact say 'Ljava/lang/Vector<Ljava/lang/String>;' Coded for * performance - searches for the attribute only when requested - only searches for it once. * + * @return The generic signature. * @since 6.0 */ public final String getGenericSignature() { @@ -221,13 +238,17 @@ public final String getGenericSignature() { } /** - * @return Name of object, i.e., method name or field name + * Gets the name of object. + * + * @return Name of object, that is, method name or field name. */ public final String getName() { return constant_pool.getConstantUtf8(name_index).getBytes(); } /** + * Gets the index in constant pool of object's name. + * * @return Index in constant pool of object's name. */ public final int getNameIndex() { @@ -235,13 +256,17 @@ public final int getNameIndex() { } /** - * @return String representation of object's type signature (Java style) + * Gets the string representation of object's type signature. + * + * @return String representation of object's type signature (Java style). */ public final String getSignature() { return constant_pool.getConstantUtf8(signature_index).getBytes(); } /** + * Gets the index in constant pool of field signature. + * * @return Index in constant pool of field signature. */ public final int getSignatureIndex() { @@ -249,6 +274,8 @@ public final int getSignatureIndex() { } /** + * Sets the collection of object attributes. + * * @param attributes Collection of object attributes. */ public final void setAttributes(final Attribute[] attributes) { @@ -257,6 +284,8 @@ public final void setAttributes(final Attribute[] attributes) { } /** + * Sets the constant pool to be used for this object. + * * @param constantPool Constant pool to be used for this object. */ public final void setConstantPool(final ConstantPool constantPool) { @@ -264,6 +293,8 @@ public final void setConstantPool(final ConstantPool constantPool) { } /** + * Sets the index in constant pool of object's name. + * * @param nameIndex Index in constant pool of object's name. */ public final void setNameIndex(final int nameIndex) { @@ -271,6 +302,8 @@ public final void setNameIndex(final int nameIndex) { } /** + * Sets the index in constant pool of field signature. + * * @param signatureIndex Index in constant pool of field signature. */ public final void setSignatureIndex(final int signatureIndex) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClass.java index 82900dcca10a..a3580c129f5a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClass.java @@ -28,7 +28,7 @@ import com.sun.org.apache.bcel.internal.Const; /** - * This class represents a inner class attribute, i.e., the class indices of the inner and outer classes, the name and + * This class represents a inner class attribute, that is, the class indices of the inner and outer classes, the name and * the attributes of the inner class. * * @see InnerClasses @@ -43,8 +43,8 @@ public final class InnerClass implements Cloneable, Node { /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ InnerClass(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort()); @@ -60,10 +60,12 @@ public InnerClass(final InnerClass c) { } /** - * @param innerClassIndex Class index in constant pool of inner class - * @param outerClassIndex Class index in constant pool of outer class - * @param innerNameIndex Name index in constant pool of inner class - * @param innerAccessFlags Access flags of inner class + * Constructs an InnerClass. + * + * @param innerClassIndex Class index in constant pool of inner class. + * @param outerClassIndex Class index in constant pool of outer class. + * @param innerNameIndex Name index in constant pool of inner class. + * @param innerAccessFlags Access flags of inner class. */ public InnerClass(final int innerClassIndex, final int outerClassIndex, final int innerNameIndex, final int innerAccessFlags) { this.innerClassIndex = innerClassIndex; @@ -76,7 +78,7 @@ public InnerClass(final int innerClassIndex, final int outerClassIndex, final in * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -84,7 +86,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public InnerClass copy() { try { @@ -96,10 +100,10 @@ public InnerClass copy() { } /** - * Dump inner class attribute to file stream in binary format. + * Dumps inner class attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(innerClassIndex); @@ -109,6 +113,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the access flags of inner class. + * * @return access flags of inner class. */ public int getInnerAccessFlags() { @@ -116,6 +122,8 @@ public int getInnerAccessFlags() { } /** + * Gets the class index of inner class. + * * @return class index of inner class. */ public int getInnerClassIndex() { @@ -123,6 +131,8 @@ public int getInnerClassIndex() { } /** + * Gets the name index of inner class. + * * @return name index of inner class. */ public int getInnerNameIndex() { @@ -130,6 +140,8 @@ public int getInnerNameIndex() { } /** + * Gets the class index of outer class. + * * @return class index of outer class. */ public int getOuterClassIndex() { @@ -137,34 +149,44 @@ public int getOuterClassIndex() { } /** - * @param innerAccessFlags access flags for this inner class + * Sets the access flags for this inner class. + * + * @param innerAccessFlags access flags for this inner class. */ public void setInnerAccessFlags(final int innerAccessFlags) { this.innerAccessFlags = innerAccessFlags; } /** - * @param innerClassIndex index into the constant pool for this class + * Sets the index into the constant pool for this class. + * + * @param innerClassIndex index into the constant pool for this class. */ public void setInnerClassIndex(final int innerClassIndex) { this.innerClassIndex = innerClassIndex; } /** - * @param innerNameIndex index into the constant pool for this class's name + * Sets the index into the constant pool for this class's name. + * + * @param innerNameIndex index into the constant pool for this class's name. */ public void setInnerNameIndex(final int innerNameIndex) { // TODO unused this.innerNameIndex = innerNameIndex; } /** - * @param outerClassIndex index into the constant pool for the owning class + * Sets the index into the constant pool for the owning class. + * + * @param outerClassIndex index into the constant pool for the owning class. */ public void setOuterClassIndex(final int outerClassIndex) { // TODO unused this.outerClassIndex = outerClassIndex; } /** + * Gets the string representation. + * * @return String representation. */ @Override @@ -173,11 +195,13 @@ public String toString() { } /** - * @return Resolved string representation + * Gets the resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public String toString(final ConstantPool constantPool) { String outerClassName; - String innerName; String innerClassName = constantPool.getConstantString(innerClassIndex, Const.CONSTANT_Class); innerClassName = Utility.compactClassName(innerClassName, false); if (outerClassIndex != 0) { @@ -186,6 +210,7 @@ public String toString(final ConstantPool constantPool) { } else { outerClassName = ""; } + final String innerName; if (innerNameIndex != 0) { innerName = constantPool.getConstantUtf8(innerNameIndex).getBytes(); } else { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClasses.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClasses.java index b61be1effa0c..758480304028 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClasses.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InnerClasses.java @@ -59,11 +59,11 @@ public InnerClasses(final InnerClasses c) { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ InnerClasses(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (InnerClass[]) null, constantPool); @@ -75,10 +75,12 @@ public InnerClasses(final InnerClasses c) { } /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param innerClasses array of inner classes attributes - * @param constantPool Array of constants + * Constructs an InnerClasses attribute. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param innerClasses array of inner classes attributes. + * @param constantPool Array of constants. */ public InnerClasses(final int nameIndex, final int length, final InnerClass[] innerClasses, final ConstantPool constantPool) { super(Const.ATTR_INNER_CLASSES, nameIndex, length, constantPool); @@ -90,7 +92,7 @@ public InnerClasses(final int nameIndex, final int length, final InnerClass[] in * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -98,7 +100,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * Creates a deep copy of this attribute. + * + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -111,22 +115,24 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump source file attribute to file stream in binary format. + * Dumps source file attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(innerClasses.length); + file.writeShort(Args.requireU2(innerClasses.length, "innerClasses.length")); for (final InnerClass innerClass : innerClasses) { innerClass.dump(file); } } /** - * @return array of inner class "records" + * Gets the array of inner class records. + * + * @return array of inner class "records". */ public InnerClass[] getInnerClasses() { return innerClasses; @@ -138,7 +144,9 @@ public Iterator iterator() { } /** - * @param innerClasses the array of inner classes + * Sets the array of inner classes. + * + * @param innerClasses The array of inner classes. */ public void setInnerClasses(final InnerClass[] innerClasses) { this.innerClasses = innerClasses != null ? innerClasses : EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InvalidMethodSignatureException.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InvalidMethodSignatureException.java index eaf1da2d2e13..49355933db97 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InvalidMethodSignatureException.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/InvalidMethodSignatureException.java @@ -43,7 +43,7 @@ public InvalidMethodSignatureException(final String signature) { * Constructs a new instance with the specified invalid signature as the message and a cause. * * @param signature The invalid signature is saved for later retrieval by the {@link #getMessage()} method. - * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null} value is permitted, and indicates that * the cause is nonexistent or unknown. */ public InvalidMethodSignatureException(final String signature, final Throwable cause) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/JavaClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/JavaClass.java index 1b0e2ed1ce0a..8d8652c6a148 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/JavaClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/JavaClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -27,6 +27,7 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; @@ -35,22 +36,25 @@ import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.generic.Type; +import com.sun.org.apache.bcel.internal.util.Args; import com.sun.org.apache.bcel.internal.util.BCELComparator; import com.sun.org.apache.bcel.internal.util.ClassQueue; import com.sun.org.apache.bcel.internal.util.SyntheticRepository; import jdk.xml.internal.Utils; /** - * Represents a Java class, i.e., the data structures, constant pool, fields, methods and commands contained in a Java + * Represents a Java class, that is, the data structures, constant pool, fields, methods and commands contained in a Java * .class file. See JVM specification for details. The intent of * this class is to represent a parsed or otherwise existing class file. Those interested in programmatically generating * classes should see the ClassGen class. * * @see com.sun.org.apache.bcel.internal.generic.ClassGen - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparable { + private static final String CLASS_NAME_OBJECT = "java.lang.Object"; + /** * The standard class file extension. * @@ -65,8 +69,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl */ public static final JavaClass[] EMPTY_ARRAY = {}; + /** Source was read from heap. */ public static final byte HEAP = 1; + + /** Source was read from file. */ public static final byte FILE = 2; + + /** Source was read from ZIP. */ public static final byte ZIP = 3; private static BCELComparator bcelComparator = new BCELComparator() { @@ -82,6 +91,8 @@ public int hashCode(final JavaClass o) { }; /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -98,6 +109,8 @@ private static String indent(final Object obj) { } /** + * Sets the comparison strategy object. + * * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { @@ -116,7 +129,7 @@ public static void setComparator(final BCELComparator comparator) { private ConstantPool constantPool; // Constant pool private int[] interfaces; // implemented interfaces private String[] interfaceNames; - private Field[] fields; // Fields, i.e., variables of class + private Field[] fields; // Fields, that is, variables of class private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class @@ -140,17 +153,17 @@ public static void setComparator(final BCELComparator comparator) { /** * Constructor gets all contents as arguments. * - * @param classNameIndex Class name - * @param superclassNameIndex Superclass name - * @param fileName File name - * @param major Major compiler version - * @param minor Minor compiler version - * @param accessFlags Access rights defined by bit flags - * @param constantPool Array of constants - * @param interfaces Implemented interfaces - * @param fields Class fields - * @param methods Class methods - * @param attributes Class attributes + * @param classNameIndex Class name. + * @param superclassNameIndex Superclass name. + * @param fileName File name. + * @param major Major compiler version. + * @param minor Minor compiler version. + * @param accessFlags Access rights defined by bit flags. + * @param constantPool Array of constants. + * @param interfaces Implemented interfaces. + * @param fields Class fields. + * @param methods Class methods. + * @param attributes Class attributes. */ public JavaClass(final int classNameIndex, final int superclassNameIndex, final String fileName, final int major, final int minor, final int accessFlags, final ConstantPool constantPool, final int[] interfaces, final Field[] fields, final Method[] methods, final Attribute[] attributes) { @@ -160,19 +173,18 @@ public JavaClass(final int classNameIndex, final int superclassNameIndex, final /** * Constructor gets all contents as arguments. * - * @param classNameIndex Index into constant pool referencing a ConstantClass that represents this class. - * @param superclassNameIndex Index into constant pool referencing a ConstantClass that represents this class's - * superclass. - * @param fileName File name - * @param major Major compiler version - * @param minor Minor compiler version - * @param accessFlags Access rights defined by bit flags - * @param constantPool Array of constants - * @param interfaces Implemented interfaces - * @param fields Class fields - * @param methods Class methods - * @param attributes Class attributes - * @param source Read from file or generated in memory? + * @param classNameIndex Index into constant pool referencing a ConstantClass that represents this class. + * @param superclassNameIndex Index into constant pool referencing a ConstantClass that represents this class's superclass. + * @param fileName File name. + * @param major Major compiler version. + * @param minor Minor compiler version. + * @param accessFlags Access rights defined by bit flags. + * @param constantPool Array of constants. + * @param interfaces Implemented interfaces. + * @param fields Class fields. + * @param methods Class methods. + * @param attributes Class attributes. + * @param source Read from file or generated in memory. */ public JavaClass(final int classNameIndex, final int superclassNameIndex, final String fileName, final int major, final int minor, final int accessFlags, final ConstantPool constantPool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes, final byte source) { @@ -222,7 +234,7 @@ public JavaClass(final int classNameIndex, final int superclassNameIndex, final superclassName = constantPool.getConstantString(superclassNameIndex, Const.CONSTANT_Class); superclassName = Utility.compactClassName(superclassName, false); } else { - superclassName = "java.lang.Object"; + superclassName = CLASS_NAME_OBJECT; } interfaceNames = new String[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { @@ -235,7 +247,7 @@ public JavaClass(final int classNameIndex, final int superclassNameIndex, final * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -291,7 +303,9 @@ private void computeNestedTypeStatus() { } /** - * @return deep copy of this class + * Creates a deep copy of this class. + * + * @return deep copy of this class. */ public JavaClass copy() { try { @@ -312,10 +326,10 @@ public JavaClass copy() { } /** - * Dump Java class to output stream in binary format. + * Dumps Java class to output stream in binary format. * - * @param file Output stream - * @throws IOException if an I/O error occurs. + * @param file Output stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeInt(Const.JVM_CLASSFILE_MAGIC); @@ -325,20 +339,20 @@ public void dump(final DataOutputStream file) throws IOException { file.writeShort(super.getAccessFlags()); file.writeShort(classNameIndex); file.writeShort(superclassNameIndex); - file.writeShort(interfaces.length); + file.writeShort(Args.requireU2(interfaces.length, "interfaces.length")); for (final int interface1 : interfaces) { file.writeShort(interface1); } - file.writeShort(fields.length); + file.writeShort(Args.requireU2(fields.length, "fields.length")); for (final Field field : fields) { field.dump(file); } - file.writeShort(methods.length); + file.writeShort(Args.requireU2(methods.length, "methods.length")); for (final Method method : methods) { method.dump(file); } if (attributes != null) { - file.writeShort(attributes.length); + file.writeShort(Args.requireU2(attributes.length, "attributes.length")); for (final Attribute attribute : attributes) { attribute.dump(file); } @@ -349,10 +363,10 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * Dump class to a file. + * Dumps class to a file. * - * @param file Output file - * @throws IOException if an I/O error occurs. + * @param file Output file. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final File file) throws IOException { final String parent = file.getParent(); @@ -368,20 +382,20 @@ public void dump(final File file) throws IOException { } /** - * Dump Java class to output stream in binary format. + * Dumps Java class to output stream in binary format. * - * @param file Output stream - * @throws IOException if an I/O error occurs. + * @param file Output stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final OutputStream file) throws IOException { dump(new DataOutputStream(file)); } /** - * Dump class to a file named fileName. + * Dumps class to a file named fileName. * - * @param fileName Output file name - * @throws IOException if an I/O error occurs. + * @param fileName Output file name. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final String fileName) throws IOException { dump(new File(fileName)); @@ -400,55 +414,69 @@ public boolean equals(final Object obj) { /** * Finds a visible field by name and type in this class and its super classes. - * @param fieldName the field name to find - * @param fieldType the field type to find + * + * @param fieldName The field name to find. + * @param fieldType The field type to find. * @return field matching given name and type, null if field is not found or not accessible from this class. - * @throws ClassNotFoundException + * @throws ClassNotFoundException Thrown if the class cannot be found. * @since 6.8.0 */ public Field findField(final String fieldName, final Type fieldType) throws ClassNotFoundException { - for (final Field field : fields) { - if (field.getName().equals(fieldName)) { - final Type fType = Type.getType(field.getSignature()); - /* - * TODO: Check if assignment compatibility is sufficient. What does Sun do? - */ - if (fType.equals(fieldType)) { - return field; - } - } - } + return findFieldVisit(fieldName, fieldType, new HashSet<>()); + } - final JavaClass superclass = getSuperClass(); - if (superclass != null && !"java.lang.Object".equals(superclass.getClassName())) { - final Field f = superclass.findField(fieldName, fieldType); - if (f != null && (f.isPublic() || f.isProtected() || !f.isPrivate() && packageName.equals(superclass.getPackageName()))) { - return f; - } + private Field findFieldVisit(final String fieldName, final Type fieldType, final Set visiting) throws ClassNotFoundException { + if (!visiting.add(this)) { + throw new ClassFormatException(getClassName()); } - final JavaClass[] implementedInterfaces = getInterfaces(); - if (implementedInterfaces != null) { - for (final JavaClass implementedInterface : implementedInterfaces) { - final Field f = implementedInterface.findField(fieldName, fieldType); - if (f != null) { + try { + for (final Field field : fields) { + if (field.getName().equals(fieldName)) { + final Type fType = Type.getType(field.getSignature()); + // TODO: Check if assignment compatibility is sufficient. What does Sun do? + if (fType.equals(fieldType)) { + return field; + } + } + } + final JavaClass superclass = getSuperClass(); + if (superclass != null && !CLASS_NAME_OBJECT.equals(superclass.getClassName())) { + final Field f = superclass.findFieldVisit(fieldName, fieldType, visiting); + if (f != null && (f.isPublic() || f.isProtected() || !f.isPrivate() && packageName.equals(superclass.getPackageName()))) { return f; } } + final JavaClass[] implementedInterfaces = getInterfaces(); + if (implementedInterfaces != null) { + for (final JavaClass implementedInterface : implementedInterfaces) { + final Field f = implementedInterface.findFieldVisit(fieldName, fieldType, visiting); + if (f != null) { + return f; + } + } + } + return null; + } finally { + visiting.remove(this); } - return null; } /** * Gets all interfaces implemented by this JavaClass (transitively). * - * @throws ClassNotFoundException if any of the class's superclasses or interfaces can't be found. + * @return all interfaces. + * @throws ClassNotFoundException Thrown if any of the class's superclasses or interfaces can't be found. */ public JavaClass[] getAllInterfaces() throws ClassNotFoundException { final ClassQueue queue = new ClassQueue(); final Set allInterfaces = new TreeSet<>(); + final Set visited = new HashSet<>(); queue.enqueue(this); while (!queue.empty()) { final JavaClass clazz = queue.dequeue(); + if (!visited.add(clazz)) { + continue; + } final JavaClass souper = clazz.getSuperClass(); final JavaClass[] interfaces = clazz.getInterfaces(); if (clazz.isInterface()) { @@ -464,7 +492,9 @@ public JavaClass[] getAllInterfaces() throws ClassNotFoundException { } /** - * @return Annotations on the class + * Gets annotations on the class. + * + * @return Annotations on the class. * @since 6.0 */ public AnnotationEntry[] getAnnotationEntries() { @@ -477,6 +507,9 @@ public AnnotationEntry[] getAnnotationEntries() { /** * Gets attribute for given tag. + * + * @param The attribute type. + * @param tag The attribute tag. * @return Attribute for given tag, null if not found. * Refer to {@link com.sun.org.apache.bcel.internal.Const#ATTR_UNKNOWN} constants named ATTR_* for possible values. * @since 6.10.0 @@ -492,6 +525,8 @@ public final T getAttribute(final byte tag) { } /** + * Gets attributes of the class. + * * @return Attributes of the class. */ public Attribute[] getAttributes() { @@ -499,7 +534,9 @@ public Attribute[] getAttributes() { } /** - * @return class in binary format + * Gets class in binary format. + * + * @return class in binary format. */ public byte[] getBytes() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -512,6 +549,8 @@ public byte[] getBytes() { } /** + * Gets the class name. + * * @return Class name. */ public String getClassName() { @@ -519,6 +558,8 @@ public String getClassName() { } /** + * Gets the class name index. + * * @return Class name index. */ public int getClassNameIndex() { @@ -526,6 +567,8 @@ public int getClassNameIndex() { } /** + * Gets the constant pool. + * * @return Constant pool. */ public ConstantPool getConstantPool() { @@ -533,7 +576,9 @@ public ConstantPool getConstantPool() { } /** - * @return Fields, i.e., variables of the class. Like the JVM spec mandates for the classfile format, these fields are + * Gets the fields. + * + * @return Fields, that is, variables of the class. Like the JVM spec mandates for the classfile format, these fields are * those specific to this class, and not those of the superclass or superinterfaces. */ public Field[] getFields() { @@ -541,13 +586,17 @@ public Field[] getFields() { } /** - * @return File name of class, aka SourceFile attribute value + * Gets the file name of class. + * + * @return File name of class, aka SourceFile attribute value. */ public String getFileName() { return fileName; } /** + * Gets indices in constant pool of implemented interfaces. + * * @return Indices in constant pool of implemented interfaces. */ public int[] getInterfaceIndices() { @@ -555,6 +604,8 @@ public int[] getInterfaceIndices() { } /** + * Gets names of implemented interfaces. + * * @return Names of implemented interfaces. */ public String[] getInterfaceNames() { @@ -564,7 +615,8 @@ public String[] getInterfaceNames() { /** * Gets interfaces directly implemented by this JavaClass. * - * @throws ClassNotFoundException if any of the class's interfaces can't be found. + * @return The interfaces. + * @throws ClassNotFoundException Thrown if any of the class's interfaces can't be found. */ public JavaClass[] getInterfaces() throws ClassNotFoundException { final String[] interfaces = getInterfaceNames(); @@ -576,6 +628,8 @@ public JavaClass[] getInterfaces() throws ClassNotFoundException { } /** + * Gets the major number of class file version. + * * @return Major number of class file version. */ public int getMajor() { @@ -583,7 +637,10 @@ public int getMajor() { } /** - * @return A {@link Method} corresponding to java.lang.reflect.Method if any + * Gets a Method corresponding to java.lang.reflect.Method if any. + * + * @param m The method to find. + * @return A {@link Method} corresponding to java.lang.reflect.Method if any. */ public Method getMethod(final java.lang.reflect.Method m) { for (final Method method : methods) { @@ -595,6 +652,8 @@ public Method getMethod(final java.lang.reflect.Method m) { } /** + * Gets the methods of the class. + * * @return Methods of the class. */ public Method[] getMethods() { @@ -602,6 +661,8 @@ public Method[] getMethods() { } /** + * Gets the minor number of class file version. + * * @return Minor number of class file version. */ public int getMinor() { @@ -609,6 +670,8 @@ public int getMinor() { } /** + * Gets the package name. + * * @return Package name. */ public String getPackageName() { @@ -617,21 +680,27 @@ public String getPackageName() { /** * Gets the ClassRepository which holds its definition. By default this is the same as - * SyntheticRepository.getInstance(); + * SyntheticRepository.getInstance(). + * + * @return The repository. */ public com.sun.org.apache.bcel.internal.util.Repository getRepository() { return repository; } /** - * @return returns either HEAP (generated), FILE, or ZIP + * Gets the source. + * + * @return either HEAP (generated), FILE, or ZIP. */ public final byte getSource() { return source; } /** - * @return file name where this class was read from + * Gets the file name where this class was read from. + * + * @return file name where this class was read from. */ public String getSourceFileName() { return sourceFileName; @@ -654,24 +723,33 @@ public String getSourceFilePath() { } /** - * @return the superclass for this JavaClass object, or null if this is {@link Object} - * @throws ClassNotFoundException if the superclass can't be found + * Gets the superclass for this JavaClass object, or null if this is {@link Object}. + * + * @return The superclass for this JavaClass object, or null if this is {@link Object}. + * @throws ClassNotFoundException Thrown if the superclass can't be found. */ public JavaClass getSuperClass() throws ClassNotFoundException { - if ("java.lang.Object".equals(getClassName())) { + if (CLASS_NAME_OBJECT.equals(getClassName())) { return null; } return repository.loadClass(getSuperclassName()); } /** - * @return list of super classes of this class in ascending order, i.e., java.lang.Object is always the last element - * @throws ClassNotFoundException if any of the superclasses can't be found + * Gets list of super classes of this class in ascending order. + * + * @return list of super classes of this class in ascending order, that is, {@link Object} is always the last element. + * @throws ClassNotFoundException Thrown if any of the superclasses can't be found. */ public JavaClass[] getSuperClasses() throws ClassNotFoundException { JavaClass clazz = this; final List allSuperClasses = new ArrayList<>(); + final Set visited = new HashSet<>(); + visited.add(this); for (clazz = clazz.getSuperClass(); clazz != null; clazz = clazz.getSuperClass()) { + if (!visited.add(clazz)) { + throw new ClassFormatException(clazz.getClassName()); + } allSuperClasses.add(clazz); } return allSuperClasses.toArray(EMPTY_ARRAY); @@ -688,6 +766,8 @@ public String getSuperclassName() { } /** + * Gets the class name index. + * * @return Class name index. */ public int getSuperclassNameIndex() { @@ -705,8 +785,11 @@ public int hashCode() { } /** - * @return true, if this class is an implementation of interface inter - * @throws ClassNotFoundException if superclasses or superinterfaces of this class can't be found + * Checks if this class is an implementation of interface inter. + * + * @param inter The interface to check. + * @return true, if this class is an implementation of interface inter. + * @throws ClassNotFoundException Thrown if superclasses or superinterfaces of this class can't be found. */ public boolean implementationOf(final JavaClass inter) throws ClassNotFoundException { if (!inter.isInterface()) { @@ -727,8 +810,9 @@ public boolean implementationOf(final JavaClass inter) throws ClassNotFoundExcep /** * Equivalent to runtime "instanceof" operator. * - * @return true if this JavaClass is derived from the super class - * @throws ClassNotFoundException if superclasses or superinterfaces of this object can't be found + * @param superclass The superclass to check. + * @return true if this JavaClass is derived from the super class. + * @throws ClassNotFoundException Thrown if superclasses or superinterfaces of this object can't be found. */ public final boolean instanceOf(final JavaClass superclass) throws ClassNotFoundException { if (equals(superclass)) { @@ -746,6 +830,9 @@ public final boolean instanceOf(final JavaClass superclass) throws ClassNotFound } /** + * Checks if this class is anonymous. + * + * @return true if anonymous. * @since 6.0 */ public final boolean isAnonymous() { @@ -753,11 +840,19 @@ public final boolean isAnonymous() { return this.isAnonymous; } + /** + * Checks if this is a class. + * + * @return true if this is a class. + */ public final boolean isClass() { return (super.getAccessFlags() & Const.ACC_INTERFACE) == 0; } /** + * Checks if this class is nested. + * + * @return true if nested. * @since 6.0 */ public final boolean isNested() { @@ -776,82 +871,109 @@ public boolean isRecord() { return this.isRecord; } + /** + * Checks if this is a super class. + * + * @return true if this is a super class. + */ public final boolean isSuper() { return (super.getAccessFlags() & Const.ACC_SUPER) != 0; } /** - * @param attributes . + * Sets the attributes. + * + * @param attributes The attributes. */ public void setAttributes(final Attribute[] attributes) { this.attributes = attributes != null ? attributes : Attribute.EMPTY_ARRAY; } /** - * @param className . + * Sets the class name. + * + * @param className The class name. */ public void setClassName(final String className) { this.className = className; } /** - * @param classNameIndex . + * Sets the class name index. + * + * @param classNameIndex The class name index. */ public void setClassNameIndex(final int classNameIndex) { this.classNameIndex = classNameIndex; } /** - * @param constantPool . + * Sets the constant pool. + * + * @param constantPool The constant pool. */ public void setConstantPool(final ConstantPool constantPool) { this.constantPool = constantPool; } /** - * @param fields . + * Sets the fields. + * + * @param fields The fields. */ public void setFields(final Field[] fields) { this.fields = fields != null ? fields : Field.EMPTY_ARRAY; } /** - * Sets File name of class, aka SourceFile attribute value + * Sets File name of class, aka SourceFile attribute value. + * + * @param fileName The file name. */ public void setFileName(final String fileName) { this.fileName = fileName; } /** - * @param interfaceNames . + * Sets the interface names. + * + * @param interfaceNames The interface names. */ public void setInterfaceNames(final String[] interfaceNames) { this.interfaceNames = Utils.createEmptyArrayIfNull(interfaceNames, String[].class); } /** - * @param interfaces . + * Sets the interfaces. + * + * @param interfaces The interfaces. */ public void setInterfaces(final int[] interfaces) { this.interfaces = Utils.createEmptyArrayIfNull(interfaces); } /** - * @param major . + * Sets the major version. + * + * @param major The major version. */ public void setMajor(final int major) { this.major = major; } /** - * @param methods . + * Sets the methods. + * + * @param methods The methods. */ public void setMethods(final Method[] methods) { this.methods = methods != null ? methods : Method.EMPTY_ARRAY; } /** - * @param minor . + * Sets the minor version. + * + * @param minor The minor version. */ public void setMinor(final int minor) { this.minor = minor; @@ -859,6 +981,8 @@ public void setMinor(final int minor) { /** * Sets the ClassRepository which loaded the JavaClass. Should be called immediately after parsing is done. + * + * @param repository The repository. */ public void setRepository(final com.sun.org.apache.bcel.internal.util.Repository repository) { // TODO make protected? this.repository = repository; @@ -866,20 +990,26 @@ public void setRepository(final com.sun.org.apache.bcel.internal.util.Repository /** * Sets absolute path to file this class was read from. + * + * @param sourceFileName The source file name. */ public void setSourceFileName(final String sourceFileName) { this.sourceFileName = sourceFileName; } /** - * @param superclassName . + * Sets the superclass name. + * + * @param superclassName The superclass name. */ public void setSuperclassName(final String superclassName) { this.superclassName = superclassName; } /** - * @param superclassNameIndex . + * Sets the superclass name index. + * + * @param superclassNameIndex The superclass name index. */ public void setSuperclassNameIndex(final int superclassNameIndex) { this.superclassNameIndex = superclassNameIndex; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumber.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumber.java index dc41ad065f84..7fdf53f356f9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumber.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumber.java @@ -28,7 +28,7 @@ import com.sun.org.apache.bcel.internal.util.Args; /** - * This class represents a (PC offset, line number) pair, i.e., a line number in the source that corresponds to a + * This class represents a (PC offset, line number) pair, that is, a line number in the source that corresponds to a * relative address in the byte code. This is used for debugging purposes. * * @see LineNumberTable @@ -37,25 +37,27 @@ public final class LineNumber implements Cloneable, Node { static final LineNumber[] EMPTY_ARRAY = {}; - /** Program Counter (PC) corresponds to line */ + /** Program Counter (PC) corresponds to line. */ private int startPc; - /** Number in source file */ + /** Number in source file. */ private int lineNumber; /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O Exception occurs in readUnsignedShort + * @param file Input stream. + * @throws IOException Thrown if an I/O Exception occurs in readUnsignedShort. */ LineNumber(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort()); } /** - * @param startPc Program Counter (PC) corresponds to - * @param lineNumber line number in source file + * Constructs a LineNumber. + * + * @param startPc Program Counter (PC) corresponds to. + * @param lineNumber line number in source file. */ public LineNumber(final int startPc, final int lineNumber) { this.startPc = Args.requireU2(startPc, "startPc"); @@ -65,7 +67,7 @@ public LineNumber(final int startPc, final int lineNumber) { /** * Initialize from another object. * - * @param c the object to copy + * @param c The object to copy. */ public LineNumber(final LineNumber c) { this(c.getStartPC(), c.getLineNumber()); @@ -75,7 +77,7 @@ public LineNumber(final LineNumber c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -83,7 +85,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public LineNumber copy() { try { @@ -95,10 +99,10 @@ public LineNumber copy() { } /** - * Dump line number/pc pair to file stream in binary format. + * Dumps line number/pc pair to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(startPc); @@ -106,35 +110,43 @@ public void dump(final DataOutputStream file) throws IOException { } /** - * @return Corresponding source line + * Gets the line number. + * + * @return Corresponding source line. */ public int getLineNumber() { return lineNumber & 0xffff; } /** - * @return PC in code + * Gets the program counter. + * + * @return PC in code. */ public int getStartPC() { return startPc & 0xffff; } /** - * @param lineNumber the source line number + * Sets the line number. + * + * @param lineNumber The source line number. */ public void setLineNumber(final int lineNumber) { this.lineNumber = (short) lineNumber; } /** - * @param startPc the pc for this line number + * Sets the program counter. + * + * @param startPc The pc for this line number. */ public void setStartPC(final int startPc) { this.startPc = (short) startPc; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumberTable.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumberTable.java index 96541f309bd2..03af3c9448ad 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumberTable.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LineNumberTable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -36,7 +36,7 @@ * * @see Code * @see LineNumber - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class LineNumberTable extends Attribute implements Iterable { @@ -46,11 +46,11 @@ public final class LineNumberTable extends Attribute implements Iterable * Note that both objects use the same references (shallow copy). Use copy() for a physical copy. *

+ * + * @param c The instance to copy. */ public LineNumberTable(final LineNumberTable c) { this(c.getNameIndex(), c.getLength(), c.getLineNumberTable(), c.getConstantPool()); @@ -89,7 +91,7 @@ public LineNumberTable(final LineNumberTable c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -97,7 +99,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -111,21 +113,23 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump line number table attribute to file stream in binary format. + * Dumps line number table attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(lineNumberTable.length); + file.writeShort(Args.requireU2(lineNumberTable.length, "lineNumberTable.length")); for (final LineNumber lineNumber : lineNumberTable) { lineNumber.dump(file); } } /** + * Gets the line number table. + * * @return Array of (pc offset, line number) pairs. */ public LineNumber[] getLineNumberTable() { @@ -135,8 +139,8 @@ public LineNumber[] getLineNumberTable() { /** * Map byte code positions to source code lines. * - * @param pos byte code offset - * @return corresponding line in source code + * @param pos byte code offset. + * @return corresponding line in source code. */ public int getSourceLine(final int pos) { int l = 0; @@ -178,8 +182,13 @@ public int getSourceLine(final int pos) { return lineNumberTable[minIndex].getLineNumber(); } + /** + * Gets the length of the line number table. + * + * @return The length of the line number table. + */ public int getTableLength() { - return lineNumberTable == null ? 0 : lineNumberTable.length; + return lineNumberTable.length; } @Override @@ -188,7 +197,9 @@ public Iterator iterator() { } /** - * @param lineNumberTable the line number entries for this table + * Sets the line number table. + * + * @param lineNumberTable The line number entries for this table. */ public void setLineNumberTable(final LineNumber[] lineNumberTable) { this.lineNumberTable = lineNumberTable != null ? lineNumberTable : LineNumber.EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariable.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariable.java index 91d99c18288a..c1ffd0e2f9c0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariable.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -34,10 +34,9 @@ * LocalVariableTypeTable attribute does have a signatureIndex. * * @see com.sun.org.apache.bcel.internal.classfile.Utility for more details on the difference. - * * @see LocalVariableTable * @see LocalVariableTypeTable - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public final class LocalVariable implements Cloneable, Node { @@ -69,33 +68,37 @@ public final class LocalVariable implements Cloneable, Node { /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. */ LocalVariable(final DataInput file, final ConstantPool constantPool) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), constantPool); } /** - * @param startPc Range in which the variable - * @param length ... is valid - * @param nameIndex Index in constant pool of variable name - * @param signatureIndex Index of variable's signature - * @param index Variable is 'index'th local variable on the method's frame - * @param constantPool Array of constants + * Constructs a LocalVariable. + * + * @param startPc Range in which the variable is valid. + * @param length length of validity. + * @param nameIndex Index in constant pool of variable name. + * @param signatureIndex Index of variable's signature. + * @param index Variable is 'index'th local variable on the method's frame. + * @param constantPool Array of constants. */ public LocalVariable(final int startPc, final int length, final int nameIndex, final int signatureIndex, final int index, final ConstantPool constantPool) { this(startPc, length, nameIndex, signatureIndex, index, constantPool, index); } /** - * @param startPc Range in which the variable - * @param length ... is valid - * @param nameIndex Index in constant pool of variable name - * @param signatureIndex Index of variable's signature - * @param index Variable is 'index'th local variable on the method's frame - * @param constantPool Array of constants - * @param origIndex Variable is 'index'th local variable on the method's frame prior to any changes + * Constructs a LocalVariable. + * + * @param startPc Range in which the variable is valid. + * @param length length of validity. + * @param nameIndex Index in constant pool of variable name. + * @param signatureIndex Index of variable's signature. + * @param index Variable is 'index'th local variable on the method's frame. + * @param constantPool Array of constants. + * @param origIndex Variable is 'index'th local variable on the method's frame prior to any changes. */ public LocalVariable(final int startPc, final int length, final int nameIndex, final int signatureIndex, final int index, final ConstantPool constantPool, final int origIndex) { @@ -123,7 +126,7 @@ public LocalVariable(final LocalVariable localVariable) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -131,7 +134,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public LocalVariable copy() { try { @@ -145,8 +150,8 @@ public LocalVariable copy() { /** * Dumps local variable to file stream in binary format. * - * @param dataOutputStream Output file stream - * @throws IOException if an I/O error occurs. + * @param dataOutputStream Output file stream. + * @throws IOException Thrown if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void dump(final DataOutputStream dataOutputStream) throws IOException { @@ -158,6 +163,8 @@ public void dump(final DataOutputStream dataOutputStream) throws IOException { } /** + * Gets the constant pool used by this object. + * * @return Constant pool used by this object. */ public ConstantPool getConstantPool() { @@ -165,20 +172,26 @@ public ConstantPool getConstantPool() { } /** - * @return index of register where variable is stored + * Gets the index of register where variable is stored. + * + * @return index of register where variable is stored. */ public int getIndex() { return index; } /** - * @return Variable is valid within getStartPC() .. getStartPC()+getLength() + * Gets the length of validity. + * + * @return Variable is valid within getStartPC() .. getStartPC()+getLength(). */ public int getLength() { return length; } /** + * Gets the variable name. + * * @return Variable name. */ public String getName() { @@ -186,6 +199,8 @@ public String getName() { } /** + * Gets the index in constant pool of variable name. + * * @return Index in constant pool of variable name. */ public int getNameIndex() { @@ -193,13 +208,17 @@ public int getNameIndex() { } /** - * @return index of register where variable was originally stored + * Gets the index of register where variable was originally stored. + * + * @return index of register where variable was originally stored. */ public int getOrigIndex() { return origIndex; } /** + * Gets the signature. + * * @return Signature. */ public String getSignature() { @@ -207,6 +226,8 @@ public String getSignature() { } /** + * Gets the index in constant pool of variable signature. + * * @return Index in constant pool of variable signature. */ public int getSignatureIndex() { @@ -214,13 +235,17 @@ public int getSignatureIndex() { } /** - * @return Start of range where the variable is valid + * Gets the start of range where the variable is valid. + * + * @return Start of range where the variable is valid. */ public int getStartPC() { return startPc; } /** + * Sets the constant pool to be used for this object. + * * @param constantPool Constant pool to be used for this object. */ public void setConstantPool(final ConstantPool constantPool) { @@ -228,34 +253,44 @@ public void setConstantPool(final ConstantPool constantPool) { } /** - * @param index the index in the local variable table of this variable + * Sets the index in the local variable table of this variable. + * + * @param index The index in the local variable table of this variable. */ public void setIndex(final int index) { // TODO unused this.index = index; } /** - * @param length the length of this local variable + * Sets the length of this local variable. + * + * @param length The length of this local variable. */ public void setLength(final int length) { this.length = length; } /** - * @param nameIndex the index into the constant pool for the name of this variable + * Sets the index into the constant pool for the name of this variable. + * + * @param nameIndex The index into the constant pool for the name of this variable. */ public void setNameIndex(final int nameIndex) { // TODO unused this.nameIndex = nameIndex; } /** - * @param signatureIndex the index into the constant pool for the signature of this variable + * Sets the index into the constant pool for the signature of this variable. + * + * @param signatureIndex The index into the constant pool for the signature of this variable. */ public void setSignatureIndex(final int signatureIndex) { // TODO unused this.signatureIndex = signatureIndex; } /** + * Sets the range where the local variable is valid. + * * @param startPc Specify range where the local variable is valid. */ public void setStartPC(final int startPc) { // TODO unused @@ -263,6 +298,8 @@ public void setStartPC(final int startPc) { // TODO unused } /** + * Gets the string representation. + * * @return string representation. */ @Override diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTable.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTable.java index 26fde9bdbdff..fc3169af25b6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTable.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTable.java @@ -47,11 +47,11 @@ public class LocalVariableTable extends Attribute implements Iterable= startPc && pc <= endPc) { + if (pc >= startPc && pc < endPc) { return variable; } } @@ -162,12 +162,19 @@ public final LocalVariable getLocalVariable(final int index, final int pc) { } /** + * Gets the local variable table. + * * @return Array of local variables of method. */ public final LocalVariable[] getLocalVariableTable() { return localVariableTable; } + /** + * Gets the table length. + * + * @return The table length. + */ public final int getTableLength() { return localVariableTable.length; } @@ -177,6 +184,11 @@ public Iterator iterator() { return Stream.of(localVariableTable).iterator(); } + /** + * Sets the local variable table. + * + * @param localVariableTable The local variable table to set. + */ public final void setLocalVariableTable(final LocalVariable[] localVariableTable) { this.localVariableTable = localVariableTable != null ? localVariableTable : EMPTY_ARRAY; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTypeTable.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTypeTable.java index ce327e20f523..35faace0a5ad 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTypeTable.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/LocalVariableTypeTable.java @@ -59,6 +59,8 @@ // J5TODO: Needs some testing ! /** + * Represents the LocalVariableTypeTable attribute. + * * @since 6.0 */ public class LocalVariableTypeTable extends Attribute implements Iterable { @@ -76,12 +78,25 @@ public class LocalVariableTypeTable extends Attribute implements Iterable iterator() { return Stream.of(localVariableTypeTable).iterator(); } + /** + * Sets the local variable table. + * + * @param localVariableTable The local variable table to set. + */ public final void setLocalVariableTable(final LocalVariable[] localVariableTable) { this.localVariableTypeTable = localVariableTable != null ? localVariableTable : EMPTY_ARRAY; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Method.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Method.java index 643c820f3661..74bce2ab130d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Method.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Method.java @@ -28,7 +28,7 @@ import com.sun.org.apache.bcel.internal.util.BCELComparator; /** - * This class represents the method info structure, i.e., the representation for a method in the class. See JVM + * This class represents the method info structure, that is, the representation for a method in the class. See JVM * specification for details. A method has access flags, a name, a signature and a number of attributes. */ public final class Method extends FieldOrMethod { @@ -54,6 +54,8 @@ public int hashCode(final Method o) { }; /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -61,6 +63,8 @@ public static BCELComparator getComparator() { } /** + * Sets the comparison strategy object. + * * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { @@ -79,20 +83,22 @@ public Method() { /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param file Input stream. + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file. */ Method(final DataInput file, final ConstantPool constantPool) throws IOException, ClassFormatException { super(file, constantPool); } /** - * @param accessFlags Access rights of method - * @param nameIndex Points to field name in constant pool - * @param signatureIndex Points to encoded signature - * @param attributes Collection of attributes - * @param constantPool Array of constants + * Constructs a Method. + * + * @param accessFlags Access rights of method. + * @param nameIndex Points to field name in constant pool. + * @param signatureIndex Points to encoded signature. + * @param attributes Collection of attributes. + * @param constantPool Array of constants. */ public Method(final int accessFlags, final int nameIndex, final int signatureIndex, final Attribute[] attributes, final ConstantPool constantPool) { super(accessFlags, nameIndex, signatureIndex, attributes, constantPool); @@ -112,7 +118,7 @@ public Method(final Method c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -120,7 +126,10 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this method + * Creates a deep copy of this method. + * + * @param constantPool The constant pool. + * @return deep copy of this method. */ public Method copy(final ConstantPool constantPool) { return (Method) copy_(constantPool); @@ -138,14 +147,18 @@ public boolean equals(final Object obj) { } /** - * @return array of method argument types + * Gets array of method argument types. + * + * @return array of method argument types. */ public Type[] getArgumentTypes() { return Type.getArgumentTypes(getSignature()); } /** - * @return Code attribute of method, if any + * Gets Code attribute of method, if any. + * + * @return Code attribute of method, if any. */ public Code getCode() { for (final Attribute attribute : super.getAttributes()) { @@ -157,8 +170,9 @@ public Code getCode() { } /** - * @return ExceptionTable attribute of method, if any, i.e., list all exceptions the method may throw not exception - * handlers! + * Gets ExceptionTable attribute of method, if any. + * + * @return ExceptionTable attribute of method, if any, that is, list all exceptions the method may throw not exception handlers. */ public ExceptionTable getExceptionTable() { for (final Attribute attribute : super.getAttributes()) { @@ -170,7 +184,9 @@ public ExceptionTable getExceptionTable() { } /** - * @return LineNumberTable of code attribute if any, i.e. the call is forwarded to the Code atribute. + * Gets LineNumberTable of code attribute if any. + * + * @return LineNumberTable of code attribute if any, for example the call is forwarded to the Code attribute. */ public LineNumberTable getLineNumberTable() { final Code code = getCode(); @@ -181,7 +197,9 @@ public LineNumberTable getLineNumberTable() { } /** - * @return LocalVariableTable of code attribute if any, i.e. the call is forwarded to the Code attribute. + * Gets LocalVariableTable of code attribute if any. + * + * @return LocalVariableTable of code attribute if any, for example the call is forwarded to the Code attribute. */ public LocalVariableTable getLocalVariableTable() { final Code code = getCode(); @@ -193,7 +211,8 @@ public LocalVariableTable getLocalVariableTable() { /** * Gets the local variable type table attribute {@link LocalVariableTypeTable}. - * @return LocalVariableTypeTable of code attribute if any, i.e. the call is forwarded to the Code attribute. + * + * @return LocalVariableTypeTable of code attribute if any, for example the call is forwarded to the Code attribute. * @since 6.10.0 */ public LocalVariableTypeTable getLocalVariableTypeTable() { @@ -205,7 +224,9 @@ public LocalVariableTypeTable getLocalVariableTypeTable() { } /** - * @return Annotations on the parameters of a method + * Gets Annotations on the parameters of a method. + * + * @return Annotations on the parameters of a method. * @since 6.0 */ public ParameterAnnotationEntry[] getParameterAnnotationEntries() { @@ -216,7 +237,9 @@ public ParameterAnnotationEntry[] getParameterAnnotationEntries() { } /** - * @return return type of method + * Gets return type of method. + * + * @return return type of method. */ public Type getReturnType() { return Type.getReturnType(getSignature()); @@ -235,7 +258,7 @@ public int hashCode() { /** * Return string representation close to declaration format, 'public static void main(String[] args) throws - * IOException', e.g. + * IOException', for example. * * @return String representation of the method. */ diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameter.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameter.java index 865e154d334a..f8cde7df5b9b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameter.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameter.java @@ -45,15 +45,18 @@ public class MethodParameter implements Cloneable, Node { /** The access flags */ private int accessFlags; + /** + * Constructs a MethodParameter. + */ public MethodParameter() { } /** * Constructs an instance from a DataInput. * - * @param input Input stream - * @throws IOException if an I/O error occurs. - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param input Input stream. + * @throws IOException Thrown if an I/O error occurs. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ MethodParameter(final DataInput input) throws IOException { nameIndex = input.readUnsignedShort(); @@ -66,7 +69,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public MethodParameter copy() { try { @@ -80,18 +85,28 @@ public MethodParameter copy() { /** * Dumps object to file stream on binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public final void dump(final DataOutputStream file) throws IOException { file.writeShort(nameIndex); file.writeShort(accessFlags); } + /** + * Gets the access flags. + * + * @return The access flags. + */ public int getAccessFlags() { return accessFlags; } + /** + * Gets the name index. + * + * @return The name index. + */ public int getNameIndex() { return nameIndex; } @@ -109,22 +124,47 @@ public String getParameterName(final ConstantPool constantPool) { return constantPool.getConstantUtf8(nameIndex).getBytes(); } + /** + * Checks if this parameter is final. + * + * @return true if this parameter is final. + */ public boolean isFinal() { return (accessFlags & Const.ACC_FINAL) != 0; } + /** + * Checks if this parameter is mandated. + * + * @return true if this parameter is mandated. + */ public boolean isMandated() { return (accessFlags & Const.ACC_MANDATED) != 0; } + /** + * Checks if this parameter is synthetic. + * + * @return true if this parameter is synthetic. + */ public boolean isSynthetic() { return (accessFlags & Const.ACC_SYNTHETIC) != 0; } + /** + * Sets the access flags. + * + * @param accessFlags The access flags. + */ public void setAccessFlags(final int accessFlags) { this.accessFlags = accessFlags; } + /** + * Sets the name index. + * + * @param nameIndex The name index. + */ public void setNameIndex(final int nameIndex) { this.nameIndex = nameIndex; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameters.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameters.java index 2f5bffd8d3c8..7f47e7fe60c5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameters.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/MethodParameters.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * This class represents a MethodParameters attribute. @@ -70,20 +71,25 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump method parameters attribute to file stream in binary format. + * Dumps method parameters attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeByte(parameters.length); + file.writeByte(Args.requireU1(parameters.length, "parameters.length")); for (final MethodParameter parameter : parameters) { parameter.dump(file); } } + /** + * Gets the method parameters. + * + * @return The method parameters. + */ public MethodParameter[] getParameters() { return parameters; } @@ -93,6 +99,11 @@ public Iterator iterator() { return Stream.of(parameters).iterator(); } + /** + * Sets the method parameters. + * + * @param parameters The method parameters to set. + */ public void setParameters(final MethodParameter[] parameters) { this.parameters = parameters != null ? parameters : EMPTY_ARRAY; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Module.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Module.java index addf6f0aea3b..5b4b11c6c3bb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Module.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Module.java @@ -27,6 +27,7 @@ import java.util.Arrays; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * This class is derived from Attribute and represents the list of modules required, exported, opened or @@ -66,47 +67,44 @@ private static String getClassNameAtIndex(final ConstantPool cp, final int index /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ - Module(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { + Module(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { super(Const.ATTR_MODULE, nameIndex, length, constantPool); - moduleNameIndex = input.readUnsignedShort(); - moduleFlags = input.readUnsignedShort(); - moduleVersionIndex = input.readUnsignedShort(); + moduleNameIndex = dataInput.readUnsignedShort(); + moduleFlags = dataInput.readUnsignedShort(); + moduleVersionIndex = dataInput.readUnsignedShort(); - final int requiresCount = input.readUnsignedShort(); + final int requiresCount = dataInput.readUnsignedShort(); requiresTable = new ModuleRequires[requiresCount]; for (int i = 0; i < requiresCount; i++) { - requiresTable[i] = new ModuleRequires(input); + requiresTable[i] = new ModuleRequires(dataInput); } - final int exportsCount = input.readUnsignedShort(); + final int exportsCount = dataInput.readUnsignedShort(); exportsTable = new ModuleExports[exportsCount]; for (int i = 0; i < exportsCount; i++) { - exportsTable[i] = new ModuleExports(input); + exportsTable[i] = new ModuleExports(dataInput); } - final int opensCount = input.readUnsignedShort(); + final int opensCount = dataInput.readUnsignedShort(); opensTable = new ModuleOpens[opensCount]; for (int i = 0; i < opensCount; i++) { - opensTable[i] = new ModuleOpens(input); + opensTable[i] = new ModuleOpens(dataInput); } - usesCount = input.readUnsignedShort(); - usesIndex = new int[usesCount]; - for (int i = 0; i < usesCount; i++) { - usesIndex[i] = input.readUnsignedShort(); - } + usesIndex = ClassParser.readU2U2Table(dataInput); + usesCount = usesIndex.length; - final int providesCount = input.readUnsignedShort(); + final int providesCount = dataInput.readUnsignedShort(); providesTable = new ModuleProvides[providesCount]; for (int i = 0; i < providesCount; i++) { - providesTable[i] = new ModuleProvides(input); + providesTable[i] = new ModuleProvides(dataInput); } } @@ -114,7 +112,7 @@ private static String getClassNameAtIndex(final ConstantPool cp, final int index * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -122,7 +120,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -145,10 +143,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump Module attribute to file stream in binary format. + * Dumps Module attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -158,34 +156,36 @@ public void dump(final DataOutputStream file) throws IOException { file.writeShort(moduleFlags); file.writeShort(moduleVersionIndex); - file.writeShort(requiresTable.length); + file.writeShort(Args.requireU2(requiresTable.length, "requiresTable.length")); for (final ModuleRequires entry : requiresTable) { entry.dump(file); } - file.writeShort(exportsTable.length); + file.writeShort(Args.requireU2(exportsTable.length, "exportsTable.length")); for (final ModuleExports entry : exportsTable) { entry.dump(file); } - file.writeShort(opensTable.length); + file.writeShort(Args.requireU2(opensTable.length, "opensTable.length")); for (final ModuleOpens entry : opensTable) { entry.dump(file); } - file.writeShort(usesIndex.length); + file.writeShort(Args.requireU2(usesIndex.length, "usesIndex.length")); for (final int entry : usesIndex) { file.writeShort(entry); } - file.writeShort(providesTable.length); + file.writeShort(Args.requireU2(providesTable.length, "providesTable.length")); for (final ModuleProvides entry : providesTable) { entry.dump(file); } } /** - * @return table of exported interfaces + * Gets the table of exported interfaces. + * + * @return table of exported interfaces. * @see ModuleExports */ public ModuleExports[] getExportsTable() { @@ -194,7 +194,8 @@ public ModuleExports[] getExportsTable() { /** * Gets flags for this module. - * @return module flags + * + * @return module flags. * @since 6.10.0 */ public int getModuleFlags() { @@ -203,8 +204,9 @@ public int getModuleFlags() { /** * Gets module name. - * @param cp Array of constants - * @return module name + * + * @param cp Array of constants. + * @return module name. * @since 6.10.0 */ public String getModuleName(final ConstantPool cp) { @@ -212,7 +214,9 @@ public String getModuleName(final ConstantPool cp) { } /** - * @return table of provided interfaces + * Gets the table of open interfaces. + * + * @return table of provided interfaces. * @see ModuleOpens */ public ModuleOpens[] getOpensTable() { @@ -220,7 +224,9 @@ public ModuleOpens[] getOpensTable() { } /** - * @return table of provided interfaces + * Gets the table of provided interfaces. + * + * @return table of provided interfaces. * @see ModuleProvides */ public ModuleProvides[] getProvidesTable() { @@ -228,7 +234,9 @@ public ModuleProvides[] getProvidesTable() { } /** - * @return table of required modules + * Gets the table of required modules. + * + * @return table of required modules. * @see ModuleRequires */ public ModuleRequires[] getRequiresTable() { @@ -237,9 +245,10 @@ public ModuleRequires[] getRequiresTable() { /** * Gets the array of class names for this module's uses. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @param compactClassName false for original constant pool value, true to replace '/' with '.' - * @return array of used class names + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @param compactClassName false for original constant pool value, true to replace '/' with '.'. + * @return array of used class names. * @since 6.10.0 */ public String[] getUsedClassNames(final ConstantPool constantPool, final boolean compactClassName) { @@ -252,8 +261,9 @@ public String[] getUsedClassNames(final ConstantPool constantPool, final boolean /** * Gets version for this module. - * @param cp Array of constants - * @return version from constant pool, "0" if version index is 0 + * + * @param cp Array of constants. + * @return version from constant pool, "0" if version index is 0. * @since 6.10.0 */ public String getVersion(final ConstantPool cp) { @@ -261,7 +271,7 @@ public String getVersion(final ConstantPool cp) { } /** - * @return String representation, i.e., a list of packages. + * @return String representation, that is, a list of packages. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleExports.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleExports.java index f92f508b8629..311cc0d19f81 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleExports.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleExports.java @@ -48,24 +48,21 @@ private static String getToModuleNameAtIndex(final ConstantPool constantPool, fi /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O Exception occurs in readUnsignedShort + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O Exception occurs in readUnsignedShort. */ - ModuleExports(final DataInput file) throws IOException { - exportsIndex = file.readUnsignedShort(); - exportsFlags = file.readUnsignedShort(); - exportsToCount = file.readUnsignedShort(); - exportsToIndex = new int[exportsToCount]; - for (int i = 0; i < exportsToCount; i++) { - exportsToIndex[i] = file.readUnsignedShort(); - } + ModuleExports(final DataInput dataInput) throws IOException { + exportsIndex = dataInput.readUnsignedShort(); + exportsFlags = dataInput.readUnsignedShort(); + exportsToIndex = ClassParser.readU2U2Table(dataInput); + exportsToCount = exportsToIndex.length; } /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -73,7 +70,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public ModuleExports copy() { try { @@ -85,10 +84,10 @@ public ModuleExports copy() { } /** - * Dump table entry to file stream in binary format. + * Dumps table entry to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(exportsIndex); @@ -101,7 +100,8 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets the flags for this ModuleExports. - * @return the exportsFlags + * + * @return The exportsFlags. * @since 6.10.0 */ public int getExportsFlags() { @@ -110,8 +110,9 @@ public int getExportsFlags() { /** * Gets the exported package name. - * @param constantPool the constant pool from the ClassFile - * @return the exported package name + * + * @param constantPool The constant pool from the ClassFile. + * @return The exported package name. * @since 6.10.0 */ public String getPackageName(final ConstantPool constantPool) { @@ -120,8 +121,9 @@ public String getPackageName(final ConstantPool constantPool) { /** * Gets an array of module names for this ModuleExports. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @return array of module names following 'exports to' + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @return array of module names following 'exports to'. * @since 6.10.0 */ public String[] getToModuleNames(final ConstantPool constantPool) { @@ -133,7 +135,7 @@ public String[] getToModuleNames(final ConstantPool constantPool) { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { @@ -141,7 +143,10 @@ public String toString() { } /** - * @return Resolved string representation + * Gets the resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public String toString(final ConstantPool constantPool) { final StringBuilder buf = new StringBuilder(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleMainClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleMainClass.java index b73bd01f7942..da10dfdd93b9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleMainClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleMainClass.java @@ -41,11 +41,11 @@ public final class ModuleMainClass extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ ModuleMainClass(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, 0, constantPool); @@ -53,13 +53,15 @@ public final class ModuleMainClass extends Attribute { } /** - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param mainClassIndex Host class index - * @param constantPool Array of constants + * Constructs a new ModuleMainClass. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param mainClassIndex Host class index. + * @param constantPool Array of constants. */ public ModuleMainClass(final int nameIndex, final int length, final int mainClassIndex, final ConstantPool constantPool) { - super(Const.ATTR_NEST_MEMBERS, nameIndex, length, constantPool); + super(Const.ATTR_MODULE_MAIN_CLASS, nameIndex, length, constantPool); this.mainClassIndex = Args.requireU2(mainClassIndex, "mainClassIndex"); } @@ -77,7 +79,7 @@ public ModuleMainClass(final ModuleMainClass c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., * the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -85,7 +87,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -95,10 +97,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump ModuleMainClass attribute to file stream in binary format. + * Dumps ModuleMainClass attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -107,6 +109,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the host class index. + * * @return index into constant pool of host class name. */ public int getHostClassIndex() { @@ -114,14 +118,16 @@ public int getHostClassIndex() { } /** - * @param mainClassIndex the host class index + * Sets the host class index. + * + * @param mainClassIndex The host class index. */ public void setHostClassIndex(final int mainClassIndex) { this.mainClassIndex = mainClassIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleOpens.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleOpens.java index 388370a45e7e..b349384ef88f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleOpens.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleOpens.java @@ -48,24 +48,21 @@ private static String getToModuleNameAtIndex(final ConstantPool constantPool, fi /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O Exception occurs in readUnsignedShort + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O Exception occurs in readUnsignedShort. */ - ModuleOpens(final DataInput file) throws IOException { - opensIndex = file.readUnsignedShort(); - opensFlags = file.readUnsignedShort(); - opensToCount = file.readUnsignedShort(); - opensToIndex = new int[opensToCount]; - for (int i = 0; i < opensToCount; i++) { - opensToIndex[i] = file.readUnsignedShort(); - } + ModuleOpens(final DataInput dataInput) throws IOException { + opensIndex = dataInput.readUnsignedShort(); + opensFlags = dataInput.readUnsignedShort(); + opensToIndex = ClassParser.readU2U2Table(dataInput); + opensToCount = opensToIndex.length; } /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -73,7 +70,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public ModuleOpens copy() { try { @@ -85,10 +84,10 @@ public ModuleOpens copy() { } /** - * Dump table entry to file stream in binary format. + * Dumps table entry to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(opensIndex); @@ -101,7 +100,8 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets the flags for this ModuleOpens. - * @return the opensFlags + * + * @return The opensFlags. * @since 6.10.0 */ public int getOpensFlags() { @@ -110,8 +110,9 @@ public int getOpensFlags() { /** * Gets the opened package name. - * @param constantPool the constant pool from the ClassFile - * @return the opened package name + * + * @param constantPool The constant pool from the ClassFile. + * @return The opened package name. * @since 6.10.0 */ public String getPackageName(final ConstantPool constantPool) { @@ -120,8 +121,9 @@ public String getPackageName(final ConstantPool constantPool) { /** * Gets an array of module names for this ModuleOpens. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @return array of module names following 'opens to' + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @return array of module names following 'opens to'. * @since 6.10.0 */ public String[] getToModuleNames(final ConstantPool constantPool) { @@ -133,7 +135,7 @@ public String[] getToModuleNames(final ConstantPool constantPool) { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { @@ -141,7 +143,10 @@ public String toString() { } /** - * @return Resolved string representation + * Gets the resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public String toString(final ConstantPool constantPool) { final StringBuilder buf = new StringBuilder(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModulePackages.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModulePackages.java index f48587e5455d..90b46a415d40 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModulePackages.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModulePackages.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -34,7 +34,7 @@ * Module attribute. There may be at most one ModulePackages attribute in a ClassFile structure. * * @see Attribute - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class ModulePackages extends Attribute { @@ -43,26 +43,24 @@ public final class ModulePackages extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ - ModulePackages(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { + ModulePackages(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (int[]) null, constantPool); - final int packageCount = input.readUnsignedShort(); - packageIndexTable = new int[packageCount]; - for (int i = 0; i < packageCount; i++) { - packageIndexTable[i] = input.readUnsignedShort(); - } + packageIndexTable = ClassParser.readU2U2Table(dataInput); } /** - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param packageIndexTable Table of indices in constant pool - * @param constantPool Array of constants + * Constructs a new ModulePackages. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param packageIndexTable Table of indices in constant pool. + * @param constantPool Array of constants. */ public ModulePackages(final int nameIndex, final int length, final int[] packageIndexTable, final ConstantPool constantPool) { super(Const.ATTR_MODULE_PACKAGES, nameIndex, length, constantPool); @@ -84,7 +82,7 @@ public ModulePackages(final ModulePackages c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -92,7 +90,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -105,21 +103,23 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump ModulePackages attribute to file stream in binary format. + * Dumps ModulePackages attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(packageIndexTable.length); + file.writeShort(Args.requireU2(packageIndexTable.length, "packageIndexTable.length")); for (final int index : packageIndexTable) { file.writeShort(index); } } /** + * Gets the number of packages. + * * @return Length of package table. */ public int getNumberOfPackages() { @@ -127,6 +127,8 @@ public int getNumberOfPackages() { } /** + * Gets the package index table. + * * @return array of indices into constant pool of package names. */ public int[] getPackageIndexTable() { @@ -134,7 +136,9 @@ public int[] getPackageIndexTable() { } /** - * @return string array of package names + * Gets the package names. + * + * @return string array of package names. */ public String[] getPackageNames() { final String[] names = new String[packageIndexTable.length]; @@ -143,14 +147,16 @@ public String[] getPackageNames() { } /** - * @param packageIndexTable the list of package indexes Also redefines number_of_packages according to table length. + * Sets the package index table. + * + * @param packageIndexTable The list of package indexes Also redefines number_of_packages according to table length. */ public void setPackageIndexTable(final int[] packageIndexTable) { this.packageIndexTable = Utils.createEmptyArrayIfNull(packageIndexTable); } /** - * @return String representation, i.e., a list of packages. + * @return String representation, that is, a list of packages. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleProvides.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleProvides.java index 490e9cd5d442..9faf0bd260f6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleProvides.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleProvides.java @@ -51,23 +51,20 @@ private static String getImplementationClassNameAtIndex(final ConstantPool const /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O Exception occurs in readUnsignedShort + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O Exception occurs in readUnsignedShort. */ - ModuleProvides(final DataInput file) throws IOException { - providesIndex = file.readUnsignedShort(); - providesWithCount = file.readUnsignedShort(); - providesWithIndex = new int[providesWithCount]; - for (int i = 0; i < providesWithCount; i++) { - providesWithIndex[i] = file.readUnsignedShort(); - } + ModuleProvides(final DataInput dataInput) throws IOException { + providesIndex = dataInput.readUnsignedShort(); + providesWithIndex = ClassParser.readU2U2Table(dataInput); + providesWithCount = providesWithIndex.length; } /** * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -75,7 +72,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public ModuleProvides copy() { try { @@ -87,10 +86,10 @@ public ModuleProvides copy() { } /** - * Dump table entry to file stream in binary format. + * Dumps table entry to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(providesIndex); @@ -102,9 +101,10 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets the array of implementation class names for this ModuleProvides. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @param compactClassName false for original constant pool value, true to replace '/' with '.' - * @return array of implementation class names + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @param compactClassName false for original constant pool value, true to replace '/' with '.'. + * @return array of implementation class names. * @since 6.10.0 */ public String[] getImplementationClassNames(final ConstantPool constantPool, final boolean compactClassName) { @@ -117,8 +117,9 @@ public String[] getImplementationClassNames(final ConstantPool constantPool, fin /** * Gets the interface name for this ModuleProvides. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @return interface name + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @return interface name. * @since 6.10.0 */ public String getInterfaceName(final ConstantPool constantPool) { @@ -126,7 +127,7 @@ public String getInterfaceName(final ConstantPool constantPool) { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { @@ -134,7 +135,10 @@ public String toString() { } /** - * @return Resolved string representation + * Gets the resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public String toString(final ConstantPool constantPool) { final StringBuilder buf = new StringBuilder(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleRequires.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleRequires.java index 3149a18290b3..e25a6cf8017f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleRequires.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ModuleRequires.java @@ -43,8 +43,8 @@ public final class ModuleRequires implements Cloneable, Node { /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O Exception occurs in readUnsignedShort + * @param file Input stream. + * @throws IOException Thrown if an I/O Exception occurs in readUnsignedShort. */ ModuleRequires(final DataInput file) throws IOException { requiresIndex = file.readUnsignedShort(); @@ -56,7 +56,7 @@ public final class ModuleRequires implements Cloneable, Node { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -64,7 +64,9 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public ModuleRequires copy() { try { @@ -76,10 +78,10 @@ public ModuleRequires copy() { } /** - * Dump table entry to file stream in binary format. + * Dumps table entry to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O Exception occurs in writeShort + * @param file Output file stream. + * @throws IOException Thrown if an I/O Exception occurs in writeShort. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(requiresIndex); @@ -89,8 +91,9 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets the module name from the constant pool. - * @param constantPool Array of constants usually obtained from the ClassFile object - * @return module name + * + * @param constantPool Array of constants usually obtained from the ClassFile object. + * @return module name. * @since 6.10.0 */ public String getModuleName(final ConstantPool constantPool) { @@ -99,7 +102,8 @@ public String getModuleName(final ConstantPool constantPool) { /** * Gets the flags for this ModuleRequires. - * @return the requiresFlags + * + * @return The requiresFlags. * @since 6.10.0 */ public int getRequiresFlags() { @@ -108,7 +112,8 @@ public int getRequiresFlags() { /** * Gets the required version from the constant pool. - * @param constantPool Array of constants usually obtained from the ClassFile object + * + * @param constantPool Array of constants usually obtained from the ClassFile object. * @return required version, "0" if version index is 0. * @since 6.10.0 */ @@ -117,7 +122,7 @@ public String getVersion(final ConstantPool constantPool) { } /** - * @return String representation + * @return String representation. */ @Override public String toString() { @@ -125,7 +130,10 @@ public String toString() { } /** - * @return Resolved string representation + * Gets the resolved string representation. + * + * @param constantPool The constant pool. + * @return Resolved string representation. */ public String toString(final ConstantPool constantPool) { final StringBuilder buf = new StringBuilder(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestHost.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestHost.java index 48ba454c930b..0aecbd0d7206 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestHost.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestHost.java @@ -41,11 +41,11 @@ public final class NestHost extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ NestHost(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, 0, constantPool); @@ -53,13 +53,15 @@ public final class NestHost extends Attribute { } /** - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param hostClassIndex Host class index - * @param constantPool Array of constants + * Constructs a new NestHost. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param hostClassIndex Host class index. + * @param constantPool Array of constants. */ public NestHost(final int nameIndex, final int length, final int hostClassIndex, final ConstantPool constantPool) { - super(Const.ATTR_NEST_MEMBERS, nameIndex, length, constantPool); + super(Const.ATTR_NEST_HOST, nameIndex, length, constantPool); this.hostClassIndex = Args.requireU2(hostClassIndex, "hostClassIndex"); } @@ -77,7 +79,7 @@ public NestHost(final NestHost c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -85,7 +87,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -97,8 +99,8 @@ public Attribute copy(final ConstantPool constantPool) { /** * Dumps NestHost attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -107,6 +109,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the host class index. + * * @return index into constant pool of host class name. */ public int getHostClassIndex() { @@ -114,14 +118,16 @@ public int getHostClassIndex() { } /** - * @param hostClassIndex the host class index + * Sets the host class index. + * + * @param hostClassIndex The host class index. */ public void setHostClassIndex(final int hostClassIndex) { this.hostClassIndex = hostClassIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestMembers.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestMembers.java index 261f57d98a8f..4a86c8190d1a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestMembers.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/NestMembers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -35,7 +35,7 @@ * ClassFile structure. * * @see Attribute - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class NestMembers extends Attribute { @@ -44,26 +44,24 @@ public final class NestMembers extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ - NestMembers(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { + NestMembers(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (int[]) null, constantPool); - final int classCount = input.readUnsignedShort(); - classes = new int[classCount]; - for (int i = 0; i < classCount; i++) { - classes[i] = input.readUnsignedShort(); - } + classes = ClassParser.readU2U2Table(dataInput); } /** - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param classes Table of indices in constant pool - * @param constantPool Array of constants + * Constructs a new NestMembers. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param classes Table of indices in constant pool. + * @param constantPool Array of constants. */ public NestMembers(final int nameIndex, final int length, final int[] classes, final ConstantPool constantPool) { super(Const.ATTR_NEST_MEMBERS, nameIndex, length, constantPool); @@ -85,7 +83,7 @@ public NestMembers(final NestMembers c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -93,7 +91,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -106,21 +104,23 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump NestMembers attribute to file stream in binary format. + * Dumps NestMembers attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(classes.length); + file.writeShort(Args.requireU2(classes.length, "classes.length")); for (final int index : classes) { file.writeShort(index); } } /** + * Gets the classes. + * * @return array of indices into constant pool of class names. */ public int[] getClasses() { @@ -128,7 +128,9 @@ public int[] getClasses() { } /** - * @return string array of class names + * Gets the class names. + * + * @return string array of class names. */ public String[] getClassNames() { final String[] names = new String[classes.length]; @@ -137,6 +139,8 @@ public String[] getClassNames() { } /** + * Gets the number of classes. + * * @return Length of classes table. */ public int getNumberClasses() { @@ -144,14 +148,16 @@ public int getNumberClasses() { } /** - * @param classes the list of class indexes Also redefines number_of_classes according to table length. + * Sets the classes. + * + * @param classes The list of class indexes Also redefines number_of_classes according to table length. */ public void setClasses(final int[] classes) { this.classes = Utils.createEmptyArrayIfNull(classes); } /** - * @return String representation, i.e., a list of classes. + * @return String representation, that is, a list of classes. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Node.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Node.java index 792ef31cb723..75dc73990588 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Node.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Node.java @@ -26,5 +26,10 @@ */ public interface Node { + /** + * Accepts a visitor. + * + * @param visitor The visitor. + */ void accept(Visitor visitor); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PMGClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PMGClass.java index b7b5e1f1d992..ae3c13d6f590 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PMGClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PMGClass.java @@ -26,6 +26,7 @@ import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * This class is derived from Attribute and represents a reference to a PMG attribute. @@ -40,25 +41,27 @@ public final class PMGClass extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ PMGClass(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, input.readUnsignedShort(), input.readUnsignedShort(), constantPool); } /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param pmgIndex index in constant pool for source file name - * @param pmgClassIndex Index in constant pool to CONSTANT_Utf8 - * @param constantPool Array of constants + * Constructs a PMGClass. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param pmgIndex index in constant pool for source file name. + * @param pmgClassIndex Index in constant pool to CONSTANT_Utf8. + * @param constantPool Array of constants. */ public PMGClass(final int nameIndex, final int length, final int pmgIndex, final int pmgClassIndex, final ConstantPool constantPool) { - super(Const.ATTR_PMG, nameIndex, length, constantPool); + super(Const.ATTR_PMG, nameIndex, Args.require(length, 4, "PMG attribute length"), constantPool); this.pmgIndex = pmgIndex; this.pmgClassIndex = pmgClassIndex; } @@ -77,7 +80,7 @@ public PMGClass(final PMGClass pgmClass) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -85,7 +88,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -93,10 +96,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump source file attribute to file stream in binary format. + * Dumps source file attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -106,6 +109,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the PMG class index. + * * @return Index in constant pool of source file name. */ public int getPMGClassIndex() { @@ -113,6 +118,8 @@ public int getPMGClassIndex() { } /** + * Gets the PMG class name. + * * @return PMG class name. */ public String getPMGClassName() { @@ -120,6 +127,8 @@ public String getPMGClassName() { } /** + * Gets the PMG index. + * * @return Index in constant pool of source file name. */ public int getPMGIndex() { @@ -127,6 +136,8 @@ public int getPMGIndex() { } /** + * Gets the PMG name. + * * @return PMG name. */ public String getPMGName() { @@ -134,21 +145,25 @@ public String getPMGName() { } /** - * @param pmgClassIndex + * Sets the PMG class index. + * + * @param pmgClassIndex The class index. */ public void setPMGClassIndex(final int pmgClassIndex) { this.pmgClassIndex = pmgClassIndex; } /** - * @param pmgIndex + * Sets the PMG index. + * + * @param pmgIndex The index. */ public void setPMGIndex(final int pmgIndex) { this.pmgIndex = pmgIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotationEntry.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotationEntry.java index 6ebe60c8049b..57b37a307d75 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotationEntry.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotationEntry.java @@ -28,6 +28,8 @@ import java.util.Collections; import java.util.List; +import com.sun.org.apache.bcel.internal.util.Args; + /** * represents one parameter annotation in the parameter annotation table * @@ -37,6 +39,12 @@ public class ParameterAnnotationEntry implements Node { static final ParameterAnnotationEntry[] EMPTY_ARRAY = {}; + /** + * Creates parameter annotation entries from attributes. + * + * @param attributes The attributes. + * @return The parameter annotation entries. + */ public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attributes) { if (attributes == null) { return EMPTY_ARRAY; @@ -60,15 +68,16 @@ public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final /** * Constructs object from input stream. * - * @param input Input stream - * @throws IOException if an I/O error occurs. + * @param input Input stream. + * @param constantPool The constant pool. + * @param isRuntimeVisible whether the contained annotations are runtime visible. + * @throws IOException Thrown if an I/O error occurs. */ - ParameterAnnotationEntry(final DataInput input, final ConstantPool constantPool) throws IOException { + ParameterAnnotationEntry(final DataInput input, final ConstantPool constantPool, final boolean isRuntimeVisible) throws IOException { final int annotationTableLength = input.readUnsignedShort(); annotationTable = new AnnotationEntry[annotationTableLength]; for (int i = 0; i < annotationTableLength; i++) { - // TODO isRuntimeVisible - annotationTable[i] = AnnotationEntry.read(input, constantPool, false); + annotationTable[i] = AnnotationEntry.read(input, constantPool, isRuntimeVisible); } } @@ -76,22 +85,30 @@ public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { v.visitParameterAnnotationEntry(this); } + /** + * Dumps parameter annotation entry to file stream. + * + * @param dos Output file stream. + * @throws IOException Thrown if an I/O error occurs. + */ public void dump(final DataOutputStream dos) throws IOException { - dos.writeShort(annotationTable.length); + dos.writeShort(Args.requireU2(annotationTable.length, "annotationTable.length")); for (final AnnotationEntry entry : annotationTable) { entry.dump(dos); } } /** - * returns the array of annotation entries in this annotation + * Gets the annotation entries. + * + * @return The array of annotation entries in this annotation. */ public AnnotationEntry[] getAnnotationEntries() { return annotationTable; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotations.java index 1e056b5d4f83..9300928d84de 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/ParameterAnnotations.java @@ -27,6 +27,8 @@ import java.util.Iterator; import java.util.stream.Stream; +import com.sun.org.apache.bcel.internal.util.Args; + /** * base class for parameter annotations * @@ -42,30 +44,31 @@ public abstract class ParameterAnnotations extends Attribute implements Iterable /** * Constructs a new instance. * - * @param parameterAnnotationType the subclass type of the parameter annotation - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param parameterAnnotationType The subclass type of the parameter annotation. + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @param isRuntimeVisible whether these parameter annotations are runtime visible. */ - ParameterAnnotations(final byte parameterAnnotationType, final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) - throws IOException { + ParameterAnnotations(final byte parameterAnnotationType, final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool, + final boolean isRuntimeVisible) throws IOException { this(parameterAnnotationType, nameIndex, length, (ParameterAnnotationEntry[]) null, constantPool); final int numParameters = input.readUnsignedByte(); parameterAnnotationTable = new ParameterAnnotationEntry[numParameters]; for (int i = 0; i < numParameters; i++) { - parameterAnnotationTable[i] = new ParameterAnnotationEntry(input, constantPool); + parameterAnnotationTable[i] = new ParameterAnnotationEntry(input, constantPool, isRuntimeVisible); } } /** * Constructs a new instance. * - * @param parameterAnnotationType the subclass type of the parameter annotation - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param parameterAnnotationTable the actual parameter annotations - * @param constantPool Array of constants + * @param parameterAnnotationType The subclass type of the parameter annotation. + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param parameterAnnotationTable The actual parameter annotations. + * @param constantPool Array of constants. */ public ParameterAnnotations(final byte parameterAnnotationType, final int nameIndex, final int length, final ParameterAnnotationEntry[] parameterAnnotationTable, final ConstantPool constantPool) { @@ -77,7 +80,7 @@ public ParameterAnnotations(final byte parameterAnnotationType, final int nameIn * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -85,7 +88,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -95,7 +98,7 @@ public Attribute copy(final ConstantPool constantPool) { @Override public void dump(final DataOutputStream dos) throws IOException { super.dump(dos); - dos.writeByte(parameterAnnotationTable.length); + dos.writeByte(Args.requireU1(parameterAnnotationTable.length, "parameterAnnotationTable.length")); for (final ParameterAnnotationEntry element : parameterAnnotationTable) { element.dump(dos); @@ -104,14 +107,18 @@ public void dump(final DataOutputStream dos) throws IOException { } /** - * returns the array of parameter annotation entries in this parameter annotation + * Gets the parameter annotation entries. + * + * @return The array of parameter annotation entries in this parameter annotation. */ public ParameterAnnotationEntry[] getParameterAnnotationEntries() { return parameterAnnotationTable; } /** - * @return the parameter annotation entry table + * Gets the parameter annotation table. + * + * @return The parameter annotation entry table. */ public final ParameterAnnotationEntry[] getParameterAnnotationTable() { return parameterAnnotationTable; @@ -123,7 +130,9 @@ public Iterator iterator() { } /** - * @param parameterAnnotationTable the entries to set in this parameter annotation + * Sets the parameter annotation table. + * + * @param parameterAnnotationTable The entries to set in this parameter annotation. */ public final void setParameterAnnotationTable(final ParameterAnnotationEntry[] parameterAnnotationTable) { this.parameterAnnotationTable = parameterAnnotationTable != null ? parameterAnnotationTable : EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PermittedSubclasses.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PermittedSubclasses.java new file mode 100644 index 000000000000..213e73ec3909 --- /dev/null +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/PermittedSubclasses.java @@ -0,0 +1,181 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.sun.org.apache.bcel.internal.classfile; + +import java.io.DataInput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; +import jdk.xml.internal.Utils; + +/** + * This class is derived from Attribute and records the classes and interfaces that are permitted to extend or + * implement the current class or interface. There may be at most one PermittedSubclasses attribute in a ClassFile + * structure. + * + * @see Attribute + * @since 6.13.0 + */ +public final class PermittedSubclasses extends Attribute { + + private int[] classes; + + /** + * Constructs object from input stream. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. + */ + PermittedSubclasses(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { + this(nameIndex, length, (int[]) null, constantPool); + classes = ClassParser.readU2U2Table(dataInput); + } + + /** + * Constructs object from table of class indices in constant pool. + * + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param classes Table of indices in constant pool. + * @param constantPool Array of constants. + */ + public PermittedSubclasses(final int nameIndex, final int length, final int[] classes, final ConstantPool constantPool) { + super(Const.ATTR_PERMITTED_SUBCLASSES, nameIndex, length, constantPool); + this.classes = Utils.createEmptyArrayIfNull(classes); + Args.requireU2(this.classes.length, "classes.length"); + } + + /** + * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a + * physical copy. + * + * @param c Source to copy. + */ + public PermittedSubclasses(final PermittedSubclasses c) { + this(c.getNameIndex(), c.getLength(), c.getClasses(), c.getConstantPool()); + } + + /** + * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. + * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. + * + * @param v Visitor object. + */ + @Override + public void accept(final Visitor v) { + v.visitPermittedSubclasses(this); + } + + /** + * Creates a deep clone of this object given constant pool. + * + * @return deep copy of this attribute. + */ + @Override + public Attribute copy(final ConstantPool constantPool) { + final PermittedSubclasses c = (PermittedSubclasses) clone(); + if (classes.length > 0) { + c.classes = classes.clone(); + } + c.setConstantPool(constantPool); + return c; + } + + /** + * Dumps PermittedSubclasses attribute to file stream in binary format. + * + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. + */ + @Override + public void dump(final DataOutputStream file) throws IOException { + super.dump(file); + file.writeShort(Args.requireU2(classes.length, "classes.length")); + for (final int index : classes) { + file.writeShort(index); + } + } + + /** + * Gets the class indices in constant pool. + * + * @return array of indices into constant pool of class names. + */ + public int[] getClasses() { + return classes; + } + + /** + * Gets permitted class names. + * + * @return string array of class names. + */ + public String[] getClassNames() { + final String[] names = new String[classes.length]; + Arrays.setAll(names, i -> Utility.pathToPackage(super.getConstantPool().getConstantString(classes[i], Const.CONSTANT_Class))); + return names; + } + + /** + * Gets the number of classes. + * + * @return Length of classes table. + */ + public int getNumberClasses() { + return classes.length; + } + + /** + * Sets class indices. + * + * @param classes The list of class indexes Also redefines number_of_classes according to table length. + */ + public void setClasses(final int[] classes) { + this.classes = Utils.createEmptyArrayIfNull(classes); + } + + /** + * String representation of PermittedSubclasses (for debugging purposes). + * + * @return String representation, that is, a list of permitted subclasses. + */ + @Override + public String toString() { + final StringBuilder buf = new StringBuilder(); + buf.append("PermittedSubclasses("); + buf.append(classes.length); + buf.append("):\n"); + for (final int index : classes) { + final String className = super.getConstantPool().getConstantString(index, Const.CONSTANT_Class); + buf.append(" ").append(Utility.compactClassName(className, false)).append("\n"); + } + return buf.substring(0, buf.length() - 1); // remove the last newline + } +} diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Record.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Record.java index f59cfa37ca4f..4448135cc6b5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Record.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Record.java @@ -56,11 +56,11 @@ private static RecordComponentInfo[] readComponents(final DataInput input, final /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ Record(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { @@ -70,10 +70,10 @@ private static RecordComponentInfo[] readComponents(final DataInput input, final /** * Constructs a new instance using components. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param classes Array of Record Component Info elements - * @param constantPool Array of constants + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param classes Array of Record Component Info elements. + * @param constantPool Array of constants. */ public Record(final int nameIndex, final int length, final RecordComponentInfo[] classes, final ConstantPool constantPool) { @@ -87,7 +87,7 @@ public Record(final int nameIndex, final int length, final RecordComponentInfo[] * defined by the contents of a Java class. For example, the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -97,7 +97,7 @@ public void accept(final Visitor v) { /** * Copies this instance and its components. * - * @return a deep copy of this instance and its components. + * @return A deep copy of this instance and its components. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -113,12 +113,12 @@ public Attribute copy(final ConstantPool constantPool) { * Dumps this instance into a file stream in binary format. * * @param file output stream. - * @throws IOException if an I/O error occurs. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(components.length); + file.writeShort(Args.requireU2(components.length, "components.length")); for (final RecordComponentInfo component : components) { component.dump(file); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RecordComponentInfo.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RecordComponentInfo.java index 3679647d4097..f22b461840f1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RecordComponentInfo.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RecordComponentInfo.java @@ -25,6 +25,7 @@ import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * Record component info from a record. Instances from this class maps @@ -44,9 +45,9 @@ public class RecordComponentInfo implements Node { /** * Constructs a new instance from an input stream. * - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ public RecordComponentInfo(final DataInput input, final ConstantPool constantPool) throws IOException { this.index = input.readUnsignedShort(); @@ -67,18 +68,37 @@ public void accept(final Visitor v) { /** * Dumps contents into a file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeShort(index); file.writeShort(descriptorIndex); - file.writeShort(attributes.length); + file.writeShort(Args.requireU2(attributes.length, "attributes.length")); for (final Attribute attribute : attributes) { attribute.dump(file); } } + /** + * Gets the attribute for the given tag if present, or null if absent. + * + * @param The attribute type. + * @param tag The attribute tag. + * @return Attribute for given tag, null if not found. + * Refer to {@link com.sun.org.apache.bcel.internal.Const#ATTR_UNKNOWN} constants named ATTR_* for possible values. + * @since 6.13.0 + */ + @SuppressWarnings("unchecked") + public final T getAttribute(final byte tag) { + for (final Attribute attribute : getAttributes()) { + if (attribute.getTag() == tag) { + return (T) attribute; + } + } + return null; + } + /** * Gets all attributes. * @@ -118,7 +138,7 @@ public int getIndex() { /** * Converts this instance to a String suitable for debugging. * - * @return a String suitable for debugging. + * @return A String suitable for debugging. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleAnnotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleAnnotations.java index 7a7c539f15ad..896eff6357cd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleAnnotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleAnnotations.java @@ -37,10 +37,10 @@ public class RuntimeInvisibleAnnotations extends Annotations { /** * Constructs a new instance. * - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public RuntimeInvisibleAnnotations(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleParameterAnnotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleParameterAnnotations.java index 3d50ce16d408..ff749043d2e3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleParameterAnnotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeInvisibleParameterAnnotations.java @@ -36,14 +36,14 @@ public class RuntimeInvisibleParameterAnnotations extends ParameterAnnotations { /** * Constructs a new instance. * - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public RuntimeInvisibleParameterAnnotations(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { - super(Const.ATTR_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS, nameIndex, length, input, constantPool); + super(Const.ATTR_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS, nameIndex, length, input, constantPool, false); } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleAnnotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleAnnotations.java index 4bf8e6f71976..52bbf4c05133 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleAnnotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleAnnotations.java @@ -37,10 +37,10 @@ public class RuntimeVisibleAnnotations extends Annotations { /** * Constructs a new instance. * - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public RuntimeVisibleAnnotations(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleParameterAnnotations.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleParameterAnnotations.java index ab5355235f66..43ce0860a411 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleParameterAnnotations.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/RuntimeVisibleParameterAnnotations.java @@ -36,14 +36,14 @@ public class RuntimeVisibleParameterAnnotations extends ParameterAnnotations { /** * Constructs a new instance. * - * @param nameIndex Index pointing to the name Code - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants + * @param nameIndex Index pointing to the name Code. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public RuntimeVisibleParameterAnnotations(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { - super(Const.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS, nameIndex, length, input, constantPool); + super(Const.ATTR_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS, nameIndex, length, input, constantPool, true); } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Signature.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Signature.java index 2161bbcb6ecf..dd04d7c61870 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Signature.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Signature.java @@ -58,28 +58,53 @@ void unread() { } } + /** + * The maximum nesting depth of a signature accepted by {@link #translate(String)}. Guards against a + * {@link StackOverflowError} from deeply nested, attacker-supplied generic signatures. + */ + private static final int MAX_NESTING_DEPTH = 512; + private static boolean identStart(final int ch) { return ch == 'T' || ch == 'L'; } - // @since 6.0 is no longer final + /** + * Tests if a string is an actual parameter list. + * + * @param s The string to test. + * @return true if the string is an actual parameter list. + * @since 6.0 is no longer final + */ public static boolean isActualParameterList(final String s) { return s.startsWith("L") && s.endsWith(">;"); } - // @since 6.0 is no longer final + /** + * Tests if a string is a formal parameter list. + * + * @param s The string to test. + * @return true if the string is a formal parameter list. + * @since 6.0 is no longer final + */ public static boolean isFormalParameterList(final String s) { return s.startsWith("<") && s.indexOf(':') > 0; } private static void matchGJIdent(final MyByteArrayInputStream in, final StringBuilder buf) { + matchGJIdent(in, buf, 0); + } + + private static void matchGJIdent(final MyByteArrayInputStream in, final StringBuilder buf, final int depth) { + if (depth > MAX_NESTING_DEPTH) { + throw new IllegalArgumentException("Illegal signature: " + in.getData() + " exceeds maximum nesting depth " + MAX_NESTING_DEPTH); + } int ch; matchIdent(in, buf); ch = in.read(); if (ch == '<' || ch == '(') { // Parameterized or method // System.out.println("Enter <"); buf.append((char) ch); - matchGJIdent(in, buf); + matchGJIdent(in, buf, depth + 1); while ((ch = in.read()) != '>' && ch != ')') { // List of parameters if (ch == -1) { throw new IllegalArgumentException("Illegal signature: " + in.getData() + " reaching EOF"); @@ -87,7 +112,7 @@ private static void matchGJIdent(final MyByteArrayInputStream in, final StringBu // System.out.println("Still no >"); buf.append(", "); in.unread(); - matchGJIdent(in, buf); // Recursive call + matchGJIdent(in, buf, depth + 1); // Recursive call } // System.out.println("Exit >"); buf.append((char) ch); @@ -97,7 +122,7 @@ private static void matchGJIdent(final MyByteArrayInputStream in, final StringBu ch = in.read(); if (identStart(ch)) { in.unread(); - matchGJIdent(in, buf); + matchGJIdent(in, buf, depth + 1); } else if (ch == ')') { in.unread(); } else if (ch != ';') { @@ -150,6 +175,12 @@ private static void matchIdent(final MyByteArrayInputStream in, final StringBuil } } + /** + * Translates a signature string. + * + * @param s The signature string. + * @return The translated signature. + */ public static String translate(final String s) { // System.out.println("Sig:" + s); final StringBuilder buf = new StringBuilder(); @@ -162,21 +193,23 @@ public static String translate(final String s) { /** * Constructs object from file stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ Signature(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, input.readUnsignedShort(), constantPool); } /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param signatureIndex Index in constant pool to CONSTANT_Utf8 - * @param constantPool Array of constants + * Constructs a Signature. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param signatureIndex Index in constant pool to CONSTANT_Utf8. + * @param constantPool Array of constants. */ public Signature(final int nameIndex, final int length, final int signatureIndex, final ConstantPool constantPool) { super(Const.ATTR_SIGNATURE, nameIndex, Args.require(length, 2, "Signature length attribute"), constantPool); @@ -199,7 +232,7 @@ public Signature(final Signature c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -208,7 +241,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -216,10 +249,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump source file attribute to file stream in binary format. + * Dumps source file attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -228,6 +261,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the GJ signature. + * * @return GJ signature. */ public String getSignature() { @@ -235,6 +270,8 @@ public String getSignature() { } /** + * Gets the signature index. + * * @return Index in constant pool of source file name. */ public int getSignatureIndex() { @@ -242,14 +279,16 @@ public int getSignatureIndex() { } /** - * @param signatureIndex the index info the constant pool of this signature + * Sets the signature index. + * + * @param signatureIndex The index info the constant pool of this signature. */ public void setSignatureIndex(final int signatureIndex) { this.signatureIndex = signatureIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SimpleElementValue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SimpleElementValue.java index e3e1cf400315..bdeb7a8b57e9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SimpleElementValue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SimpleElementValue.java @@ -27,11 +27,20 @@ import com.sun.org.apache.bcel.internal.Const; /** + * Represents a simple element value in an annotation. + * * @since 6.0 */ public class SimpleElementValue extends ElementValue { private int index; + /** + * Constructs a SimpleElementValue. + * + * @param type The element value type. + * @param index The index into the constant pool. + * @param cpool The constant pool. + */ public SimpleElementValue(final int type, final int index, final ConstantPool cpool) { super(type, cpool); this.index = index; @@ -59,12 +68,19 @@ public void dump(final DataOutputStream dos) throws IOException { } /** - * @return Value entry index in the cpool + * Gets the value entry index in the constant pool. + * + * @return Value entry index in the constant pool. */ public int getIndex() { return index; } + /** + * Gets the boolean value. + * + * @return The boolean value. + */ public boolean getValueBoolean() { if (super.getType() != PRIMITIVE_BOOLEAN) { throw new IllegalStateException("Don't call getValueBoolean() on a non BOOLEAN ElementValue"); @@ -73,6 +89,11 @@ public boolean getValueBoolean() { return bo.getBytes() != 0; } + /** + * Gets the byte value. + * + * @return The byte value. + */ public byte getValueByte() { if (super.getType() != PRIMITIVE_BYTE) { throw new IllegalStateException("Don't call getValueByte() on a non BYTE ElementValue"); @@ -80,6 +101,11 @@ public byte getValueByte() { return (byte) super.getConstantPool().getConstantInteger(getIndex()).getBytes(); } + /** + * Gets the char value. + * + * @return The char value. + */ public char getValueChar() { if (super.getType() != PRIMITIVE_CHAR) { throw new IllegalStateException("Don't call getValueChar() on a non CHAR ElementValue"); @@ -87,6 +113,11 @@ public char getValueChar() { return (char) super.getConstantPool().getConstantInteger(getIndex()).getBytes(); } + /** + * Gets the double value. + * + * @return The double value. + */ public double getValueDouble() { if (super.getType() != PRIMITIVE_DOUBLE) { throw new IllegalStateException("Don't call getValueDouble() on a non DOUBLE ElementValue"); @@ -95,6 +126,11 @@ public double getValueDouble() { return d.getBytes(); } + /** + * Gets the float value. + * + * @return The float value. + */ public float getValueFloat() { if (super.getType() != PRIMITIVE_FLOAT) { throw new IllegalStateException("Don't call getValueFloat() on a non FLOAT ElementValue"); @@ -103,6 +139,11 @@ public float getValueFloat() { return f.getBytes(); } + /** + * Gets the int value. + * + * @return The int value. + */ public int getValueInt() { if (super.getType() != PRIMITIVE_INT) { throw new IllegalStateException("Don't call getValueInt() on a non INT ElementValue"); @@ -110,6 +151,11 @@ public int getValueInt() { return super.getConstantPool().getConstantInteger(getIndex()).getBytes(); } + /** + * Gets the long value. + * + * @return The long value. + */ public long getValueLong() { if (super.getType() != PRIMITIVE_LONG) { throw new IllegalStateException("Don't call getValueLong() on a non LONG ElementValue"); @@ -118,6 +164,11 @@ public long getValueLong() { return j.getBytes(); } + /** + * Gets the short value. + * + * @return The short value. + */ public short getValueShort() { if (super.getType() != PRIMITIVE_SHORT) { throw new IllegalStateException("Don't call getValueShort() on a non SHORT ElementValue"); @@ -126,6 +177,11 @@ public short getValueShort() { return (short) s.getBytes(); } + /** + * Gets the string value. + * + * @return The string value. + */ public String getValueString() { if (super.getType() != STRING) { throw new IllegalStateException("Don't call getValueString() on a non STRING ElementValue"); @@ -133,6 +189,11 @@ public String getValueString() { return super.getConstantPool().getConstantUtf8(getIndex()).getBytes(); } + /** + * Sets the index into the constant pool. + * + * @param index The index. + */ public void setIndex(final int index) { this.index = index; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SourceFile.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SourceFile.java index bfa9cbf8fcb2..f9f8aba37399 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SourceFile.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/SourceFile.java @@ -42,17 +42,19 @@ public final class SourceFile extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ SourceFile(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, input.readUnsignedShort(), constantPool); } /** + * Constructs a SourceFile. + * * @param nameIndex Index in constant pool to CONSTANT_Utf8, which should represent the string "SourceFile". * @param length Content length in bytes, the value should be 2. * @param constantPool The constant pool that this attribute is associated with. @@ -80,7 +82,7 @@ public SourceFile(final SourceFile c) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -88,7 +90,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -96,10 +98,10 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump source file attribute to file stream in binary format. + * Dumps source file attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -108,6 +110,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the source file index. + * * @return Index in constant pool of source file name. */ public int getSourceFileIndex() { @@ -115,6 +119,8 @@ public int getSourceFileIndex() { } /** + * Gets the source file name. + * * @return Source file name. */ public String getSourceFileName() { @@ -122,14 +128,16 @@ public String getSourceFileName() { } /** - * @param sourceFileIndex + * Sets the source file index. + * + * @param sourceFileIndex The source file index to set. */ public void setSourceFileIndex(final int sourceFileIndex) { this.sourceFileIndex = sourceFileIndex; } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMap.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMap.java index 317638e6b2d0..5696916abe48 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMap.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMap.java @@ -46,7 +46,6 @@ * @see Code * @see StackMapEntry * @see StackMapType - * @LastModified: Sept 2025 */ public final class StackMap extends Attribute { @@ -55,11 +54,11 @@ public final class StackMap extends Attribute { /** * Constructs object from input stream. * - * @param nameIndex Index of name - * @param length Content length in bytes - * @param dataInput Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index of name. + * @param length Content length in bytes. + * @param dataInput Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. */ StackMap(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (StackMapEntry[]) null, constantPool); @@ -70,14 +69,13 @@ public final class StackMap extends Attribute { } } - /* - * @param nameIndex Index of name - * - * @param length Content length in bytes - * - * @param map Table of stack map entries + /** + * Constructs a StackMap. * - * @param constantPool Array of constants + * @param nameIndex Index of name. + * @param length Content length in bytes. + * @param table Table of stack map entries. + * @param constantPool Array of constants. */ public StackMap(final int nameIndex, final int length, final StackMapEntry[] table, final ConstantPool constantPool) { super(Const.ATTR_STACK_MAP, nameIndex, length, constantPool); @@ -89,7 +87,7 @@ public StackMap(final int nameIndex, final int length, final StackMapEntry[] tab * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -97,7 +95,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -109,33 +107,42 @@ public Attribute copy(final ConstantPool constantPool) { } /** - * Dump stack map table attribute to file stream in binary format. + * Dumps stack map table attribute to file stream in binary format. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { super.dump(file); - file.writeShort(table.length); + file.writeShort(Args.requireU2(table.length, "table.length")); for (final StackMapEntry entry : table) { entry.dump(file); } } + /** + * Gets the map length. + * + * @return The map length. + */ public int getMapLength() { return table.length; } /** - * @return Array of stack map entries + * Gets the stack map. + * + * @return Array of stack map entries. */ public StackMapEntry[] getStackMap() { return table; } /** - * @param table Array of stack map entries + * Sets the stack map. + * + * @param table Array of stack map entries. */ public void setStackMap(final StackMapEntry[] table) { this.table = table != null ? table : StackMapEntry.EMPTY_ARRAY; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapEntry.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapEntry.java index 015083dd066f..5249d1b4b394 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapEntry.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapEntry.java @@ -27,6 +27,7 @@ import java.util.Arrays; import com.sun.org.apache.bcel.internal.Const; +import com.sun.org.apache.bcel.internal.util.Args; /** * This class represents a stack map entry recording the types of local variables and the of stack items at a given @@ -45,6 +46,7 @@ * full_frame; * } * + * * @see StackMap * @see StackMapType */ @@ -61,8 +63,8 @@ public final class StackMapEntry implements Node, Cloneable { /** * Constructs object from input stream. * - * @param dataInput Input stream - * @throws IOException if an I/O error occurs. + * @param dataInput Input stream. + * @throws IOException Thrown if an I/O error occurs. */ StackMapEntry(final DataInput dataInput, final ConstantPool constantPool) throws IOException { this(dataInput.readByte() & 0xFF, -1, null, null, constantPool); @@ -105,13 +107,13 @@ public final class StackMapEntry implements Node, Cloneable { /** * DO NOT USE * - * @param byteCodeOffset - * @param numberOfLocals NOT USED - * @param typesOfLocals array of {@link StackMapType}s of locals - * @param numberOfStackItems NOT USED - * @param typesOfStackItems array ot {@link StackMapType}s of stack items - * @param constantPool the constant pool - * @deprecated Since 6.0, use {@link #StackMapEntry(int, int, StackMapType[], StackMapType[], ConstantPool)} instead + * @param byteCodeOffset byte code offset. + * @param numberOfLocals NOT USED. + * @param typesOfLocals array of {@link StackMapType}s of locals. + * @param numberOfStackItems NOT USED. + * @param typesOfStackItems array ot {@link StackMapType}s of stack items. + * @param constantPool The constant pool. + * @deprecated Since 6.0, use {@link #StackMapEntry(int, int, StackMapType[], StackMapType[], ConstantPool)} instead. */ @java.lang.Deprecated public StackMapEntry(final int byteCodeOffset, final int numberOfLocals, final StackMapType[] typesOfLocals, final int numberOfStackItems, @@ -131,11 +133,11 @@ public StackMapEntry(final int byteCodeOffset, final int numberOfLocals, final S /** * Create an instance * - * @param tag the frameType to use - * @param byteCodeOffset - * @param typesOfLocals array of {@link StackMapType}s of locals - * @param typesOfStackItems array ot {@link StackMapType}s of stack items - * @param constantPool the constant pool + * @param tag The frameType to use. + * @param byteCodeOffset byte code offset. + * @param typesOfLocals array of {@link StackMapType}s of locals. + * @param typesOfStackItems array ot {@link StackMapType}s of stack items. + * @param constantPool The constant pool. */ public StackMapEntry(final int tag, final int byteCodeOffset, final StackMapType[] typesOfLocals, final StackMapType[] typesOfStackItems, final ConstantPool constantPool) { @@ -150,7 +152,7 @@ public StackMapEntry(final int tag, final int byteCodeOffset, final StackMapType * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -158,10 +160,12 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public StackMapEntry copy() { - StackMapEntry e; + final StackMapEntry e; try { e = (StackMapEntry) clone(); } catch (final CloneNotSupportedException ex) { @@ -176,10 +180,10 @@ public StackMapEntry copy() { } /** - * Dump stack map entry + * Dumps stack map entry * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.write(frameType); @@ -197,11 +201,11 @@ public void dump(final DataOutputStream file) throws IOException { } } else if (frameType == Const.FULL_FRAME) { file.writeShort(byteCodeOffset); - file.writeShort(typesOfLocals.length); + file.writeShort(Args.requireU2(typesOfLocals.length, "typesOfLocals.length")); for (final StackMapType type : typesOfLocals) { type.dump(file); } - file.writeShort(typesOfStackItems.length); + file.writeShort(Args.requireU2(typesOfStackItems.length, "typesOfStackItems.length")); for (final StackMapType type : typesOfStackItems) { type.dump(file); } @@ -211,23 +215,35 @@ public void dump(final DataOutputStream file) throws IOException { } } + /** + * Gets the byte code offset. + * + * @return The byte code offset. + */ public int getByteCodeOffset() { return byteCodeOffset; } /** + * Gets the constant pool. + * * @return Constant pool used by this object. */ public ConstantPool getConstantPool() { return constantPool; } + /** + * Gets the frame type. + * + * @return The frame type. + */ public int getFrameType() { return frameType; } /** - * Calculate stack map entry size + * Calculate stack map entry size. */ int getMapEntrySize() { if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) { @@ -262,18 +278,38 @@ int getMapEntrySize() { return len; } + /** + * Gets the number of locals. + * + * @return The number of locals. + */ public int getNumberOfLocals() { return typesOfLocals.length; } + /** + * Gets the number of stack items. + * + * @return The number of stack items. + */ public int getNumberOfStackItems() { return typesOfStackItems.length; } + /** + * Gets the types of locals. + * + * @return The types of locals. + */ public StackMapType[] getTypesOfLocals() { return typesOfLocals; } + /** + * Gets the types of stack items. + * + * @return The types of stack items. + */ public StackMapType[] getTypesOfStackItems() { return typesOfStackItems; } @@ -288,6 +324,11 @@ private boolean invalidFrameType(final int f) { // @formatter:on } + /** + * Sets the byte code offset. + * + * @param newOffset The new offset. + */ public void setByteCodeOffset(final int newOffset) { if (newOffset < 0 || newOffset > 32767) { throw new IllegalArgumentException("Invalid StackMap offset: " + newOffset); @@ -312,12 +353,19 @@ public void setByteCodeOffset(final int newOffset) { } /** + * Sets the constant pool. + * * @param constantPool Constant pool to be used for this object. */ public void setConstantPool(final ConstantPool constantPool) { this.constantPool = constantPool; } + /** + * Sets the frame type. + * + * @param ft The frame type. + */ public void setFrameType(final int ft) { if (ft >= Const.SAME_FRAME && ft <= Const.SAME_FRAME_MAX) { byteCodeOffset = ft - Const.SAME_FRAME; @@ -330,25 +378,39 @@ public void setFrameType(final int ft) { } /** + * Sets the number of locals (deprecated). * - * @deprecated since 6.0 + * @param n The number of locals. + * @deprecated Since 6.0 */ @java.lang.Deprecated public void setNumberOfLocals(final int n) { // TODO unused } /** + * Sets the number of stack items (deprecated). * - * @deprecated since 6.0 + * @param n The number of stack items. + * @deprecated Since 6.0 */ @java.lang.Deprecated public void setNumberOfStackItems(final int n) { // TODO unused } + /** + * Sets the types of locals. + * + * @param types The types of locals. + */ public void setTypesOfLocals(final StackMapType[] types) { typesOfLocals = types != null ? types : StackMapType.EMPTY_ARRAY; } + /** + * Sets the types of stack items. + * + * @param types The types of stack items. + */ public void setTypesOfStackItems(final StackMapType[] types) { typesOfStackItems = types != null ? types : StackMapType.EMPTY_ARRAY; } @@ -403,10 +465,10 @@ public String toString() { } /** - * Update the distance (as an offset delta) from this StackMap entry to the next. Note that this might cause the + * Updates the distance (as an offset delta) from this StackMap entry to the next. Note that this might cause the * frame type to change. Note also that delta may be negative. * - * @param delta offset delta + * @param delta offset delta. */ public void updateByteCodeOffset(final int delta) { setByteCodeOffset(byteCodeOffset + delta); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapType.java index b93066d53b71..23177ad3c4a6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/StackMapType.java @@ -36,6 +36,9 @@ */ public final class StackMapType implements Node, Cloneable { + /** + * Empty array constant. + */ public static final StackMapType[] EMPTY_ARRAY = {}; // BCELifier code generator writes calls to constructor translating null to EMPTY_ARRAY private byte type; @@ -43,8 +46,11 @@ public final class StackMapType implements Node, Cloneable { private ConstantPool constantPool; /** - * @param type type tag as defined in the Constants interface - * @param index index to constant pool, or byte code offset + * Constructs a StackMapType. + * + * @param type type tag as defined in the Constants interface. + * @param index index to constant pool, or byte code offset. + * @param constantPool The constant pool. */ public StackMapType(final byte type, final int index, final ConstantPool constantPool) { this.type = checkType(type); @@ -55,8 +61,9 @@ public StackMapType(final byte type, final int index, final ConstantPool constan /** * Constructs object from file stream. * - * @param file Input stream - * @throws IOException if an I/O error occurs. + * @param file Input stream. + * @param constantPool The constant pool. + * @throws IOException Thrown if an I/O error occurs. */ StackMapType(final DataInput file, final ConstantPool constantPool) throws IOException { this(file.readByte(), -1, constantPool); @@ -70,7 +77,7 @@ public StackMapType(final byte type, final int index, final ConstantPool constan * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. * @since 6.8.0 */ @Override @@ -86,7 +93,9 @@ private byte checkType(final byte type) { } /** - * @return deep copy of this object + * Creates a deep copy of this object. + * + * @return deep copy of this object. */ public StackMapType copy() { try { @@ -98,10 +107,10 @@ public StackMapType copy() { } /** - * Dump type entries to file. + * Dumps type entries to file. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ public void dump(final DataOutputStream file) throws IOException { file.writeByte(type); @@ -112,7 +121,8 @@ public void dump(final DataOutputStream file) throws IOException { /** * Gets the class name of this StackMapType from the constant pool at index position. - * @return the fully qualified name of the class for this StackMapType. + * + * @return The fully qualified name of the class for this StackMapType. * @since 6.8.0 */ public String getClassName() { @@ -120,6 +130,8 @@ public String getClassName() { } /** + * Gets the constant pool. + * * @return Constant pool used by this object. */ public ConstantPool getConstantPool() { @@ -127,19 +139,28 @@ public ConstantPool getConstantPool() { } /** + * Gets the index. + * * @return index to constant pool if type == ITEM_Object, or offset in byte code, if type == ITEM_NewObject, and -1 - * otherwise + * otherwise. */ public int getIndex() { return index; } + /** + * Gets the type. + * + * @return The type. + */ public byte getType() { return type; } /** - * @return true, if type is either ITEM_Object or ITEM_NewObject + * Checks if this type has an index. + * + * @return true, if type is either ITEM_Object or ITEM_NewObject. */ public boolean hasIndex() { return type == Const.ITEM_Object || type == Const.ITEM_NewObject; @@ -159,22 +180,34 @@ private String printIndex() { } /** + * Sets the constant pool. + * * @param constantPool Constant pool to be used for this object. */ public void setConstantPool(final ConstantPool constantPool) { this.constantPool = constantPool; } + /** + * Sets the index. + * + * @param index The index. + */ public void setIndex(final int index) { this.index = index; } + /** + * Sets the type. + * + * @param type The type. + */ public void setType(final byte type) { this.type = checkType(type); } /** - * @return String representation + * @return String representation. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Synthetic.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Synthetic.java index c7fef8fcebc0..2daa48dae334 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Synthetic.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Synthetic.java @@ -1,6 +1,5 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -22,56 +21,59 @@ package com.sun.org.apache.bcel.internal.classfile; import java.io.DataInput; -import java.io.DataOutputStream; import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.util.Args; /** - * This class is derived from Attribute and declares this class as 'synthetic', i.e., it needs special - * handling. The JVM specification states "A class member that does not appear in the source code must be marked using a - * Synthetic attribute." It may appear in the ClassFile attribute table, a field_info table or a method_info table. This - * class is intended to be instantiated from the Attribute.readAttribute() method. + * This class is derived from Attribute and declares this class as 'synthetic', that is, it needs special handling. The JVM specification states "A + * class member that does not appear in the source code must be marked using a Synthetic attribute." It may appear in the ClassFile attribute table, a + * field_info table or a method_info table. This class is intended to be instantiated from the Attribute.readAttribute() method. + * + *
+ *
+ * Synthetic_attribute {
+ *     u2 attribute_name_index;
+ *     u4 attribute_length;
+ * }
+ * 
* * @see Attribute + * @see JVM Specification: The Synthetic Attribute + * @LastModified: Nov 2026 */ public final class Synthetic extends Attribute { - private byte[] bytes; - /** - * @param nameIndex Index in constant pool to CONSTANT_Utf8, which should represent the string "Synthetic". - * @param length Content length in bytes - should be zero. - * @param bytes Attribute contents + * Constructs a Synthetic attribute. + * + * @param nameIndex Index in constant pool to CONSTANT_Utf8, which should represent the string "Synthetic". + * @param length JVM Specification: "The value of the attribute_length item must be zero.". + * @param bytes Attribute contents. * @param constantPool The constant pool this attribute is associated with. + * @see JVM Specification: The Synthetic Attribute */ public Synthetic(final int nameIndex, final int length, final byte[] bytes, final ConstantPool constantPool) { super(Const.ATTR_SYNTHETIC, nameIndex, Args.require0(length, "Synthetic attribute length"), constantPool); - this.bytes = bytes; } /** * Constructs object from input stream. * - * @param nameIndex Index in constant pool to CONSTANT_Utf8 - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool to CONSTANT_Utf8. + * @param length JVM Specification: "The value of the attribute_length item must be zero.". + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. + * @see JVM Specification: The Synthetic Attribute */ Synthetic(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (byte[]) null, constantPool); - if (length > 0) { - bytes = new byte[length]; - input.readFully(bytes); - println("Synthetic attribute with length > 0"); - } } /** - * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a - * physical copy. + * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a physical copy. * * @param c Source to copy. */ @@ -80,10 +82,10 @@ public Synthetic(final Synthetic c) { } /** - * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. - * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. + * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., the hierarchy of methods, fields, + * attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -91,44 +93,33 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { final Synthetic c = (Synthetic) clone(); - if (bytes != null) { - c.bytes = bytes.clone(); - } c.setConstantPool(constantPool); return c; } /** - * Dump source file attribute to file stream in binary format. + * Gets data bytes. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. - */ - @Override - public void dump(final DataOutputStream file) throws IOException { - super.dump(file); - if (super.getLength() > 0) { - file.write(bytes, 0, super.getLength()); - } - } - - /** * @return data bytes. */ public byte[] getBytes() { - return bytes; + return Const.EMPTY_BYTE_ARRAY; } /** - * @param bytes + * Sets data bytes. + * + * @param bytes data bytes. */ public void setBytes(final byte[] bytes) { - this.bytes = bytes; + if (bytes != null) { + Args.require0(bytes.length, "Deprecated attribute length"); + } } /** @@ -136,10 +127,6 @@ public void setBytes(final byte[] bytes) { */ @Override public String toString() { - final StringBuilder buf = new StringBuilder("Synthetic"); - if (super.getLength() > 0) { - buf.append(" ").append(Utility.toHexString(bytes)); - } - return buf.toString(); + return "Synthetic"; } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Unknown.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Unknown.java index 3500e472c85c..8a137534d5f1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Unknown.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Unknown.java @@ -1,6 +1,5 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -29,16 +28,20 @@ import com.sun.org.apache.bcel.internal.Const; /** - * This class represents a reference to an unknown (i.e., application-specific) attribute of a class. It is instantiated + * This class represents a reference to an unknown (that is, application-specific) attribute of a class. It is instantiated * from the {@link Attribute#readAttribute(java.io.DataInput, ConstantPool)} method. Applications that need to read in * application-specific attributes should create an {@link UnknownAttributeReader} implementation and attach it via * {@link Attribute#addAttributeReader(String, UnknownAttributeReader)}. * * @see Attribute * @see UnknownAttributeReader + * @LastModified: Nov 2026 */ public final class Unknown extends Attribute { + //Unknown non-empty class-file attribute is not allowed + static final int MAX_LEN = 0; + private byte[] bytes; private final String name; @@ -46,10 +49,10 @@ public final class Unknown extends Attribute { /** * Constructs a new instance for a non-standard attribute. * - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param bytes Attribute contents - * @param constantPool Array of constants + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param bytes Attribute contents. + * @param constantPool Array of constants. */ public Unknown(final int nameIndex, final int length, final byte[] bytes, final ConstantPool constantPool) { super(Const.ATTR_UNKNOWN, nameIndex, length, constantPool); @@ -58,17 +61,25 @@ public Unknown(final int nameIndex, final int length, final byte[] bytes, final } /** - * Constructs a new instance from an input stream. + * Constructs a new instance from a DataInput. + *

+ * The size of an Attribute unknown to the JVM specification is + * limited to 1 MB and is overridden with the system property {@code BCEL.Attribute.Unknown.max_attribute_length}. + *

* - * @param nameIndex Index in constant pool - * @param length Content length in bytes - * @param input Input stream - * @param constantPool Array of constants - * @throws IOException if an I/O error occurs. + * @param nameIndex Index in constant pool. + * @param length Content length in bytes. + * @param input Input stream. + * @param constantPool Array of constants. + * @throws IOException Thrown if an I/O error occurs. + * @see Attribute */ Unknown(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException { this(nameIndex, length, (byte[]) null, constantPool); if (length > 0) { + if (length > MAX_LEN) { + throw new IOException("Unknown non-empty class-file attribute is not allowed"); + } bytes = new byte[length]; input.readFully(bytes); } @@ -87,7 +98,7 @@ public Unknown(final Unknown unknown) { * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -95,7 +106,7 @@ public void accept(final Visitor v) { } /** - * @return deep copy of this attribute + * @return deep copy of this attribute. */ @Override public Attribute copy(final ConstantPool constantPool) { @@ -110,8 +121,8 @@ public Attribute copy(final ConstantPool constantPool) { /** * Dumps unknown bytes to file stream. * - * @param file Output file stream - * @throws IOException if an I/O error occurs. + * @param file Output file stream. + * @throws IOException Thrown if an I/O error occurs. */ @Override public void dump(final DataOutputStream file) throws IOException { @@ -122,6 +133,8 @@ public void dump(final DataOutputStream file) throws IOException { } /** + * Gets the data bytes. + * * @return data bytes. */ public byte[] getBytes() { @@ -137,7 +150,9 @@ public String getName() { } /** - * @param bytes the bytes to set + * Sets the data bytes. + * + * @param bytes The bytes to set. */ public void setBytes(final byte[] bytes) { this.bytes = bytes; @@ -151,7 +166,7 @@ public String toString() { if (super.getLength() == 0 || bytes == null) { return "(Unknown attribute " + name + ")"; } - String hex; + final String hex; final int limit = 10; if (super.getLength() > limit) { final byte[] tmp = Arrays.copyOf(bytes, limit); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/UnknownAttributeReader.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/UnknownAttributeReader.java index 2c1cae9ee3d0..a85f8f64d7fc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/UnknownAttributeReader.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/UnknownAttributeReader.java @@ -40,7 +40,6 @@ public interface UnknownAttributeReader { * agree with what the factory expects the length to be. * @param file This is the data input that the factory needs to read its data from. * @param constantPool This is the constant pool associated with the Attribute that we are constructing. - * * @return The user-defined AttributeReader should take this data and use it to construct an attribute. In the case of * errors, a null can be returned which will cause the parsing of the class file to fail. * diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Utility.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Utility.java index 6967dcefd94b..2840fcd6e089 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Utility.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Utility.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -33,17 +33,17 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Locale; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.util.ByteSequence; +import jdk.xml.internal.Utils; /** * Utility functions that do not really belong to any class in particular. * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ // @since 6.0 methods are no longer final public abstract class Utility { @@ -53,7 +53,7 @@ public abstract class Utility { */ private static final class JavaReader extends FilterReader { - public JavaReader(final Reader in) { + JavaReader(final Reader in) { super(in); } @@ -67,21 +67,35 @@ public int read() throws IOException { if (i < 0) { return -1; } - if (i >= '0' && i <= '9' || i >= 'a' && i <= 'f') { // Normal escape + if (isHex(i)) { // Normal escape final int j = in.read(); if (j < 0) { return -1; } - final char[] tmp = {(char) i, (char) j}; + if (!isHex(j)) { + // Would otherwise reach Integer.parseInt and throw an undeclared NumberFormatException. + throw new IOException("Invalid escape sequence: expected a second hexadecimal digit after '" + ESCAPE_CHAR + (char) i + "'"); + } + final char[] tmp = { (char) i, (char) j }; return Integer.parseInt(new String(tmp), 16); } + if (i >= MAP_CHAR.length || MAP_CHAR[i] == UNMAPPED) { + // Reject instead of throwing an undeclared ArrayIndexOutOfBoundsException (i >= 256) or silently + // aliasing every unmapped character to MAP_CHAR's default slot value (the '$A' encoding). + throw new IOException("Invalid escape character after '" + ESCAPE_CHAR + "': 0x" + Integer.toHexString(i)); + } return MAP_CHAR[i]; } @Override public int read(final char[] cbuf, final int off, final int len) throws IOException { for (int i = 0; i < len; i++) { - cbuf[off + i] = (char) read(); + final int ch = read(); + if (ch < 0) { + // Propagate end-of-stream instead of writing (char) -1 and over-reporting the read length. + return i > 0 ? i : -1; + } + cbuf[off + i] = (char) ch; } return len; } @@ -93,7 +107,7 @@ public int read(final char[] cbuf, final int off, final int len) throws IOExcept */ private static final class JavaWriter extends FilterWriter { - public JavaWriter(final Writer out) { + JavaWriter(final Writer out) { super(out); } @@ -132,6 +146,21 @@ public void write(final String str, final int off, final int len) throws IOExcep } } + /* + * Maximum nesting depth accepted by typeSignatureToString(). Signatures are attacker-controlled bytes from untrusted class files; without a limit, a deeply + * nested generic signature such as "LA;>;>;" drives one stack frame per nesting level and kills the calling thread with a StackOverflowError. + */ + private static final int MAX_SIGNATURE_NESTING = 512; + + /** + * The maximum number of bytes that {@link #decode(String, boolean)} will decompress. Guards against decompression bombs: the compressed input is + * attacker-controlled and a small input can decompress to an enormous size. + */ + private static final int MAX_DECODED_LENGTH = 64 * 1024 * 1024; + + /** Marker for {@link #MAP_CHAR} slots that do not correspond to a valid special escape character. */ + private static final int UNMAPPED = -1; + /* * How many chars have been consumed during parsing in typeSignatureToString(). Read by methodSignatureToString(). Set * by side effect, but only internally. @@ -140,10 +169,10 @@ public void write(final String str, final int off, final int len) throws IOExcep /* * The 'WIDE' instruction is used in the byte code to allow 16-bit wide indices for local variables. This opcode - * precedes an 'ILOAD', e.g.. The opcode immediately following takes an extra byte which is combined with the following - * byte to form a 16-bit value. + * precedes an 'ILOAD', for example. The opcode immediately following takes an extra byte which is combined with the following + * byte to form a 16-bit value. Read across consecutive codeToString() calls, so kept per-thread like CONSUMER_CHARS. */ - private static boolean wide; + private static final ThreadLocal WIDE = ThreadLocal.withInitial(() -> Boolean.FALSE); // A-Z, g-z, _, $ private static final int FREE_CHARS = 48; @@ -155,6 +184,7 @@ public void write(final String str, final int off, final int len) throws IOExcep private static final char ESCAPE_CHAR = '$'; static { + Arrays.fill(MAP_CHAR, UNMAPPED); int j = 0; for (int i = 'A'; i <= 'Z'; i++) { CHAR_MAP[j] = i; @@ -176,8 +206,8 @@ public void write(final String str, final int off, final int len) throws IOExcep /** * Convert bit field of flags into string such as 'static final'. * - * @param accessFlags Access flags - * @return String representation of flags + * @param accessFlags Access flags. + * @return String representation of flags. */ public static String accessToString(final int accessFlags) { return accessToString(accessFlags, false); @@ -185,13 +215,14 @@ public static String accessToString(final int accessFlags) { /** * Convert bit field of flags into string such as 'static final'. - * + *

* Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized". * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'. + *

* - * @param accessFlags Access flags - * @param forClass access flags are for class qualifiers ? - * @return String representation of flags + * @param accessFlags Access flags. + * @param forClass access flags are for class qualifiers ?. + * @return String representation of flags. */ public static String accessToString(final int accessFlags, final boolean forClass) { final StringBuilder buf = new StringBuilder(); @@ -213,29 +244,43 @@ public static String accessToString(final int accessFlags, final boolean forClas } /** - * Convert (signed) byte to (unsigned) short value, i.e., all negative values become positive. + * Convert (signed) byte to (unsigned) short value, that is, all negative values become positive. */ private static short byteToShort(final byte b) { return b < 0 ? (short) (256 + b) : (short) b; } /** - * @param accessFlags the class flags + * Gets the class or interface type name. * - * @return "class" or "interface", depending on the ACC_INTERFACE flag + * @param accessFlags The class flags. + * @return "class" or "interface", depending on the ACC_INTERFACE flag. */ public static String classOrInterface(final int accessFlags) { return (accessFlags & Const.ACC_INTERFACE) != 0 ? "interface" : "class"; } /** - * @return 'flag' with bit 'i' set to 0 + * Clears a bit in a flag. + * + * @param flag The flag value. + * @param i The bit position. + * @return 'flag' with bit 'i' set to 0. */ public static int clearBit(final int flag, final int i) { final int bit = pow2(i); return (flag & bit) == 0 ? flag : flag ^ bit; } + /** + * Disassembles byte code. + * + * @param code byte code array. + * @param constantPool The constant pool. + * @param index offset in code array. + * @param length number of opcodes to decompile. + * @return disassembled string representation. + */ public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length) { return codeToString(code, constantPool, index, length, true); } @@ -244,15 +289,17 @@ public static String codeToString(final byte[] code, final ConstantPool constant * Disassemble a byte array of JVM byte codes starting from code line 'index' and return the disassembled string * representation. Decode only 'num' opcodes (including their operands), use -1 if you want to decompile everything. * - * @param code byte code array - * @param constantPool Array of constants - * @param index offset in 'code' array (number of opcodes, not bytes!) - * @param length number of opcodes to decompile, -1 for all - * @param verbose be verbose, e.g. print constant pool index - * @return String representation of byte codes + * @param code byte code array. + * @param constantPool Array of constants. + * @param index offset in 'code' array (number of opcodes, not bytes!). + * @param length number of opcodes to decompile, -1 for all. + * @param verbose be verbose, for example print constant pool index. + * @return String representation of byte codes. */ public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length, final boolean verbose) { final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber + // Defend against a stale flag left behind by a previous (possibly truncated) disassembly on this thread. + WIDE.set(Boolean.FALSE); try (ByteSequence stream = new ByteSequence(code)) { for (int i = 0; i < index; i++) { codeToString(stream, constantPool, verbose); @@ -265,10 +312,23 @@ public static String codeToString(final byte[] code, final ConstantPool constant } } catch (final IOException e) { throw new ClassFormatException("Byte code error: " + buf.toString(), e); + } finally { + // A crafted code array can end right after a WIDE opcode (normal loop exit) or throw before the flag is + // consumed; never leak the flag to the next disassembly on this thread, or that (unrelated) input is + // mis-decoded from its first load/store/iinc/ret instruction onwards. + WIDE.remove(); } return buf.toString(); } + /** + * Disassembles byte code. + * + * @param bytes stream of bytes. + * @param constantPool The constant pool. + * @return disassembled string representation. + * @throws IOException Thrown if a failure from reading from the bytes argument occurs. + */ public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool) throws IOException { return codeToString(bytes, constantPool, true); } @@ -276,37 +336,34 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c /** * Disassemble a stream of byte codes and return the string representation. * - * @param bytes stream of bytes - * @param constantPool Array of constants - * @param verbose be verbose, e.g. print constant pool index - * @return String representation of byte code - * - * @throws IOException if a failure from reading from the bytes argument occurs + * @param bytes stream of bytes. + * @param constantPool Array of constants. + * @param verbose be verbose, for example print constant pool index. + * @return String representation of byte code. + * @throws IOException Thrown if a failure from reading from the bytes argument occurs */ - @SuppressWarnings("fallthrough") // by design for case Const.INSTANCEOF - public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, - final boolean verbose) throws IOException { + public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, final boolean verbose) throws IOException { final short opcode = (short) bytes.readUnsignedByte(); int defaultOffset = 0; - int low; - int high; - int npairs; - int index; - int vindex; - int constant; - int[] match; - int[] jumpTable; + final int low; + final int high; + final int npairs; + final int index; + final int vindex; + final int constant; + final int[] match; + final int[] jumpTable; int noPadBytes = 0; - int offset; + final int offset; final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode)); /* - * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned + * Special case: Skip (0-3) padding bytes, that is, the following bytes are 4-byte-aligned */ if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) { final int remainder = bytes.getIndex() % 4; noPadBytes = remainder == 0 ? 0 : 4 - remainder; for (int i = 0; i < noPadBytes; i++) { - byte b; + final byte b; if ((b = bytes.readByte()) != 0) { System.err.println("Warning: Padding byte != 0 in " + Const.getOpcodeName(opcode) + ":" + b); } @@ -323,8 +380,15 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c high = bytes.readInt(); offset = bytes.getIndex() - 12 - noPadBytes - 1; defaultOffset += offset; + // Each jump table entry is a 4 byte offset, so a well-formed table cannot declare more entries than fit + // into the remaining byte code; checking before allocating keeps a crafted low/high pair from forcing a + // huge allocation. + final long jumpTableLength = (long) high - low + 1; + if (jumpTableLength < 0 || jumpTableLength * 4 > bytes.available()) { + throw new ClassFormatException("Invalid TABLESWITCH: low = " + low + ", high = " + high + " but only " + bytes.available() + " bytes remain"); + } buf.append("\tdefault = ").append(defaultOffset).append(", low = ").append(low).append(", high = ").append(high).append("("); - jumpTable = new int[high - low + 1]; + jumpTable = new int[(int) jumpTableLength]; for (int i = 0; i < jumpTable.length; i++) { jumpTable[i] = offset + bytes.readInt(); buf.append(jumpTable[i]); @@ -340,6 +404,10 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c case Const.LOOKUPSWITCH: { npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - noPadBytes - 1; + // Each match-offset pair is 8 bytes, see the TABLESWITCH check above. + if (npairs < 0 || (long) npairs * 8 > bytes.available()) { + throw new ClassFormatException("Invalid LOOKUPSWITCH: npairs = " + npairs + " but only " + bytes.available() + " bytes remain"); + } match = new int[npairs]; jumpTable = new int[npairs]; defaultOffset += offset; @@ -399,9 +467,9 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c case Const.LLOAD: case Const.LSTORE: case Const.RET: - if (wide) { + if (WIDE.get().booleanValue()) { vindex = bytes.readUnsignedShort(); - wide = false; // Clear flag + WIDE.set(Boolean.FALSE); // Clear flag } else { vindex = bytes.readUnsignedByte(); } @@ -412,7 +480,7 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c * called again with the following opcode. */ case Const.WIDE: - wide = true; + WIDE.set(Boolean.TRUE); buf.append("\t(wide)"); break; /* @@ -507,10 +575,10 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c * Increment local variable. */ case Const.IINC: - if (wide) { + if (WIDE.get().booleanValue()) { vindex = bytes.readUnsignedShort(); constant = bytes.readShort(); - wide = false; + WIDE.set(Boolean.FALSE); } else { vindex = bytes.readUnsignedByte(); constant = bytes.readByte(); @@ -532,7 +600,7 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c buf.append(bytes.readInt()); break; default: // Never reached - throw new IllegalStateException("Unreachable default case reached!"); + throw new IllegalStateException("Unreachable default case reached."); } } } @@ -543,33 +611,33 @@ public static String codeToString(final ByteSequence bytes, final ConstantPool c /** * Shorten long class names, java/lang/String becomes String. * - * @param str The long class name - * @return Compacted class name + * @param str The long class name. + * @return Compacted class name. */ public static String compactClassName(final String str) { return compactClassName(str, true); } /** - * Shorten long class names, java/lang/String becomes java.lang.String, e.g.. If chopit is + * Shorten long class names, java/lang/String becomes java.lang.String, for example. If chopit is * true the prefix java.lang is also removed. * - * @param str The long class name - * @param chopit flag that determines whether chopping is executed or not - * @return Compacted class name + * @param str The long class name. + * @param chopit flag that determines whether chopping is executed or not. + * @return Compacted class name. */ public static String compactClassName(final String str, final boolean chopit) { return compactClassName(str, "java.lang.", chopit); } /** - * Shorten long class name str, i.e., chop off the prefix, if the class name starts with this string + * Shorten long class name str, that is, chop off the prefix, if the class name starts with this string * and the flag chopit is true. Slashes / are converted to dots .. * - * @param str The long class name - * @param prefix The prefix the get rid off - * @param chopit flag that determines whether chopping is executed or not - * @return Compacted class name + * @param str The long class name. + * @param prefix The prefix the get rid off. + * @param chopit flag that determines whether chopping is executed or not. + * @return Compacted class name. */ public static String compactClassName(String str, final String prefix, final boolean chopit) { final int len = prefix.length(); @@ -583,6 +651,9 @@ public static String compactClassName(String str, final String prefix, final boo /** * Escape all occurrences of newline chars '\n', quotes \", etc. + * + * @param label The string to convert. + * @return The converted string. */ public static String convertString(final String label) { final char[] ch = label.toCharArray(); @@ -645,13 +716,13 @@ private static int countBrackets(final String brackets) { /** * Decode a string back to a byte array. * - * @param s the string to convert - * @param uncompress use gzip to uncompress the stream of bytes - * - * @throws IOException if there's a gzip exception + * @param s The string to convert. + * @param uncompress use gzip to uncompress the stream of bytes. + * @return The decoded byte array. + * @throws IOException Thrown if there's a gzip exception or the decompressed data exceeds {@code MAX_DECODED_LENGTH}. */ public static byte[] decode(final String s, final boolean uncompress) throws IOException { - byte[] bytes; + final byte[] bytes; try (JavaReader jr = new JavaReader(new CharArrayReader(s.toCharArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { int ch; while ((ch = jr.read()) >= 0) { @@ -660,20 +731,17 @@ public static byte[] decode(final String s, final boolean uncompress) throws IOE bytes = bos.toByteArray(); } if (uncompress) { - final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes)); - final byte[] tmp = new byte[bytes.length * 3]; // Rough estimate - int count = 0; - int b; - while ((b = gis.read()) >= 0) { - tmp[count++] = (byte) b; + // @formatter:off + try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes))) { + return gis.readNBytes(MAX_DECODED_LENGTH + 1); } - bytes = Arrays.copyOf(tmp, count); + // @formatter:on } return bytes; } /** - * Encode byte array it into Java identifier string, i.e., a string that only contains the following characters: (a, ... + * Encode byte array it into Java identifier string, that is, a string that only contains the following characters: (a, ... * z, A, ... Z, 0, ... 9, _, $). The encoding algorithm itself is not too clever: if the current byte's ASCII value * already is a valid Java identifier part, leave it as it is. Otherwise it writes the escape character($) followed by: * @@ -686,10 +754,10 @@ public static byte[] decode(final String s, final boolean uncompress) throws IOE * This operation inflates the original byte array by roughly 40-50% *

* - * @param bytes the byte array to convert - * @param compress use gzip to minimize string - * - * @throws IOException if there's a gzip exception + * @param bytes The byte array to convert. + * @param compress use gzip to minimize string. + * @return The encoded string. + * @throws IOException Thrown if there's a gzip exception. */ public static String encode(byte[] bytes, final boolean compress) throws IOException { if (compress) { @@ -712,11 +780,11 @@ public static String encode(byte[] bytes, final boolean compress) throws IOExcep /** * Fillup char with up to length characters with char 'fill' and justify it left or right. * - * @param str string to format - * @param length length of desired string - * @param leftJustify format left or right - * @param fill fill character - * @return formatted string + * @param str string to format. + * @param length length of desired string. + * @param leftJustify format left or right. + * @param fill fill character. + * @return formatted string. */ public static String fillup(final String str, final int length, final boolean leftJustify, final char fill) { final int len = length - str.length(); @@ -731,46 +799,22 @@ public static String fillup(final String str, final int length, final boolean le /** * Return a string for an integer justified left or right and filled up with 'fill' characters if necessary. * - * @param i integer to format - * @param length length of desired string - * @param leftJustify format left or right - * @param fill fill character - * @return formatted int + * @param i integer to format. + * @param length length of desired string. + * @param leftJustify format left or right. + * @param fill fill character. + * @return formatted int. */ public static String format(final int i, final int length, final boolean leftJustify, final char fill) { return fillup(Integer.toString(i), length, leftJustify, fill); } /** - * WARNING: - * - * There is some nomenclature confusion through much of the BCEL code base with respect to the terms Descriptor and - * Signature. For the offical definitions see: - * - * @see Descriptors in The Java - * Virtual Machine Specification - * - * @see Signatures in The Java - * Virtual Machine Specification - * - * In brief, a descriptor is a string representing the type of a field or method. Signatures are similar, but more - * complex. Signatures are used to encode declarations written in the Java programming language that use types - * outside the type system of the Java Virtual Machine. They are used to describe the type of any class, interface, - * constructor, method or field whose declaration uses type variables or parameterized types. - * - * To parse a descriptor, call typeSignatureToString. To parse a signature, call signatureToString. - * - * Note that if the signature string is a single, non-generic item, the call to signatureToString reduces to a call - * to typeSignatureToString. Also note, that if you only wish to parse the first item in a longer signature string, - * you should call typeSignatureToString directly. - */ - - /** - * Parse Java type such as "char", or "java.lang.String[]" and return the signature in byte code format, e.g. "C" or + * Parse Java type such as "char", or "java.lang.String[]" and return the signature in byte code format, for example "C" or * "[Ljava/lang/String;" respectively. * - * @param type Java type - * @return byte code signature + * @param type Java type. + * @return byte code signature. */ public static String getSignature(String type) { final StringBuilder buf = new StringBuilder(); @@ -824,17 +868,50 @@ public static String getSignature(String type) { return buf.toString(); } + private static boolean isHex(final int i) { + return i >= '0' && i <= '9' || i >= 'a' && i <= 'f'; + } + + /** + * WARNING: + * + * There is some nomenclature confusion through much of the BCEL code base with respect to the terms Descriptor and + * Signature. For the offical definitions see: + * + * @see Descriptors in The Java + * Virtual Machine Specification + * + * @see Signatures in The Java + * Virtual Machine Specification + * + * In brief, a descriptor is a string representing the type of a field or method. Signatures are similar, but more + * complex. Signatures are used to encode declarations written in the Java programming language that use types + * outside the type system of the Java Virtual Machine. They are used to describe the type of any class, interface, + * constructor, method or field whose declaration uses type variables or parameterized types. + * + * To parse a descriptor, call typeSignatureToString. To parse a signature, call signatureToString. + * + * Note that if the signature string is a single, non-generic item, the call to signatureToString reduces to a call + * to typeSignatureToString. Also note, that if you only wish to parse the first item in a longer signature string, + * you should call typeSignatureToString directly. + */ + /** - * @param ch the character to test if it's part of an identifier + * Tests if a character is part of a Java identifier. * - * @return true, if character is one of (a, ... z, A, ... Z, 0, ... 9, _) + * @param ch The character to test if it's part of an identifier. + * @return true, if character is one of (a, ... z, A, ... Z, 0, ... 9, _). */ public static boolean isJavaIdentifierPart(final char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_'; } /** - * @return true, if bit 'i' in 'flag' is set + * Tests if a bit is set. + * + * @param flag The flag value. + * @param i The bit position. + * @return true, if bit 'i' in 'flag' is set. */ public static boolean isSet(final int flag, final int i) { return (flag & pow2(i)) != 0; @@ -843,9 +920,9 @@ public static boolean isSet(final int flag, final int i) { /** * Converts argument list portion of method signature to string with all class names compacted. * - * @param signature Method signature - * @return String Array of argument types - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature Method signature. + * @return String Array of argument types. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ public static String[] methodSignatureArgumentTypes(final String signature) throws ClassFormatException { return methodSignatureArgumentTypes(signature, true); @@ -854,10 +931,10 @@ public static String[] methodSignatureArgumentTypes(final String signature) thro /** * Converts argument list portion of method signature to string. * - * @param signature Method signature - * @param chopit flag that determines whether chopping is executed or not - * @return String Array of argument types - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature Method signature. + * @param chopit flag that determines whether chopping is executed or not. + * @return String Array of argument types. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ public static String[] methodSignatureArgumentTypes(final String signature, final boolean chopit) throws ClassFormatException { final List vec = new ArrayList<>(); @@ -882,9 +959,9 @@ public static String[] methodSignatureArgumentTypes(final String signature, fina /** * Converts return type portion of method signature to string with all class names compacted. * - * @param signature Method signature - * @return String representation of method return type - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature Method signature. + * @return String representation of method return type. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ public static String methodSignatureReturnType(final String signature) throws ClassFormatException { return methodSignatureReturnType(signature, true); @@ -893,34 +970,31 @@ public static String methodSignatureReturnType(final String signature) throws Cl /** * Converts return type portion of method signature to string. * - * @param signature Method signature - * @param chopit flag that determines whether chopping is executed or not - * @return String representation of method return type - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature Method signature. + * @param chopit flag that determines whether chopping is executed or not. + * @return String representation of method return type. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ public static String methodSignatureReturnType(final String signature, final boolean chopit) throws ClassFormatException { - int index; - String type; try { // Read return type after ')' - index = signature.lastIndexOf(')') + 1; + final int index = signature.lastIndexOf(')') + 1; if (index <= 0) { throw new InvalidMethodSignatureException(signature); } - type = typeSignatureToString(signature.substring(index), chopit); + return typeSignatureToString(signature.substring(index), chopit); } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new InvalidMethodSignatureException(signature, e); } - return type; } /** * Converts method signature to string with all class names compacted. * - * @param signature to convert - * @param name of method - * @param access flags of method - * @return Human readable signature + * @param signature to convert. + * @param name of method. + * @param access flags of method. + * @return Human readable signature. */ public static String methodSignatureToString(final String signature, final String name, final String access) { return methodSignatureToString(signature, name, access, true); @@ -929,11 +1003,11 @@ public static String methodSignatureToString(final String signature, final Strin /** * Converts method signature to string. * - * @param signature to convert - * @param name of method - * @param access flags of method - * @param chopit flag that determines whether chopping is executed or not - * @return Human readable signature + * @param signature to convert. + * @param name of method. + * @param access flags of method. + * @param chopit flag that determines whether chopping is executed or not. + * @return Human readable signature. */ public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit) { return methodSignatureToString(signature, name, access, chopit, null); @@ -943,18 +1017,18 @@ public static String methodSignatureToString(final String signature, final Strin * This method converts a method signature string into a Java type declaration like 'void main(String[])' and throws a * 'ClassFormatException' when the parsed type is invalid. * - * @param signature Method signature - * @param name Method name - * @param access Method access rights - * @param chopit flag that determines whether chopping is executed or not - * @param vars the LocalVariableTable for the method - * @return Java type declaration - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature Method signature. + * @param name Method name. + * @param access Method access rights. + * @param chopit flag that determines whether chopping is executed or not. + * @param vars The LocalVariableTable for the method. + * @return Java type declaration. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file */ public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit, final LocalVariableTable vars) throws ClassFormatException { final StringBuilder buf = new StringBuilder("("); - String type; + final String type; int index; int varIndex = access.contains("static") ? 0 : 1; try { @@ -1001,11 +1075,10 @@ public static String methodSignatureToString(final String signature, final Strin /** * Converts string containing the method return and argument types to a byte code method signature. * - * @param ret Return type of method - * @param argv Types of method arguments - * @return Byte code representation of method signature - * - * @throws ClassFormatException if the signature is for Void + * @param ret Return type of method. + * @param argv Types of method arguments. + * @return Byte code representation of method signature. + * @throws ClassFormatException Thrown if the signature is for Void */ public static String methodTypeToSignature(final String ret, final String[] argv) throws ClassFormatException { final StringBuilder buf = new StringBuilder("("); @@ -1027,8 +1100,8 @@ public static String methodTypeToSignature(final String ret, final String[] argv /** * Converts '.'s to '/'s. * - * @param name Source - * @return converted value + * @param name Source. + * @return converted value. * @since 6.7.0 */ public static String packageToPath(final String name) { @@ -1038,8 +1111,8 @@ public static String packageToPath(final String name) { /** * Converts a path to a package name. * - * @param str the source path. - * @return a package name. + * @param str The source path. + * @return A package name. * @since 6.6.0 */ public static String pathToPackage(final String str) { @@ -1050,14 +1123,35 @@ private static int pow2(final int n) { return 1 << n; } + /** + * Prints an array to a string. + * + * @param obj The array to print. + * @return The string representation. + */ public static String printArray(final Object[] obj) { return printArray(obj, true); } + /** + * Prints an array to a string. + * + * @param obj The array to print. + * @param braces whether to include braces. + * @return The string representation. + */ public static String printArray(final Object[] obj, final boolean braces) { return printArray(obj, braces, false); } + /** + * Prints an array to a string. + * + * @param obj The array to print. + * @param braces whether to include braces. + * @param quote whether to quote elements. + * @return The string representation. + */ public static String printArray(final Object[] obj, final boolean braces, final boolean quote) { if (obj == null) { return null; @@ -1082,10 +1176,22 @@ public static String printArray(final Object[] obj, final boolean braces, final return buf.toString(); } + /** + * Prints an array to a stream. + * + * @param out The output stream. + * @param obj The array to print. + */ public static void printArray(final PrintStream out, final Object[] obj) { out.println(printArray(obj, true)); } + /** + * Prints an array to a writer. + * + * @param out The output writer. + * @param obj The array to print. + */ public static void printArray(final PrintWriter out, final Object[] obj) { out.println(printArray(obj, true)); } @@ -1093,10 +1199,10 @@ public static void printArray(final PrintWriter out, final Object[] obj) { /** * Replace all occurrences of old in str with new. * - * @param str String to permute - * @param old String to be replaced - * @param new_ Replacement string - * @return new String object + * @param str String to permute. + * @param old String to be replaced. + * @param new_ Replacement string. + * @return new String object. */ public static String replace(String str, final String old, final String new_) { int index; @@ -1121,12 +1227,15 @@ public static String replace(String str, final String old, final String new_) { } /** - * Map opcode names to opcode numbers. E.g., return Constants.ALOAD for "aload" + * Map opcode names to opcode numbers. E.g., return Constants.ALOAD for "aload". + * + * @param name The opcode name. + * @return The value. */ - public static short searchOpcode(String name) { - name = name.toLowerCase(Locale.ENGLISH); + public static short searchOpcode(final String name) { + final String lcName = Utils.toLowerCase(name); for (short i = 0; i < Const.OPCODE_NAMES_LENGTH; i++) { - if (Const.getOpcodeName(i).equals(name)) { + if (Const.getOpcodeName(i).equals(lcName)) { return i; } } @@ -1134,7 +1243,11 @@ public static short searchOpcode(String name) { } /** - * @return 'flag' with bit 'i' set to 1 + * Sets a bit in a flag. + * + * @param flag The flag value. + * @param i The bit position. + * @return 'flag' with bit 'i' set to 1. */ public static int setBit(final int flag, final int i) { return flag | pow2(i); @@ -1144,8 +1257,8 @@ public static int setBit(final int flag, final int i) { * Converts a signature to a string with all class names compacted. Class, Method and Type signatures are supported. * Enum and Interface signatures are not supported. * - * @param signature signature to convert - * @return String containg human readable signature + * @param signature signature to convert. + * @return String containg human readable signature. */ public static String signatureToString(final String signature) { return signatureToString(signature, true); @@ -1155,16 +1268,16 @@ public static String signatureToString(final String signature) { * Converts a signature to a string. Class, Method and Type signatures are supported. Enum and Interface signatures are * not supported. * - * @param signature signature to convert - * @param chopit flag that determines whether chopping is executed or not - * @return String containg human readable signature + * @param signature signature to convert. + * @param chopit flag that determines whether chopping is executed or not. + * @return String containg human readable signature. */ public static String signatureToString(final String signature, final boolean chopit) { String type = ""; String typeParams = ""; int index = 0; if (signature.charAt(0) == '<') { - // we have type paramters + // we have type parameters typeParams = typeParamTypesToString(signature, chopit); index += unwrap(CONSUMER_CHARS); // update position } @@ -1206,9 +1319,8 @@ public static String signatureToString(final String signature, final boolean cho /** * Convert bytes into hexadecimal string * - * @param bytes an array of bytes to convert to hexadecimal - * - * @return bytes as hexadecimal string, e.g. 00 fa 12 ... + * @param bytes An array of bytes to convert to hexadecimal. + * @return bytes as hexadecimal string, for example 00 fa 12 ... */ public static String toHexString(final byte[] bytes) { final StringBuilder buf = new StringBuilder(); @@ -1229,19 +1341,17 @@ public static String toHexString(final byte[] bytes) { /** * Return type of method signature as a byte value as defined in Constants * - * @param signature in format described above - * @return type of method signature + * @param signature in format described above. + * @return type of method signature. * @see Const - * - * @throws ClassFormatException if signature is not a method signature + * @throws ClassFormatException Thrown if signature is not a method signature */ public static byte typeOfMethodSignature(final String signature) throws ClassFormatException { - int index; try { if (signature.charAt(0) != '(') { throw new InvalidMethodSignatureException(signature); } - index = signature.lastIndexOf(')') + 1; + final int index = signature.lastIndexOf(')') + 1; return typeOfSignature(signature.substring(index)); } catch (final StringIndexOutOfBoundsException e) { throw new InvalidMethodSignatureException(signature, e); @@ -1251,11 +1361,10 @@ public static byte typeOfMethodSignature(final String signature) throws ClassFor /** * Return type of signature as a byte value as defined in Constants * - * @param signature in format described above - * @return type of signature + * @param signature in format described above. + * @return type of signature. * @see Const - * - * @throws ClassFormatException if signature isn't a known type + * @throws ClassFormatException Thrown if signature isn't a known type */ public static byte typeOfSignature(final String signature) throws ClassFormatException { try { @@ -1298,9 +1407,9 @@ public static byte typeOfSignature(final String signature) throws ClassFormatExc /** * Converts a type parameter list signature to a string. * - * @param signature signature to convert - * @param chopit flag that determines whether chopping is executed or not - * @return String containg human readable signature + * @param signature signature to convert. + * @param chopit flag that determines whether chopping is executed or not. + * @return String containg human readable signature. */ private static String typeParamTypesToString(final String signature, final boolean chopit) { // The first character is guranteed to be '<' @@ -1322,9 +1431,9 @@ private static String typeParamTypesToString(final String signature, final boole /** * Converts a type parameter signature to a string. * - * @param signature signature to convert - * @param chopit flag that determines whether chopping is executed or not - * @return String containg human readable signature + * @param signature signature to convert. + * @param chopit flag that determines whether chopping is executed or not. + * @return String containg human readable signature. */ private static String typeParamTypeToString(final String signature, final boolean chopit) { int index = signature.indexOf(':'); @@ -1354,10 +1463,10 @@ private static String typeParamTypeToString(final String signature, final boolea /** * Converts a list of type signatures to a string. * - * @param signature signature to convert - * @param chopit flag that determines whether chopping is executed or not - * @param term character indicating the end of the list - * @return String containg human readable signature + * @param signature signature to convert. + * @param chopit flag that determines whether chopping is executed or not. + * @param term character indicating the end of the list. + * @return String containg human readable signature. */ private static String typeSignaturesToString(final String signature, final boolean chopit, final char term) { // The first character will be an 'open' that matches the 'close' contained in term. @@ -1383,13 +1492,29 @@ private static String typeSignaturesToString(final String signature, final boole * This method converts a type signature string into a Java type declaration such as 'String[]' and throws a * 'ClassFormatException' when the parsed type is invalid. * - * @param signature type signature - * @param chopit flag that determines whether chopping is executed or not - * @return string containing human readable type signature - * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file + * @param signature type signature. + * @param chopit flag that determines whether chopping is executed or not. + * @return string containing human readable type signature. + * @throws ClassFormatException Thrown if a class is malformed or cannot be interpreted as a class file * @since 6.4.0 */ public static String typeSignatureToString(final String signature, final boolean chopit) throws ClassFormatException { + return typeSignatureToString(signature, chopit, 0); + } + + /** + * Recursive worker for {@link #typeSignatureToString(String, boolean)} carrying the current nesting depth. + * + * @param signature type signature. + * @param chopit flag that determines whether chopping is executed or not. + * @param depth current nesting depth. + * @return string containing human readable type signature. + * @throws ClassFormatException Thrown if the signature is malformed or nested deeper than {@code MAX_SIGNATURE_NESTING}. + */ + private static String typeSignatureToString(final String signature, final boolean chopit, final int depth) throws ClassFormatException { + if (depth > MAX_SIGNATURE_NESTING) { + throw new ClassFormatException("Invalid signature: nesting depth exceeds " + MAX_SIGNATURE_NESTING); + } // corrected concurrent private static field acess wrap(CONSUMER_CHARS, 1); // This is the default, read just one char like 'B' try { @@ -1469,7 +1594,7 @@ public static String typeSignatureToString(final String signature, final boolean type.append("?"); consumedChars++; } else { - type.append(typeSignatureToString(signature.substring(consumedChars), chopit)); + type.append(typeSignatureToString(signature.substring(consumedChars), chopit, depth + 1)); // update our consumed count by the number of characters the for type argument consumedChars = unwrap(CONSUMER_CHARS) + consumedChars; wrap(CONSUMER_CHARS, consumedChars); @@ -1490,7 +1615,7 @@ public static String typeSignatureToString(final String signature, final boolean type.append("?"); consumedChars++; } else { - type.append(typeSignatureToString(signature.substring(consumedChars), chopit)); + type.append(typeSignatureToString(signature.substring(consumedChars), chopit, depth + 1)); // update our consumed count by the number of characters the for type argument consumedChars = unwrap(CONSUMER_CHARS) + consumedChars; wrap(CONSUMER_CHARS, consumedChars); @@ -1506,7 +1631,7 @@ public static String typeSignatureToString(final String signature, final boolean type.append("."); // convert SimpleClassTypeSignature to fake ClassTypeSignature // and then recurse to parse it - type.append(typeSignatureToString("L" + signature.substring(consumedChars + 1), chopit)); + type.append(typeSignatureToString("L" + signature.substring(consumedChars + 1), chopit, depth + 1)); // update our consumed count by the number of characters the for type argument // note that this count includes the "L" we added, but that is ok // as it accounts for the "." we didn't consume @@ -1526,17 +1651,14 @@ public static String typeSignatureToString(final String signature, final boolean return "boolean"; case '[': { // Array declaration int n; - StringBuilder brackets; - String type; - int consumedChars; // Shadows global var - brackets = new StringBuilder(); // Accumulate []'s + final StringBuilder brackets = new StringBuilder(); // Accumulate []'s // Count opening brackets and look for optional size argument for (n = 0; signature.charAt(n) == '['; n++) { brackets.append("[]"); } - consumedChars = n; // Remember value + final int consumedChars = n; // Remember value // The rest of the string denotes a '' - type = typeSignatureToString(signature.substring(n), chopit); + final String type = typeSignatureToString(signature.substring(n), chopit, depth + 1); // corrected concurrent private static field acess // consumed_chars += consumed_chars; is replaced by: final int temp = unwrap(CONSUMER_CHARS) + consumedChars; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Visitor.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Visitor.java index 1f6fe9c96eec..60e78a703a2f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Visitor.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/classfile/Visitor.java @@ -26,118 +26,290 @@ * traverse the contents of a Java class just by calling the 'accept' method which all classes have. */ public interface Visitor { + /** + * Visits an Annotations attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitAnnotation(Annotations obj); /** + * Visits an AnnotationDefault attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitAnnotationDefault(AnnotationDefault obj); /** + * Visits an AnnotationEntry. + * + * @param obj The annotation entry. * @since 6.0 */ void visitAnnotationEntry(AnnotationEntry obj); /** + * Visits a BootstrapMethods attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitBootstrapMethods(BootstrapMethods obj); + /** + * Visits a Code attribute. + * + * @param obj The attribute. + */ void visitCode(Code obj); + /** + * Visits a CodeException. + * + * @param obj The exception. + */ void visitCodeException(CodeException obj); + /** + * Visits a ConstantClass. + * + * @param obj The constant. + */ void visitConstantClass(ConstantClass obj); + /** + * Visits a ConstantDouble. + * + * @param obj The constant. + */ void visitConstantDouble(ConstantDouble obj); /** + * Visits a ConstantDynamic. + * + * @param constantDynamic The constant. * @since 6.3 */ default void visitConstantDynamic(final ConstantDynamic constantDynamic) { // empty } + /** + * Visits a ConstantFieldref. + * + * @param obj The constant. + */ void visitConstantFieldref(ConstantFieldref obj); + /** + * Visits a ConstantFloat. + * + * @param obj The constant. + */ void visitConstantFloat(ConstantFloat obj); + /** + * Visits a ConstantInteger. + * + * @param obj The constant. + */ void visitConstantInteger(ConstantInteger obj); + /** + * Visits a ConstantInterfaceMethodref. + * + * @param obj The constant. + */ void visitConstantInterfaceMethodref(ConstantInterfaceMethodref obj); + /** + * Visits a ConstantInvokeDynamic. + * + * @param obj The constant. + */ void visitConstantInvokeDynamic(ConstantInvokeDynamic obj); + /** + * Visits a ConstantLong. + * + * @param obj The constant. + */ void visitConstantLong(ConstantLong obj); /** + * Visits a ConstantMethodHandle. + * + * @param obj The constant. * @since 6.0 */ void visitConstantMethodHandle(ConstantMethodHandle obj); + /** + * Visits a ConstantMethodref. + * + * @param obj The constant. + */ void visitConstantMethodref(ConstantMethodref obj); /** + * Visits a ConstantMethodType. + * + * @param obj The constant. * @since 6.0 */ void visitConstantMethodType(ConstantMethodType obj); /** + * Visits a ConstantModule. + * + * @param constantModule The constant. * @since 6.1 */ void visitConstantModule(ConstantModule constantModule); + /** + * Visits a ConstantNameAndType. + * + * @param obj The constant. + */ void visitConstantNameAndType(ConstantNameAndType obj); /** + * Visits a ConstantPackage. + * + * @param constantPackage The constant. * @since 6.1 */ void visitConstantPackage(ConstantPackage constantPackage); + /** + * Visits a ConstantPool. + * + * @param obj The constant pool. + */ void visitConstantPool(ConstantPool obj); + /** + * Visits a ConstantString. + * + * @param obj The constant. + */ void visitConstantString(ConstantString obj); + /** + * Visits a ConstantUtf8. + * + * @param obj The constant. + */ void visitConstantUtf8(ConstantUtf8 obj); + /** + * Visits a ConstantValue attribute. + * + * @param obj The attribute. + */ void visitConstantValue(ConstantValue obj); + /** + * Visits a Deprecated attribute. + * + * @param obj The attribute. + */ void visitDeprecated(Deprecated obj); /** + * Visits an EnclosingMethod attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitEnclosingMethod(EnclosingMethod obj); + /** + * Visits an ExceptionTable attribute. + * + * @param obj The attribute. + */ void visitExceptionTable(ExceptionTable obj); + /** + * Visits a Field. + * + * @param obj The field. + */ void visitField(Field obj); + /** + * Visits an InnerClass. + * + * @param obj The inner class. + */ void visitInnerClass(InnerClass obj); + /** + * Visits an InnerClasses attribute. + * + * @param obj The attribute. + */ void visitInnerClasses(InnerClasses obj); + /** + * Visits a JavaClass. + * + * @param obj The class. + */ void visitJavaClass(JavaClass obj); + /** + * Visits a LineNumber. + * + * @param obj The line number. + */ void visitLineNumber(LineNumber obj); + /** + * Visits a LineNumberTable attribute. + * + * @param obj The attribute. + */ void visitLineNumberTable(LineNumberTable obj); + /** + * Visits a LocalVariable. + * + * @param obj The local variable. + */ void visitLocalVariable(LocalVariable obj); + /** + * Visits a LocalVariableTable attribute. + * + * @param obj The attribute. + */ void visitLocalVariableTable(LocalVariableTable obj); /** + * Visits a LocalVariableTypeTable attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitLocalVariableTypeTable(LocalVariableTypeTable obj); + /** + * Visits a Method. + * + * @param obj The method. + */ void visitMethod(Method obj); /** + * Visits a MethodParameter. + * + * @param obj The method parameter. * @since 6.4.0 */ default void visitMethodParameter(final MethodParameter obj) { @@ -145,11 +317,17 @@ default void visitMethodParameter(final MethodParameter obj) { } /** + * Visits a MethodParameters attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitMethodParameters(MethodParameters obj); /** + * Visits a Module attribute. + * + * @param constantModule The module. * @since 6.4.0 */ default void visitModule(final Module constantModule) { @@ -157,6 +335,9 @@ default void visitModule(final Module constantModule) { } /** + * Visits a ModuleExports entry. + * + * @param constantModule The module exports. * @since 6.4.0 */ default void visitModuleExports(final ModuleExports constantModule) { @@ -164,6 +345,9 @@ default void visitModuleExports(final ModuleExports constantModule) { } /** + * Visits a ModuleMainClass attribute. + * + * @param obj The attribute. * @since 6.4.0 */ default void visitModuleMainClass(final ModuleMainClass obj) { @@ -171,6 +355,9 @@ default void visitModuleMainClass(final ModuleMainClass obj) { } /** + * Visits a ModuleOpens entry. + * + * @param constantModule The module opens. * @since 6.4.0 */ default void visitModuleOpens(final ModuleOpens constantModule) { @@ -178,6 +365,9 @@ default void visitModuleOpens(final ModuleOpens constantModule) { } /** + * Visits a ModulePackages attribute. + * + * @param constantModule The module packages. * @since 6.4.0 */ default void visitModulePackages(final ModulePackages constantModule) { @@ -185,6 +375,9 @@ default void visitModulePackages(final ModulePackages constantModule) { } /** + * Visits a ModuleProvides entry. + * + * @param constantModule The module provides. * @since 6.4.0 */ default void visitModuleProvides(final ModuleProvides constantModule) { @@ -192,6 +385,9 @@ default void visitModuleProvides(final ModuleProvides constantModule) { } /** + * Visits a ModuleRequires entry. + * + * @param constantModule The module requires. * @since 6.4.0 */ default void visitModuleRequires(final ModuleRequires constantModule) { @@ -199,6 +395,9 @@ default void visitModuleRequires(final ModuleRequires constantModule) { } /** + * Visits a NestHost attribute. + * + * @param obj The attribute. * @since 6.4.0 */ default void visitNestHost(final NestHost obj) { @@ -206,6 +405,9 @@ default void visitNestHost(final NestHost obj) { } /** + * Visits a NestMembers attribute. + * + * @param obj The attribute. * @since 6.4.0 */ default void visitNestMembers(final NestMembers obj) { @@ -213,20 +415,35 @@ default void visitNestMembers(final NestMembers obj) { } /** + * Visits a ParameterAnnotations attribute. + * + * @param obj The attribute. * @since 6.0 */ void visitParameterAnnotation(ParameterAnnotations obj); - /** + * Visits a ParameterAnnotationEntry. + * + * @param obj The annotation entry. * @since 6.0 */ void visitParameterAnnotationEntry(ParameterAnnotationEntry obj); + /** + * Visits a PermittedSubclasses attribute. + * + * @param obj The attribute. + * @since 6.13.0 + */ + default void visitPermittedSubclasses(final PermittedSubclasses obj) { + // empty + } + /** * Visits a {@link Record} object. * - * @param obj Record to visit + * @param obj Record to visit. * @since 6.9.0 */ default void visitRecord(final Record obj) { @@ -236,33 +453,63 @@ default void visitRecord(final Record obj) { /** * Visits a {@link RecordComponentInfo} object. * - * @param record component to visit + * @param record component to visit. * @since 6.9.0 */ default void visitRecordComponent(final RecordComponentInfo record) { // noop } + /** + * Visits a Signature attribute. + * + * @param obj The attribute. + */ void visitSignature(Signature obj); + /** + * Visits a SourceFile attribute. + * + * @param obj The attribute. + */ void visitSourceFile(SourceFile obj); + /** + * Visits a StackMap attribute. + * + * @param obj The attribute. + */ void visitStackMap(StackMap obj); + /** + * Visits a StackMapEntry. + * + * @param obj The entry. + */ void visitStackMapEntry(StackMapEntry obj); /** * Visits a {@link StackMapType} object. * - * @param obj object to visit + * @param obj object to visit. * @since 6.8.0 */ default void visitStackMapType(final StackMapType obj) { // empty } + /** + * Visits a Synthetic attribute. + * + * @param obj The attribute. + */ void visitSynthetic(Synthetic obj); + /** + * Visits an Unknown attribute. + * + * @param obj The attribute. + */ void visitUnknown(Unknown obj); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AALOAD.java index 19bd38d0a7d4..8e6bba355578 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AALOAD.java @@ -24,9 +24,9 @@ /** * AALOAD - Load reference from array * - *
+ * 
  * Stack: ..., arrayref, index -> value
- * 
+ *
*/ public class AALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public AALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AASTORE.java index 9561ab4c77bb..4146fb27a3c2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AASTORE.java @@ -24,9 +24,9 @@ /** * AASTORE - Store into reference array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class AASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public AASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ACONST_NULL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ACONST_NULL.java index 95556b9d085e..94be6185a944 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ACONST_NULL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ACONST_NULL.java @@ -24,9 +24,9 @@ /** * ACONST_NULL - Push null reference * - *
+ * 
  * Stack: ... -> ..., null
- * 
+ *
*/ public class ACONST_NULL extends Instruction implements PushInstruction, TypedInstruction { @@ -39,9 +39,9 @@ public ACONST_NULL() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -52,7 +52,7 @@ public void accept(final Visitor v) { } /** - * @return Type.NULL + * @return Type.NULL. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ALOAD.java index 8db0f9fadeb3..ddecfeffc2df 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ALOAD.java @@ -23,10 +23,9 @@ /** * ALOAD - Load reference from local variable * - *
+ * 
  * Stack: ... -> ..., objectref
- * 
- * @LastModified: Jan 2020 + *
*/ public class ALOAD extends LoadInstruction { @@ -40,7 +39,7 @@ public class ALOAD extends LoadInstruction { /** * Load reference from local variable * - * @param n index of local variable + * @param n index of local variable. */ public ALOAD(final int n) { super(com.sun.org.apache.bcel.internal.Const.ALOAD, com.sun.org.apache.bcel.internal.Const.ALOAD_0, n); @@ -48,9 +47,9 @@ public ALOAD(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ANEWARRAY.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ANEWARRAY.java index eabf15c38b4b..a254824df562 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ANEWARRAY.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ANEWARRAY.java @@ -26,9 +26,9 @@ /** * ANEWARRAY - Create new array of references * - *
+ * 
  * Stack: ..., count -> ..., arrayref
- * 
+ *
*/ public class ANEWARRAY extends CPInstruction implements LoadClass, AllocationInstruction, ExceptionThrower, StackConsumer, StackProducer { @@ -38,15 +38,20 @@ public class ANEWARRAY extends CPInstruction implements LoadClass, AllocationIns ANEWARRAY() { } + /** + * Constructs an ANEWARRAY instruction. + * + * @param index index into the constant pool. + */ public ANEWARRAY(final int index) { super(com.sun.org.apache.bcel.internal.Const.ANEWARRAY, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARETURN.java index ff2428d457cf..67ca231b0513 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARETURN.java @@ -24,9 +24,9 @@ /** * ARETURN - Return reference from method * - *
+ * 
  * Stack: ..., objectref -> <empty>
- * 
+ *
*/ public class ARETURN extends ReturnInstruction { @@ -39,9 +39,9 @@ public ARETURN() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARRAYLENGTH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARRAYLENGTH.java index db756700085d..092c08d12ddd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARRAYLENGTH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ARRAYLENGTH.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,10 +25,10 @@ /** * ARRAYLENGTH - Get length of array * - *
+ * 
  * Stack: ..., arrayref -> ..., length
- * 
- * @LastModified: Sept 2025 + *
+ * @LastModified: Nov 2026 */ public class ARRAYLENGTH extends Instruction implements ExceptionThrower, StackProducer, StackConsumer /* since 6.0 */ { @@ -41,9 +41,9 @@ public ARRAYLENGTH() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -53,7 +53,7 @@ public void accept(final Visitor v) { } /** - * @return exceptions this instruction may cause + * @return exceptions this instruction may cause. */ @Override public Class[] getExceptions() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ASTORE.java index 7852c66466f6..6b7224d4ffb4 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ASTORE.java @@ -22,10 +22,9 @@ /** * ASTORE - Store reference into local variable * - *
+ * 
  * Stack ..., objectref -> ...
- * 
- * @LastModified: Jan 2020 + *
*/ public class ASTORE extends StoreInstruction { @@ -39,7 +38,7 @@ public class ASTORE extends StoreInstruction { /** * Store reference into local variable * - * @param n index of local variable + * @param n index of local variable. */ public ASTORE(final int n) { super(com.sun.org.apache.bcel.internal.Const.ASTORE, com.sun.org.apache.bcel.internal.Const.ASTORE_0, n); @@ -47,9 +46,9 @@ public ASTORE(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ATHROW.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ATHROW.java index 07171fefde15..7c17da6e7503 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ATHROW.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ATHROW.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,11 +25,10 @@ /** * ATHROW - Throw exception * - *
+ * 
  * Stack: ..., objectref -> objectref
- * 
- * - * @LastModified: Sept 2025 + *
+ * @LastModified: Nov 2026 */ public class ATHROW extends Instruction implements UnconditionalBranch, ExceptionThrower, StackConsumer { @@ -42,9 +41,9 @@ public ATHROW() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +54,7 @@ public void accept(final Visitor v) { } /** - * @return exceptions this instruction may cause + * @return exceptions this instruction may cause. */ @Override public Class[] getExceptions() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationElementValueGen.java index 1ed232d72925..4f28804e934d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationElementValueGen.java @@ -28,22 +28,44 @@ import com.sun.org.apache.bcel.internal.classfile.ElementValue; /** + * Generates annotation element values. + * * @since 6.0 */ public class AnnotationElementValueGen extends ElementValueGen { // For annotation element values, this is the annotation private final AnnotationEntryGen a; + /** + * Constructs an AnnotationElementValueGen. + * + * @param value The annotation element value. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. + */ public AnnotationElementValueGen(final AnnotationElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { super(ANNOTATION, cpool); a = new AnnotationEntryGen(value.getAnnotationEntry(), cpool, copyPoolEntries); } + /** + * Constructs an AnnotationElementValueGen. + * + * @param a The annotation entry generator. + * @param cpool The constant pool generator. + */ public AnnotationElementValueGen(final AnnotationEntryGen a, final ConstantPoolGen cpool) { super(ANNOTATION, cpool); this.a = a; } + /** + * Constructs an AnnotationElementValueGen. + * + * @param type The type. + * @param annotation The annotation. + * @param cpool The constant pool generator. + */ public AnnotationElementValueGen(final int type, final AnnotationEntryGen annotation, final ConstantPoolGen cpool) { super(type, cpool); if (type != ANNOTATION) { @@ -58,12 +80,19 @@ public void dump(final DataOutputStream dos) throws IOException { a.dump(dos); } + /** + * Gets the annotation. + * + * @return The annotation. + */ public AnnotationEntryGen getAnnotation() { return a; } /** - * Return immutable variant of this AnnotationElementValueGen + * Returns an immutable variant of this AnnotationElementValueGen. + * + * @return An immutable variant of this AnnotationElementValueGen. */ @Override public ElementValue getElementValue() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationEntryGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationEntryGen.java index 0fad6ea7389d..32374b09e713 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationEntryGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/AnnotationEntryGen.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -38,11 +38,14 @@ import com.sun.org.apache.bcel.internal.classfile.RuntimeInvisibleParameterAnnotations; import com.sun.org.apache.bcel.internal.classfile.RuntimeVisibleAnnotations; import com.sun.org.apache.bcel.internal.classfile.RuntimeVisibleParameterAnnotations; +import com.sun.org.apache.bcel.internal.util.Args; import jdk.xml.internal.Utils; /** + * Generates annotation entries. + * * @since 6.0 - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class AnnotationEntryGen { @@ -51,11 +54,11 @@ public class AnnotationEntryGen { /** * Converts a list of AnnotationGen objects into a set of attributes that can be attached to the class file. * - * @param cp The constant pool gen where we can create the necessary name refs - * @param annotationEntryGens An array of AnnotationGen objects + * @param cp The constant pool gen where we can create the necessary name refs. + * @param annotationEntryGens An array of AnnotationGen objects. */ static Attribute[] getAnnotationAttributes(final ConstantPoolGen cp, final AnnotationEntryGen[] annotationEntryGens) { - if (annotationEntryGens == null && annotationEntryGens.length == 0) { + if (annotationEntryGens == null || annotationEntryGens.length == 0) { return Attribute.EMPTY_ARRAY; } @@ -147,7 +150,7 @@ static Attribute[] getParameterAnnotationAttributes(final ConstantPoolGen cp, // Lets do the visible ones final ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream(); try (DataOutputStream rvaDos = new DataOutputStream(rvaBytes)) { - rvaDos.writeByte(vec.length); // First goes number of parameters + rvaDos.writeByte(Args.requireU1(vec.length, "vec.length")); // First goes number of parameters for (int i = 0; i < vec.length; i++) { rvaDos.writeShort(visCount[i]); if (visCount[i] > 0) { @@ -162,7 +165,7 @@ static Attribute[] getParameterAnnotationAttributes(final ConstantPoolGen cp, // Lets do the invisible ones final ByteArrayOutputStream riaBytes = new ByteArrayOutputStream(); try (DataOutputStream riaDos = new DataOutputStream(riaBytes)) { - riaDos.writeByte(vec.length); // First goes number of parameters + riaDos.writeByte(Args.requireU1(vec.length, "vec.length")); // First goes number of parameters for (int i = 0; i < vec.length; i++) { riaDos.writeShort(invisCount[i]); if (invisCount[i] > 0) { @@ -201,6 +204,15 @@ static Attribute[] getParameterAnnotationAttributes(final ConstantPoolGen cp, return null; } + /** + * Reads an AnnotationEntryGen from a DataInput. + * + * @param dis The data input stream. + * @param cpool The constant pool generator. + * @param b whether the annotation is runtime visible. + * @return The annotation entry generator. + * @throws IOException Thrown if an I/O error occurs. + */ public static AnnotationEntryGen read(final DataInput dis, final ConstantPoolGen cpool, final boolean b) throws IOException { final AnnotationEntryGen a = new AnnotationEntryGen(cpool); a.typeIndex = dis.readUnsignedShort(); @@ -226,6 +238,10 @@ public static AnnotationEntryGen read(final DataInput dis, final ConstantPoolGen * passed in is for a different class file, then copyPoolEntries should have been passed as true as that will force us * to do a deep copy of the annotation and move the cpool entries across. We need to copy the type and the element name * value pairs and the visibility. + * + * @param a The annotation entry. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. */ public AnnotationEntryGen(final AnnotationEntry a, final ConstantPoolGen cpool, final boolean copyPoolEntries) { this.cpool = cpool; @@ -242,6 +258,14 @@ private AnnotationEntryGen(final ConstantPoolGen cpool) { this.cpool = cpool; } + /** + * Constructs an AnnotationEntryGen. + * + * @param type The object type. + * @param elements The element value pairs. + * @param vis whether the annotation is visible. + * @param cpool The constant pool generator. + */ public AnnotationEntryGen(final ObjectType type, final List elements, final boolean vis, final ConstantPoolGen cpool) { this.cpool = cpool; this.typeIndex = cpool.addUtf8(type.getSignature()); @@ -249,6 +273,11 @@ public AnnotationEntryGen(final ObjectType type, final List isRuntimeVisible = vis; } + /** + * Adds an element name value pair. + * + * @param evp The element value pair generator. + */ public void addElementNameValuePair(final ElementValuePairGen evp) { if (evs == null) { evs = new ArrayList<>(); @@ -260,16 +289,24 @@ private List copyValues(final ElementValuePair[] in, final return Utils.streamOfIfNonNull(in).map(nvp -> new ElementValuePairGen(nvp, cpool, copyPoolEntries)).collect(Collectors.toList()); } + /** + * Dumps this annotation entry to a DataOutputStream. + * + * @param dos The data output stream. + * @throws IOException Thrown if an I/O error occurs. + */ public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(typeIndex); // u2 index of type name in cpool - dos.writeShort(evs.size()); // u2 element_value pair count + dos.writeShort(Args.requireU2(evs.size(), "evs.size()")); // u2 element_value pair count for (final ElementValuePairGen envp : evs) { envp.dump(dos); } } /** - * Retrieve an immutable version of this AnnotationGen + * Retrieves an immutable version of this AnnotationGen. + * + * @return An immutable version of this AnnotationGen. */ public AnnotationEntry getAnnotation() { final AnnotationEntry a = new AnnotationEntry(typeIndex, cpool.getConstantPool(), isRuntimeVisible); @@ -279,15 +316,30 @@ public AnnotationEntry getAnnotation() { return a; } + /** + * Gets the type index. + * + * @return The type index. + */ public int getTypeIndex() { return typeIndex; } + /** + * Gets the type name. + * + * @return The type name. + */ public final String getTypeName() { return getTypeSignature(); // BCELBUG: Should I use this instead? // Utility.signatureToString(getTypeSignature()); } + /** + * Gets the type signature. + * + * @return The type signature. + */ public final String getTypeSignature() { // ConstantClass c = (ConstantClass) cpool.getConstant(typeIndex); final ConstantUtf8 utf8 = (ConstantUtf8) cpool.getConstant(typeIndex/* c.getNameIndex() */); @@ -303,6 +355,11 @@ public List getValues() { return evs; } + /** + * Gets whether this annotation is runtime visible. + * + * @return true if this annotation is runtime visible. + */ public boolean isRuntimeVisible() { return isRuntimeVisible; } @@ -311,6 +368,11 @@ private void isRuntimeVisible(final boolean b) { isRuntimeVisible = b; } + /** + * Returns a short string representation of this annotation. + * + * @return A short string representation of this annotation. + */ public String toShortString() { final StringBuilder s = new StringBuilder(); s.append("@").append(getTypeName()).append("("); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArithmeticInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArithmeticInstruction.java index 752ab1155c75..753bb81f0e0c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArithmeticInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArithmeticInstruction.java @@ -35,14 +35,16 @@ public abstract class ArithmeticInstruction extends Instruction implements Typed } /** - * @param opcode of instruction + * Constructs an ArithmeticInstruction. + * + * @param opcode of instruction. */ protected ArithmeticInstruction(final short opcode) { super(opcode, (short) 1); } /** - * @return type associated with the instruction + * @return type associated with the instruction. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayElementValueGen.java index 59b774a9afc3..cc1b17f46abf 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayElementValueGen.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -28,11 +28,14 @@ import com.sun.org.apache.bcel.internal.classfile.ArrayElementValue; import com.sun.org.apache.bcel.internal.classfile.ElementValue; +import com.sun.org.apache.bcel.internal.util.Args; import jdk.xml.internal.Utils; /** + * Generates array element values in annotations. + * * @since 6.0 - * @LastModified: Sept 2025 + * @LastModified: Oct 2026 */ public class ArrayElementValueGen extends ElementValueGen { // J5TODO: Should we make this an array or a list? A list would be easier to @@ -40,8 +43,11 @@ public class ArrayElementValueGen extends ElementValueGen { private final List evalues; /** - * @param value - * @param cpool + * Constructs an ArrayElementValueGen. + * + * @param value The array element value. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. */ public ArrayElementValueGen(final ArrayElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { super(ARRAY, cpool); @@ -52,11 +58,23 @@ public ArrayElementValueGen(final ArrayElementValue value, final ConstantPoolGen } } + /** + * Constructs an ArrayElementValueGen. + * + * @param cp The constant pool generator. + */ public ArrayElementValueGen(final ConstantPoolGen cp) { super(ARRAY, cp); evalues = new ArrayList<>(); } + /** + * Constructs an ArrayElementValueGen. + * + * @param type The type. + * @param elementValues The element values. + * @param cpool The constant pool generator. + */ public ArrayElementValueGen(final int type, final ElementValue[] elementValues, final ConstantPoolGen cpool) { super(type, cpool); if (type != ARRAY) { @@ -65,6 +83,11 @@ public ArrayElementValueGen(final int type, final ElementValue[] elementValues, this.evalues = Utils.streamOfIfNonNull(elementValues).map(e -> copy(e, cpool, true)).collect(Collectors.toList()); } + /** + * Adds an element. + * + * @param gen The element value generator. + */ public void addElement(final ElementValueGen gen) { evalues.add(gen); } @@ -72,14 +95,16 @@ public void addElement(final ElementValueGen gen) { @Override public void dump(final DataOutputStream dos) throws IOException { dos.writeByte(super.getElementValueType()); // u1 type of value (ARRAY == '[') - dos.writeShort(evalues.size()); + dos.writeShort(Args.requireU2(evalues.size(), "evalues.size()")); for (final ElementValueGen element : evalues) { element.dump(dos); } } /** - * Return immutable variant of this ArrayElementValueGen + * Return immutable variant of this ArrayElementValueGen. + * + * @return immutable variant of this ArrayElementValueGen. */ @Override public ElementValue getElementValue() { @@ -91,10 +116,20 @@ public ElementValue getElementValue() { return new ArrayElementValue(super.getElementValueType(), immutableData, getConstantPool().getConstantPool()); } + /** + * Gets the element values. + * + * @return The element values. + */ public List getElementValues() { return evalues; } + /** + * Gets the element values size. + * + * @return The element values size. + */ public int getElementValuesSize() { return evalues.size(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayInstruction.java index 538c180712a8..53bd9a58f972 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayInstruction.java @@ -35,7 +35,9 @@ public abstract class ArrayInstruction extends Instruction implements ExceptionT } /** - * @param opcode of instruction + * Constructs an ArrayInstruction. + * + * @param opcode of instruction. */ protected ArrayInstruction(final short opcode) { super(opcode, (short) 1); @@ -47,7 +49,7 @@ public Class[] getExceptions() { } /** - * @return type associated with the instruction + * @return type associated with the instruction. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayType.java index 78a676e875ed..7d6c03fcd3f3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ArrayType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -24,7 +24,7 @@ /** * Denotes array type, such as int[][] * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class ArrayType extends ReferenceType { @@ -32,20 +32,20 @@ public final class ArrayType extends ReferenceType { private final Type basicType; /** - * Convenience constructor for array type, e.g. int[] + * Convenience constructor for array type, for example int[] * - * @param type array type, e.g. T_INT - * @param dimensions array dimensions + * @param type array type, for example T_INT. + * @param dimensions array dimensions. */ public ArrayType(final byte type, final int dimensions) { this(BasicType.getType(type), dimensions); } /** - * Convenience constructor for reference array type, e.g. Object[] + * Convenience constructor for reference array type, for example Object[] * - * @param className complete name of class ({@link String}, for example) - * @param dimensions array dimensions + * @param className complete name of class ({@link String}, for example). + * @param dimensions array dimensions. */ public ArrayType(final String className, final int dimensions) { this(ObjectType.getInstance(className), dimensions); @@ -54,8 +54,8 @@ public ArrayType(final String className, final int dimensions) { /** * Constructor for array of given type * - * @param type type of array (may be an array itself) - * @param dimensions array dimensions + * @param type type of array (may be an array itself). + * @param dimensions array dimensions. */ @SuppressWarnings("deprecation") //signature public ArrayType(final Type type, final int dimensions) { @@ -97,7 +97,9 @@ public boolean equals(final Object type) { } /** - * @return basic type of array, i.e., for int[][][] the basic type is int + * Gets the basic type of array, that is, for {@code int[][][]} the basic type is int. + * + * @return basic type of array, that is, for {@code int[][][]} the basic type is int. */ public Type getBasicType() { return basicType; @@ -116,14 +118,18 @@ public String getClassName() { } /** - * @return number of dimensions of array + * Gets the number of dimensions of array. + * + * @return number of dimensions of array. */ public int getDimensions() { return dimensions; } /** - * @return element type of array, i.e., for int[][][] the element type is int[][] + * Gets the element type of array, that is, for {@code int[][][]} the element type is {@code int[][]}. + * + * @return element type of array, that is, for {@code int[][][]} the element type is {@code int[][]}. */ public Type getElementType() { if (dimensions == 1) { @@ -133,10 +139,21 @@ public Type getElementType() { } /** - * @return a hash code value for the object. + * @return A hash code value for the object. */ @Override public int hashCode() { return basicType.hashCode() ^ dimensions; } + + /** + * Tests whether the given type is the element type of this array type, that is, for {@code int[][][]} the element type is {@code int[][]}. + * + * @param type the type to test. + * @return true if the given type is the element type of this array type, that is, for {@code int[][][]} the element type is {@code int[][]}. + * @since 6.13.0 + */ + public boolean isElementType(final Type type) { + return getElementType().equals(type); + } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BALOAD.java index dc14c3fcdb1f..f255e98d60d9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BALOAD.java @@ -23,9 +23,9 @@ /** * BALOAD - Load byte or boolean from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value
- * 
+ *
*/ public class BALOAD extends ArrayInstruction implements StackProducer { @@ -38,9 +38,9 @@ public BALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BASTORE.java index da73a504beb3..ccb516dbb003 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BASTORE.java @@ -23,9 +23,9 @@ /** * BASTORE - Store into byte or boolean array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class BASTORE extends ArrayInstruction implements StackConsumer { @@ -38,9 +38,9 @@ public BASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BIPUSH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BIPUSH.java index 264fe1cb54de..e4650ecc0aad 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BIPUSH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BIPUSH.java @@ -27,9 +27,9 @@ /** * BIPUSH - Push byte on stack * - *
+ * 
  * Stack: ... -> ..., value
- * 
+ *
*/ public class BIPUSH extends Instruction implements ConstantPushInstruction { @@ -42,7 +42,9 @@ public class BIPUSH extends Instruction implements ConstantPushInstruction { } /** - * Push byte on stack + * Push byte on stack. + * + * @param b The byte value to push. */ public BIPUSH(final byte b) { super(com.sun.org.apache.bcel.internal.Const.BIPUSH, (short) 2); @@ -51,9 +53,9 @@ public BIPUSH(final byte b) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -65,7 +67,7 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -74,7 +76,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return Type.BYTE + * @return Type.BYTE. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -87,7 +89,7 @@ public Number getValue() { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -96,7 +98,7 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BREAKPOINT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BREAKPOINT.java index a4fc7be058ff..06fdef674f3e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BREAKPOINT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BREAKPOINT.java @@ -25,15 +25,18 @@ */ public class BREAKPOINT extends Instruction { + /** + * Constructs a BREAKPOINT instruction. + */ public BREAKPOINT() { super(com.sun.org.apache.bcel.internal.Const.BREAKPOINT, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BasicType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BasicType.java index 71bc5491186d..3a07d676e88e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BasicType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BasicType.java @@ -27,6 +27,13 @@ */ public final class BasicType extends Type { + /** + * Gets the BasicType for the given type constant. + * + * @param type The type constant. + * @return The BasicType. + * @since 6.0 + */ // @since 6.0 no longer final public static BasicType getType(final byte type) { switch (type) { @@ -56,7 +63,7 @@ public static BasicType getType(final byte type) { /** * Constructor for basic types such as int, long, 'void' * - * @param type one of T_INT, T_BOOLEAN, ..., T_VOID + * @param type one of T_INT, T_BOOLEAN, ..., T_VOID. * @see Const */ BasicType(final byte type) { @@ -67,7 +74,7 @@ public static BasicType getType(final byte type) { } /** - * @return true if both type objects refer to the same type + * @return true if both type objects refer to the same type. */ @Override public boolean equals(final Object type) { @@ -75,7 +82,7 @@ public boolean equals(final Object type) { } /** - * @return a hash code value for the object. + * @return A hash code value for the object. */ @Override public int hashCode() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchHandle.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchHandle.java index f489f9a76581..fee76732cae0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchHandle.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchHandle.java @@ -56,6 +56,8 @@ public int getPosition() { } /** + * Gets the target of instruction. + * * @return target of instruction. */ public InstructionHandle getTarget() { @@ -83,6 +85,8 @@ void setPosition(final int pos) { /** * Pass new target to instruction. + * + * @param ih The new target. */ public void setTarget(final InstructionHandle ih) { bi.setTarget(ih); @@ -97,6 +101,9 @@ protected int updatePosition(final int offset, final int maxOffset) { /** * Update target of instruction. + * + * @param oldIh The old instruction handle. + * @param newIh The new instruction handle. */ public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { bi.updateTarget(oldIh, newIh); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchInstruction.java index 4aba9a97027a..97db064440e5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/BranchInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,11 +25,11 @@ import com.sun.org.apache.bcel.internal.util.ByteSequence; /** - * Abstract super class for branching instructions like GOTO, IFEQ, etc.. Branch instructions may have a variable - * length, namely GOTO, JSR, LOOKUPSWITCH and TABLESWITCH. + * Abstract super class for branching instructions like GOTO, IFEQ, and so on. Branch instructions may have a variable length, namely GOTO, JSR, LOOKUPSWITCH + * and TABLESWITCH. * * @see InstructionList - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public abstract class BranchInstruction extends Instruction implements InstructionTargeter { @@ -72,8 +72,8 @@ static void notifyTarget(final InstructionHandle oldIh, final InstructionHandle /** * Common super constructor * - * @param opcode Instruction opcode - * @param target instruction to branch to + * @param opcode Instruction opcode. + * @param target instruction to branch to. */ protected BranchInstruction(final short opcode, final InstructionHandle target) { super(opcode, (short) 3); @@ -81,7 +81,7 @@ protected BranchInstruction(final short opcode, final InstructionHandle target) } /** - * @return true, if ih is target of this instruction + * @return true, if ih is target of this instruction. */ @Override public boolean containsTarget(final InstructionHandle ih) { @@ -99,9 +99,9 @@ void dispose() { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -110,18 +110,22 @@ public void dump(final DataOutputStream out) throws IOException { if (!isValidShort(index)) { throw new ClassGenException("Branch target offset too large for short: " + index); } - out.writeShort(index); // May be negative, i.e., point backwards + out.writeShort(index); // May be negative, that is, point backwards } /** - * @return target offset in byte code + * Gets the target offset in byte code. + * + * @return target offset in byte code. */ public final int getIndex() { return index; } /** - * @return the position + * Gets the position. + * + * @return The position. * @since 6.0 */ protected int getPosition() { @@ -129,22 +133,28 @@ protected int getPosition() { } /** - * @return target of branch instruction + * Gets the target of branch instruction. + * + * @return target of branch instruction. */ public InstructionHandle getTarget() { return target; } /** - * @return the offset to this instruction's target + * Gets the offset to this instruction's target. + * + * @return The offset to this instruction's target. */ protected int getTargetOffset() { return getTargetOffset(target); } /** - * @param target branch target - * @return the offset to 'target' relative to this instruction + * Gets the offset to target relative to this instruction. + * + * @param target branch target. + * @return The offset to 'target' relative to this instruction. */ protected int getTargetOffset(final InstructionHandle target) { if (target == null) { @@ -158,9 +168,9 @@ protected int getTargetOffset(final InstructionHandle target) { } /** - * Read needed data (e.g. index) from file. Conversion to a InstructionHandle is done in InstructionList(byte[]). + * Reads needed data (for example index) from file. Conversion to a InstructionHandle is done in InstructionList(byte[]). * - * @param bytes input stream + * @param bytes input stream. * @param wide wide prefix? * @see InstructionList */ @@ -171,7 +181,9 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @param index the index to set + * Sets the index. + * + * @param index The index to set. * @since 6.0 */ protected void setIndex(final int index) { @@ -179,7 +191,9 @@ protected void setIndex(final int index) { } /** - * @param position the position to set + * Sets the position. + * + * @param position The position to set. * @since 6.0 */ protected void setPosition(final int position) { @@ -207,7 +221,7 @@ void setOpcode( final short opcode ) { /** * Set branch target * - * @param target branch target + * @param target branch target. */ public void setTarget(final InstructionHandle target) { notifyTarget(this.target, target, this); @@ -220,8 +234,8 @@ public void setTarget(final InstructionHandle target) { * <position in byte code> <name of opcode> "["<opcode number>"]" "("<length of instruction>")" * "<"<target instruction>">" "@"<branch target offset> * - * @param verbose long/short format switch - * @return mnemonic for instruction + * @param verbose long/short format switch. + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { @@ -254,9 +268,9 @@ public String toString(final boolean verbose) { * length instructions 'setPositions' performs multiple passes over the instruction list to calculate the correct (byte) * positions and offsets by calling this function. * - * @param offset additional offset caused by preceding (variable length) instructions - * @param maxOffset the maximum offset that may be caused by these instructions - * @return additional offset caused by possible change of this instruction's length + * @param offset additional offset caused by preceding (variable length) instructions. + * @param maxOffset The maximum offset that may be caused by these instructions. + * @return additional offset caused by possible change of this instruction's length. */ protected int updatePosition(final int offset, final int maxOffset) { position += offset; @@ -264,8 +278,8 @@ protected int updatePosition(final int offset, final int maxOffset) { } /** - * @param oldIh old target - * @param newIh new target + * @param oldIh old target. + * @param newIh new target. */ @Override public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CALOAD.java index 02cc46df6602..15d6f652cad0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CALOAD.java @@ -24,9 +24,9 @@ /** * CALOAD - Load char from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value
- * 
+ *
*/ public class CALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public CALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CASTORE.java index ca4a4e1fe41b..d9df0c09a0ce 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CASTORE.java @@ -24,9 +24,9 @@ /** * CASTORE - Store into char array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class CASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public CASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CHECKCAST.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CHECKCAST.java index 6983350f646d..df9309739605 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CHECKCAST.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CHECKCAST.java @@ -26,9 +26,9 @@ /** * CHECKCAST - Check whether object is of given type * - *
+ * 
  * Stack: ..., objectref -> ..., objectref
- * 
+ *
*/ public class CHECKCAST extends CPInstruction implements LoadClass, ExceptionThrower, StackProducer, StackConsumer { @@ -41,7 +41,7 @@ public class CHECKCAST extends CPInstruction implements LoadClass, ExceptionThro /** * Check whether object is of given type * - * @param index index to class in constant pool + * @param index index to class in constant pool. */ public CHECKCAST(final int index) { super(com.sun.org.apache.bcel.internal.Const.CHECKCAST, index); @@ -49,9 +49,9 @@ public CHECKCAST(final int index) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -65,7 +65,7 @@ public void accept(final Visitor v) { } /** - * @return exceptions this instruction may cause + * @return exceptions this instruction may cause. */ @Override public Class[] getExceptions() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CPInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CPInstruction.java index ff45e5cde93e..1914192ead37 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CPInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CPInstruction.java @@ -22,6 +22,7 @@ import java.io.DataOutputStream; import java.io.IOException; +import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.classfile.Constant; import com.sun.org.apache.bcel.internal.classfile.ConstantClass; import com.sun.org.apache.bcel.internal.classfile.ConstantPool; @@ -34,8 +35,6 @@ * @see ConstantPoolGen * @see LDC * @see INVOKEVIRTUAL - * - * @LastModified: Sept 2025 */ public abstract class CPInstruction extends Instruction implements TypedInstruction, IndexedInstruction { @@ -52,7 +51,10 @@ public abstract class CPInstruction extends Instruction implements TypedInstruct } /** - * @param index to constant pool + * Constructs a CPInstruction. + * + * @param opcode The opcode. + * @param index to constant pool. */ protected CPInstruction(final short opcode, final int index) { super(opcode, (short) 3); @@ -60,9 +62,9 @@ protected CPInstruction(final short opcode, final int index) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -84,7 +86,7 @@ public final int getIndex() { @Override public Type getType(final ConstantPoolGen cpg) { final ConstantPool cp = cpg.getConstantPool(); - String name = cp.getConstantString(index, com.sun.org.apache.bcel.internal.Const.CONSTANT_Class); + String name = cp.getConstantString(index, Const.CONSTANT_Class); if (!name.startsWith("[")) { name = "L" + name + ";"; } @@ -92,10 +94,10 @@ public Type getType(final ConstantPoolGen cpg) { } /** - * Read needed data (i.e., index) from file. + * Reads needed data (that is, index) from file. * - * @param bytes input stream - * @param wide wide prefix? + * @param bytes input stream. + * @param wide wide prefix?. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -107,11 +109,12 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws * Sets the index to constant pool. * * @param index in constant pool. + * @throws ClassGenException Thrown if index is out of bounds. */ @Override public void setIndex(final int index) { // TODO could be package-protected? - if (index < 0) { - throw new ClassGenException("Negative index value: " + index); + if (!isNonNegativeUShort(index)) { + throw new ClassGenException("Illegal index: " + index); } this.index = index; } @@ -122,8 +125,8 @@ public void setIndex(final int index) { // TODO could be package-protected? * <name of opcode> "["<opcode number>"]" "("<length of instruction>")" "<"< constant pool * index>">" * - * @param verbose long/short format switch - * @return mnemonic for instruction + * @param verbose long/short format switch. + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { @@ -131,7 +134,7 @@ public String toString(final boolean verbose) { } /** - * @return mnemonic for instruction with symbolic references resolved + * @return mnemonic for instruction with symbolic references resolved. */ @Override public String toString(final ConstantPool cp) { @@ -140,6 +143,6 @@ public String toString(final ConstantPool cp) { if (c instanceof ConstantClass) { str = Utility.packageToPath(str); } - return com.sun.org.apache.bcel.internal.Const.getOpcodeName(super.getOpcode()) + " " + str; + return Const.getOpcodeName(super.getOpcode()) + " " + str; } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassElementValueGen.java index 8e024eebaa48..7c58a05e578e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassElementValueGen.java @@ -29,6 +29,8 @@ import com.sun.org.apache.bcel.internal.classfile.ElementValue; /** + * Generates class element values in annotations. + * * @since 6.0 */ public class ClassElementValueGen extends ElementValueGen { @@ -37,6 +39,13 @@ public class ClassElementValueGen extends ElementValueGen { // For 'class' this points to the class entry in the cpool private final int idx; + /** + * Constructs a ClassElementValueGen. + * + * @param value The class element value. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. + */ public ClassElementValueGen(final ClassElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { super(CLASS, cpool); if (copyPoolEntries) { @@ -47,11 +56,23 @@ public ClassElementValueGen(final ClassElementValue value, final ConstantPoolGen } } + /** + * Constructs a ClassElementValueGen. + * + * @param typeIdx The type index. + * @param cpool The constant pool generator. + */ protected ClassElementValueGen(final int typeIdx, final ConstantPoolGen cpool) { super(CLASS, cpool); this.idx = typeIdx; } + /** + * Constructs a ClassElementValueGen. + * + * @param t The object type. + * @param cpool The constant pool generator. + */ public ClassElementValueGen(final ObjectType t, final ConstantPoolGen cpool) { super(CLASS, cpool); // this.idx = cpool.addClass(t); @@ -64,6 +85,11 @@ public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(idx); } + /** + * Gets the class string. + * + * @return The class string. + */ public String getClassString() { final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(idx); return cu8.getBytes(); @@ -74,13 +100,20 @@ public String getClassString() { } /** - * Return immutable variant of this ClassElementValueGen + * Return immutable variant of this ClassElementValueGen. + * + * @return immutable variant of this ClassElementValueGen. */ @Override public ElementValue getElementValue() { return new ClassElementValue(super.getElementValueType(), idx, getConstantPool().getConstantPool()); } + /** + * Gets the index. + * + * @return The index. + */ public int getIndex() { return idx; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGen.java index debf930fe90b..a34387c8f1b0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGen.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -43,7 +43,7 @@ * Template class for building up a java class. May be initialized with an existing Java class (file). * * @see JavaClass - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class ClassGen extends AccessFlags implements Cloneable { @@ -61,14 +61,18 @@ public int hashCode(final ClassGen o) { }; /** - * @return Comparison strategy object + * Gets the comparison strategy object. + * + * @return Comparison strategy object. */ public static BCELComparator getComparator() { return bcelComparator; } /** - * @param comparator Comparison strategy object + * Sets the comparison strategy object. + * + * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { bcelComparator = comparator; @@ -100,7 +104,7 @@ public static void setComparator(final BCELComparator comparator) { /** * Constructs a new instance from an existing class. * - * @param clazz JavaClass object (e.g. read from file) + * @param clazz JavaClass object (for example read from file). */ public ClassGen(final JavaClass clazz) { super(clazz.getAccessFlags()); @@ -140,11 +144,11 @@ public ClassGen(final JavaClass clazz) { /** * Convenience constructor to set up some important values initially. * - * @param className fully qualified class name - * @param superClassName fully qualified superclass name - * @param fileName source file name - * @param accessFlags access qualifiers - * @param interfaces implemented interfaces + * @param className fully qualified class name. + * @param superClassName fully qualified superclass name. + * @param fileName source file name. + * @param accessFlags access qualifiers. + * @param interfaces implemented interfaces. */ public ClassGen(final String className, final String superClassName, final String fileName, final int accessFlags, final String[] interfaces) { this(className, superClassName, fileName, accessFlags, interfaces, new ConstantPoolGen()); @@ -153,12 +157,12 @@ public ClassGen(final String className, final String superClassName, final Strin /** * Convenience constructor to set up some important values initially. * - * @param className fully qualified class name - * @param superClassName fully qualified superclass name - * @param fileName source file name - * @param accessFlags access qualifiers - * @param interfaces implemented interfaces - * @param cp constant pool to use + * @param className fully qualified class name. + * @param superClassName fully qualified superclass name. + * @param fileName source file name. + * @param accessFlags access qualifiers. + * @param interfaces implemented interfaces. + * @param cp constant pool to use. */ public ClassGen(final String className, final String superClassName, final String fileName, final int accessFlags, final String[] interfaces, final ConstantPoolGen cp) { @@ -178,6 +182,11 @@ public ClassGen(final String className, final String superClassName, final Strin } } + /** + * Adds an annotation entry to this class. + * + * @param a The annotation entry to add. + */ public void addAnnotationEntry(final AnnotationEntryGen a) { annotationList.add(a); } @@ -185,7 +194,7 @@ public void addAnnotationEntry(final AnnotationEntryGen a) { /** * Add an attribute to this class. * - * @param a attribute to add + * @param a attribute to add. */ public void addAttribute(final Attribute a) { attributeList.add(a); @@ -196,7 +205,7 @@ public void addAttribute(final Attribute a) { * * Add an empty constructor to this class that does nothing but calling super(). * - * @param accessFlags rights for constructor + * @param accessFlags rights for constructor. */ public void addEmptyConstructor(final int accessFlags) { final InstructionList il = new InstructionList(); @@ -211,16 +220,16 @@ public void addEmptyConstructor(final int accessFlags) { /** * Add a field to this class. * - * @param f field to add + * @param f field to add. */ public void addField(final Field f) { fieldList.add(f); } /** - * Add an interface to this class, i.e., this class has to implement it. + * Add an interface to this class, that is, this class has to implement it. * - * @param name interface to implement (fully qualified class name) + * @param name interface to implement (fully qualified class name). */ public void addInterface(final String name) { interfaceList.add(name); @@ -229,7 +238,7 @@ public void addInterface(final String name) { /** * Add a method to this class. * - * @param m method to add + * @param m method to add. */ public void addMethod(final Method m) { methodList.add(m); @@ -237,6 +246,8 @@ public void addMethod(final Method m) { /** * Add observer for this object. + * + * @param o The observer. */ public void addObserver(final ClassObserver o) { if (observers == null) { @@ -254,12 +265,21 @@ public Object clone() { } } + /** + * Checks if this class contains the given field. + * + * @param f The field to check. + * @return true if this class contains the field. + */ public boolean containsField(final Field f) { return fieldList.contains(f); } /** - * @return field object with given name, or null + * Gets the field object with given name, or null. + * + * @param name The field name. + * @return field object with given name, or null. */ public Field containsField(final String name) { for (final Field f : fieldList) { @@ -271,7 +291,11 @@ public Field containsField(final String name) { } /** - * @return method object with given name and signature, or null + * Gets the method object with given name and signature, or null. + * + * @param name The method name. + * @param signature The method signature. + * @return method object with given name and signature, or null. */ public Method containsMethod(final String name, final String signature) { for (final Method m : methodList) { @@ -293,39 +317,84 @@ public boolean equals(final Object obj) { return obj instanceof ClassGen && bcelComparator.equals(this, (ClassGen) obj); } + /** + * Gets the annotation entries. + * + * @return The annotation entries. + */ // J5TODO: Should we make calling unpackAnnotations() lazy and put it in here? public AnnotationEntryGen[] getAnnotationEntries() { return annotationList.toArray(AnnotationEntryGen.EMPTY_ARRAY); } + /** + * Gets the attributes. + * + * @return The attributes. + */ public Attribute[] getAttributes() { return attributeList.toArray(Attribute.EMPTY_ARRAY); } + /** + * Gets the class name. + * + * @return The class name. + */ public String getClassName() { return className; } + /** + * Gets the class name index. + * + * @return The class name index. + */ public int getClassNameIndex() { return classNameIndex; } + /** + * Gets the constant pool. + * + * @return The constant pool. + */ public ConstantPoolGen getConstantPool() { return cp; } + /** + * Gets the fields. + * + * @return The fields. + */ public Field[] getFields() { return fieldList.toArray(Field.EMPTY_ARRAY); } + /** + * Gets the file name. + * + * @return The file name. + */ public String getFileName() { return fileName; } + /** + * Gets the interface names. + * + * @return The interface names. + */ public String[] getInterfaceNames() { return interfaceList.toArray(Const.EMPTY_STRING_ARRAY); } + /** + * Gets the interfaces. + * + * @return The interfaces. + */ public int[] getInterfaces() { final int size = interfaceList.size(); final int[] interfaces = new int[size]; @@ -334,7 +403,9 @@ public int[] getInterfaces() { } /** - * @return the (finally) built up Java class object. + * Gets the (finally) built up Java class object. + * + * @return The (finally) built up Java class object. */ public JavaClass getJavaClass() { final int[] interfaces = getInterfaces(); @@ -357,31 +428,56 @@ public JavaClass getJavaClass() { } /** - * @return major version number of class file + * Gets major version number of class file. + * + * @return major version number of class file. */ public int getMajor() { return major; } + /** + * Gets the method at the given position. + * + * @param pos The position. + * @return The method at the given position. + */ public Method getMethodAt(final int pos) { return methodList.get(pos); } + /** + * Gets the methods. + * + * @return The methods. + */ public Method[] getMethods() { return methodList.toArray(Method.EMPTY_ARRAY); } /** - * @return minor version number of class file + * Gets minor version number of class file. + * + * @return minor version number of class file. */ public int getMinor() { return minor; } + /** + * Gets the superclass name. + * + * @return The superclass name. + */ public String getSuperclassName() { return superClassName; } + /** + * Gets the superclass name index. + * + * @return The superclass name index. + */ public int getSuperclassNameIndex() { return superclassNameIndex; } @@ -399,7 +495,7 @@ public int hashCode() { /** * Remove an attribute from this class. * - * @param a attribute to remove + * @param a attribute to remove. */ public void removeAttribute(final Attribute a) { attributeList.remove(a); @@ -408,7 +504,7 @@ public void removeAttribute(final Attribute a) { /** * Remove a field to this class. * - * @param f field to remove + * @param f field to remove. */ public void removeField(final Field f) { fieldList.remove(f); @@ -417,7 +513,7 @@ public void removeField(final Field f) { /** * Remove an interface from this class. * - * @param name interface to remove (fully qualified name) + * @param name interface to remove (fully qualified name). */ public void removeInterface(final String name) { interfaceList.remove(name); @@ -426,7 +522,7 @@ public void removeInterface(final String name) { /** * Remove a method from this class. * - * @param m method to remove + * @param m method to remove. */ public void removeMethod(final Method m) { methodList.remove(m); @@ -434,6 +530,8 @@ public void removeMethod(final Method m) { /** * Remove observer for this object. + * + * @param o The observer to remove. */ public void removeObserver(final ClassObserver o) { if (observers != null) { @@ -443,6 +541,9 @@ public void removeObserver(final ClassObserver o) { /** * Replace given field with new one. If the old one does not exist add the new_ field to the class anyway. + * + * @param old The old field. + * @param newField The new field. */ public void replaceField(final Field old, final Field newField) { if (newField == null) { @@ -458,6 +559,9 @@ public void replaceField(final Field old, final Field newField) { /** * Replace given method with new one. If the old one does not exist add the newMethod method to the class anyway. + * + * @param old The old method. + * @param newMethod The new method. */ public void replaceMethod(final Method old, final Method newMethod) { if (newMethod == null) { @@ -471,33 +575,59 @@ public void replaceMethod(final Method old, final Method newMethod) { } } + /** + * Sets the class name. + * + * @param name The class name. + */ public void setClassName(final String name) { className = Utility.pathToPackage(name); classNameIndex = cp.addClass(name); } + /** + * Sets the class name index. + * + * @param classNameIndex The class name index. + */ public void setClassNameIndex(final int classNameIndex) { this.classNameIndex = classNameIndex; this.className = Utility.pathToPackage(cp.getConstantPool().getConstantString(classNameIndex, Const.CONSTANT_Class)); } + /** + * Sets the constant pool. + * + * @param constantPool The constant pool. + */ public void setConstantPool(final ConstantPoolGen constantPool) { cp = constantPool; } /** - * Sets major version number of class file, default value is 45 (JDK 1.1) + * Sets major version number of class file, default value is 45 (JDK 1.1). * - * @param major major version number + * @param major major version number. */ public void setMajor(final int major) { // TODO could be package-protected - only called by test code this.major = major; } + /** + * Sets the method at the given position. + * + * @param method The method. + * @param pos The position. + */ public void setMethodAt(final Method method, final int pos) { methodList.set(pos, method); } + /** + * Sets the methods. + * + * @param methods The methods. + */ public void setMethods(final Method[] methods) { methodList.clear(); if (methods != null) { @@ -506,19 +636,29 @@ public void setMethods(final Method[] methods) { } /** - * Sets minor version number of class file, default value is 3 (JDK 1.1) + * Sets minor version number of class file, default value is 3 (JDK 1.1). * - * @param minor minor version number + * @param minor minor version number. */ public void setMinor(final int minor) { // TODO could be package-protected - only called by test code this.minor = minor; } + /** + * Sets the superclass name. + * + * @param name The superclass name. + */ public void setSuperclassName(final String name) { superClassName = Utility.pathToPackage(name); superclassNameIndex = cp.addClass(name); } + /** + * Sets the superclass name index. + * + * @param superclassNameIndex The superclass name index. + */ public void setSuperclassNameIndex(final int superclassNameIndex) { this.superclassNameIndex = superclassNameIndex; superClassName = Utility.pathToPackage(cp.getConstantPool().getConstantString(superclassNameIndex, Const.CONSTANT_Class)); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGenException.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGenException.java index 8dfbde810de1..21f02504e4b5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGenException.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassGenException.java @@ -28,13 +28,27 @@ public class ClassGenException extends RuntimeException { private static final long serialVersionUID = 7247369755051242791L; + /** + * Constructs a new ClassGenException. + */ public ClassGenException() { } + /** + * Constructs a new ClassGenException with the specified message. + * + * @param s The error message. + */ public ClassGenException(final String s) { super(s); } + /** + * Constructs a new ClassGenException with the specified message and cause. + * + * @param s The error message. + * @param initCause The cause. + */ public ClassGenException(final String s, final Throwable initCause) { super(s, initCause); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassObserver.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassObserver.java index 64f2c44c41d1..eac9795e22a7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassObserver.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ClassObserver.java @@ -27,5 +27,10 @@ */ public interface ClassObserver { + /** + * Notifies the observer that the ClassGen object has changed. + * + * @param clazz The ClassGen object that changed. + */ void notify(ClassGen clazz); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CodeExceptionGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CodeExceptionGen.java index 2518131cceea..f38cc991805c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CodeExceptionGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CodeExceptionGen.java @@ -23,11 +23,11 @@ import com.sun.org.apache.bcel.internal.classfile.CodeException; /** - * This class represents an exception handler, i.e., specifies the region where a handler is active and an instruction + * This class represents an exception handler, that is, specifies the region where a handler is active and an instruction * where the actual handling is done. pool as parameters. Opposed to the JVM specification the end of the handled region - * is set to be inclusive, i.e. all instructions between start and end are protected including the start and end + * is set to be inclusive, for example all instructions between start and end are protected including the start and end * instructions (handles) themselves. The end of the region is automatically mapped to be exclusive when calling - * getCodeException(), i.e., there is no difference semantically. + * getCodeException(), that is, there is no difference semantically. * * @see MethodGen * @see CodeException @@ -43,13 +43,13 @@ public final class CodeExceptionGen implements InstructionTargeter, Cloneable { private ObjectType catchType; /** - * Add an exception handler, i.e., specify region where a handler is active and an instruction where the actual handling + * Add an exception handler, that is, specify region where a handler is active and an instruction where the actual handling * is done. * - * @param startPc Start of handled region (inclusive) - * @param endPc End of handled region (inclusive) - * @param handlerPc Where handling is done - * @param catchType which exception is handled, null for ANY + * @param startPc Start of handled region (inclusive). + * @param endPc End of handled region (inclusive). + * @param handlerPc Where handling is done. + * @param catchType which exception is handled, null for ANY. */ public CodeExceptionGen(final InstructionHandle startPc, final InstructionHandle endPc, final InstructionHandle handlerPc, final ObjectType catchType) { setStartPC(startPc); @@ -68,25 +68,30 @@ public Object clone() { } /** - * @return true, if ih is target of this handler + * @return true, if ih is target of this handler. */ @Override public boolean containsTarget(final InstructionHandle ih) { return startPc == ih || endPc == ih || handlerPc == ih; } - /** Gets the type of the Exception to catch, 'null' for ANY. */ + /** + * Gets the type of the Exception to catch, 'null' for ANY. + * + * @return The type of the Exception to catch, 'null' for ANY. + */ public ObjectType getCatchType() { return catchType; } /** - * Gets CodeException object.
+ * Gets CodeException object. * * This relies on that the instruction list has already been dumped to byte code or that the 'setPositions' methods * has been called for the instruction list. * - * @param cp constant pool + * @param cp constant pool. + * @return The CodeException object. */ public CodeException getCodeException(final ConstantPoolGen cp) { return new CodeException(startPc.getPosition(), endPc.getPosition() + endPc.getInstruction().getLength(), handlerPc.getPosition(), @@ -94,55 +99,65 @@ public CodeException getCodeException(final ConstantPoolGen cp) { } /** - * @return end of handled region (inclusive) + * Gets the end of handled region (inclusive). + * + * @return end of handled region (inclusive). */ public InstructionHandle getEndPC() { return endPc; } /** - * @return start of handler + * Gets the start of handler. + * + * @return start of handler. */ public InstructionHandle getHandlerPC() { return handlerPc; } /** - * @return start of handled region (inclusive) + * Gets the start of handled region (inclusive). + * + * @return start of handled region (inclusive). */ public InstructionHandle getStartPC() { return startPc; } - /** Sets the type of the Exception to catch. Set 'null' for ANY. */ + /** + * Sets the type of the Exception to catch. Set 'null' for ANY. + * + * @param catchType The type of the Exception to catch. + */ public void setCatchType(final ObjectType catchType) { this.catchType = catchType; } - /* - * Sets end of handler + /** + * Sets end of handler. * - * @param endPc End of handled region (inclusive) + * @param endPc End of handled region (inclusive). */ public void setEndPC(final InstructionHandle endPc) { // TODO could be package-protected? BranchInstruction.notifyTarget(this.endPc, endPc, this); this.endPc = endPc; } - /* - * Sets handler code + /** + * Sets handler code. * - * @param handlerPc Start of handler + * @param handlerPc Start of handler. */ public void setHandlerPC(final InstructionHandle handlerPc) { // TODO could be package-protected? BranchInstruction.notifyTarget(this.handlerPc, handlerPc, this); this.handlerPc = handlerPc; } - /* - * Sets start of handler + /** + * Sets start of handler. * - * @param startPc Start of handled region (inclusive) + * @param startPc Start of handled region (inclusive). */ public void setStartPC(final InstructionHandle startPc) { // TODO could be package-protected? BranchInstruction.notifyTarget(this.startPc, startPc, this); @@ -155,8 +170,8 @@ public String toString() { } /** - * @param oldIh old target, either start or end - * @param newIh new target + * @param oldIh old target, either start or end. + * @param newIh new target. */ @Override public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CompoundInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CompoundInstruction.java index 40fc722d0d1d..117a2447d51e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CompoundInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/CompoundInstruction.java @@ -34,5 +34,10 @@ */ public interface CompoundInstruction { + /** + * Gets the instruction list. + * + * @return The instruction list. + */ InstructionList getInstructionList(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPoolGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPoolGen.java index b07fef8f9016..9c10ece38da5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPoolGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPoolGen.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -43,14 +43,13 @@ import com.sun.org.apache.bcel.internal.classfile.Utility; /** - * This class is used to build up a constant pool. The user adds constants via 'addXXX' methods, 'addString', - * 'addClass', etc.. These methods return an index into the constant pool. Finally, 'getFinalConstantPool()' returns the - * constant pool built up. Intermediate versions of the constant pool can be obtained with 'getConstantPool()'. A - * constant pool has capacity for Constants.MAX_SHORT entries. Note that the first (0) is used by the JVM and that - * Double and Long constants need two slots. + * This class is used to build up a constant pool. The user adds constants via 'addXXX' methods, 'addString', 'addClass', and so on. These methods return an + * index into the constant pool. Finally, 'getFinalConstantPool()' returns the constant pool built up. Intermediate versions of the constant pool can be + * obtained with 'getConstantPool()'. A constant pool has capacity for Constants.MAX_SHORT entries. Note that the first (0) is used by the JVM and that Double + * and Long constants need two slots. * * @see Constant - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public class ConstantPoolGen { @@ -62,7 +61,22 @@ public class ConstantPoolGen { private static final String FIELDREF_DELIM = "&"; - private static final String NAT_DELIM = "%"; // Name and Type + /** + * Builds a lookup key that stays collision-free even when the parts contain the ASCII characters used as + * delimiters above. Class, member and signature names read from a class file may legally contain those characters + * (the JVMS only forbids {@code . ; [ /} and, for members, {@code < >}), so each part is prefixed with its length + * to keep distinct triples distinct. + * + * @param parts The key parts. + * @return A collision-free key. + */ + private static String toKey(final String... parts) { + final StringBuilder buf = new StringBuilder(); + for (final String part : parts) { + buf.append(part.length()).append(':').append(part); + } + return buf.toString(); + } /** * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter @@ -103,7 +117,7 @@ public ConstantPoolGen() { /** * Constructs a new instance with the given array of constants. * - * @param cs array of given constants, new ones will be appended + * @param cs array of given constants, new ones will be appended. */ public ConstantPoolGen(final Constant[] cs) { /* @@ -149,13 +163,7 @@ public ConstantPoolGen(final Constant[] cs) { final ConstantNameAndType n = (ConstantNameAndType) c; final ConstantUtf8 u8NameIdx = (ConstantUtf8) constants[n.getNameIndex()]; final ConstantUtf8 u8SigIdx = (ConstantUtf8) constants[n.getSignatureIndex()]; - - sb.append(u8NameIdx.getBytes()); - sb.append(NAT_DELIM); - sb.append(u8SigIdx.getBytes()); - final String key = sb.toString(); - sb.delete(0, sb.length()); - + final String key = toKey(u8NameIdx.getBytes(), u8SigIdx.getBytes()); if (!natTable.containsKey(key)) { natTable.put(key, Integer.valueOf(i)); } @@ -167,7 +175,7 @@ public ConstantPoolGen(final Constant[] cs) { } } else if (c instanceof ConstantCP) { final ConstantCP m = (ConstantCP) c; - String className; + final String className; ConstantUtf8 u8; if (c instanceof ConstantInvokeDynamic) { @@ -186,22 +194,14 @@ public ConstantPoolGen(final Constant[] cs) { u8 = (ConstantUtf8) constants[n.getSignatureIndex()]; final String signature = u8.getBytes(); - // Since name cannot begin with digit, we can use METHODREF_DELIM without fear of duplicates + // Distinguishes the three kinds of reference that share cpTable. String delim = METHODREF_DELIM; if (c instanceof ConstantInterfaceMethodref) { delim = IMETHODREF_DELIM; } else if (c instanceof ConstantFieldref) { delim = FIELDREF_DELIM; } - - sb.append(className); - sb.append(delim); - sb.append(methodName); - sb.append(delim); - sb.append(signature); - final String key = sb.toString(); - sb.delete(0, sb.length()); - + final String key = toKey(delim, className, methodName, signature); if (!cpTable.containsKey(key)) { cpTable.put(key, Integer.valueOf(i)); } @@ -234,18 +234,17 @@ public ConstantPoolGen(final Constant[] cs) { /** * Constructs a new instance with the given constant pool. * - * @param cp the constant pool. + * @param cp The constant pool. */ public ConstantPoolGen(final ConstantPool cp) { this(cp.getConstantPool()); } /** - * Add a reference to an array class (e.g. String[][]) as needed by MULTIANEWARRAY instruction, e.g. to the - * ConstantPool. + * Add a reference to an array class (for example, String[][]) as needed by MULTIANEWARRAY instruction, for example, to the ConstantPool. * - * @param type type of array class - * @return index of entry + * @param type type of array class. + * @return index of entry. */ public int addArrayClass(final ArrayType type) { return addClass_(type.getSignature()); @@ -254,8 +253,8 @@ public int addArrayClass(final ArrayType type) { /** * Add a new Class reference to the ConstantPool for a given type. * - * @param type Class to add - * @return index of entry + * @param type Class to add. + * @return index of entry. */ public int addClass(final ObjectType type) { return addClass(type.getClassName()); @@ -264,8 +263,8 @@ public int addClass(final ObjectType type) { /** * Add a new Class reference to the ConstantPool, if it is not already in there. * - * @param str Class to add - * @return index of entry + * @param str Class to add. + * @return index of entry. */ public int addClass(final String str) { return addClass_(Utility.packageToPath(str)); @@ -288,7 +287,7 @@ private int addClass_(final String clazz) { * * @param constant The constant to add. * @param cpGen Source pool. - * @return index of entry + * @return index of entry. */ public int addConstant(final Constant constant, final ConstantPoolGen cpGen) { final Constant[] constants = cpGen.getConstantPool().getConstantPool(); @@ -350,8 +349,8 @@ public int addConstant(final Constant constant, final ConstantPoolGen cpGen) { /** * Add a new double constant to the ConstantPool, if it is not already in there. * - * @param n Double number to add - * @return index of entry + * @param n Double number to add. + * @return index of entry. */ public int addDouble(final double n) { int ret; @@ -368,10 +367,10 @@ public int addDouble(final double n) { /** * Add a new Fieldref constant to the ConstantPool, if it is not already in there. * - * @param className class name string to add - * @param fieldName field name string to add - * @param signature signature string to add - * @return index of entry + * @param className class name string to add. + * @param fieldName field name string to add. + * @param signature signature string to add. + * @return index of entry. */ public int addFieldref(final String className, final String fieldName, final String signature) { final int cpRet; @@ -383,14 +382,14 @@ public int addFieldref(final String className, final String fieldName, final Str final int nameAndTypeIndex = addNameAndType(fieldName, signature); final int ret = index; constants[index++] = new ConstantFieldref(classIndex, nameAndTypeIndex); - return computeIfAbsent(cpTable, className + FIELDREF_DELIM + fieldName + FIELDREF_DELIM + signature, ret); + return computeIfAbsent(cpTable, toKey(FIELDREF_DELIM, className, fieldName, signature), ret); } /** * Add a new Float constant to the ConstantPool, if it is not already in there. * - * @param n Float number to add - * @return index of entry + * @param n Float number to add. + * @return index of entry. */ public int addFloat(final float n) { int ret; @@ -406,8 +405,8 @@ public int addFloat(final float n) { /** * Add a new Integer constant to the ConstantPool, if it is not already in there. * - * @param n integer number to add - * @return index of entry + * @param n integer number to add. + * @return index of entry. */ public int addInteger(final int n) { int ret; @@ -420,6 +419,12 @@ public int addInteger(final int n) { return ret; } + /** + * Adds a new InterfaceMethodref constant to the ConstantPool. + * + * @param method The method to add. + * @return index of entry. + */ public int addInterfaceMethodref(final MethodGen method) { return addInterfaceMethodref(method.getClassName(), method.getName(), method.getSignature()); } @@ -427,10 +432,10 @@ public int addInterfaceMethodref(final MethodGen method) { /** * Add a new InterfaceMethodref constant to the ConstantPool, if it is not already in there. * - * @param className class name string to add - * @param methodName method name string to add - * @param signature signature string to add - * @return index of entry + * @param className class name string to add. + * @param methodName method name string to add. + * @param signature signature string to add. + * @return index of entry. */ public int addInterfaceMethodref(final String className, final String methodName, final String signature) { final int cpRet; @@ -442,14 +447,14 @@ public int addInterfaceMethodref(final String className, final String methodName final int nameAndTypeIndex = addNameAndType(methodName, signature); final int ret = index; constants[index++] = new ConstantInterfaceMethodref(classIndex, nameAndTypeIndex); - return computeIfAbsent(cpTable, className + IMETHODREF_DELIM + methodName + IMETHODREF_DELIM + signature, ret); + return computeIfAbsent(cpTable, toKey(IMETHODREF_DELIM, className, methodName, signature), ret); } /** * Add a new long constant to the ConstantPool, if it is not already in there. * - * @param n Long number to add - * @return index of entry + * @param n Long number to add. + * @return index of entry. */ public int addLong(final long n) { int ret; @@ -462,6 +467,13 @@ public int addLong(final long n) { index += 2; // Wastes one entry according to spec return ret; } + + /** + * Adds a new Methodref constant to the ConstantPool. + * + * @param method The method to add. + * @return index of entry. + */ public int addMethodref(final MethodGen method) { return addMethodref(method.getClassName(), method.getName(), method.getSignature()); } @@ -469,10 +481,10 @@ public int addMethodref(final MethodGen method) { /** * Add a new Methodref constant to the ConstantPool, if it is not already in there. * - * @param className class name string to add - * @param methodName method name string to add - * @param signature method signature string to add - * @return index of entry + * @param className class name string to add. + * @param methodName method name string to add. + * @param signature method signature string to add. + * @return index of entry. */ public int addMethodref(final String className, final String methodName, final String signature) { final int cpRet; @@ -484,15 +496,15 @@ public int addMethodref(final String className, final String methodName, final S final int classIndex = addClass(className); final int ret = index; constants[index++] = new ConstantMethodref(classIndex, nameAndTypeIndex); - return computeIfAbsent(cpTable, className + METHODREF_DELIM + methodName + METHODREF_DELIM + signature, ret); + return computeIfAbsent(cpTable, toKey(METHODREF_DELIM, className, methodName, signature), ret); } /** * Add a new NameAndType constant to the ConstantPool if it is not already in there. * - * @param name Name string to add - * @param signature signature string to add - * @return index of entry + * @param name Name string to add. + * @param signature signature string to add. + * @return index of entry. */ public int addNameAndType(final String name, final String signature) { int ret; @@ -504,14 +516,14 @@ public int addNameAndType(final String name, final String signature) { final int signatureIndex = addUtf8(signature); ret = index; constants[index++] = new ConstantNameAndType(nameIndex, signatureIndex); - return computeIfAbsent(natTable, name + NAT_DELIM + signature, ret); + return computeIfAbsent(natTable, toKey(name, signature), ret); } /** * Add a new String constant to the ConstantPool, if it is not already in there. * - * @param str String to add - * @return index of entry + * @param str String to add. + * @return index of entry. */ public int addString(final String str) { int ret; @@ -529,8 +541,8 @@ public int addString(final String str) { /** * Add a new Utf8 constant to the ConstantPool, if it is not already in there. * - * @param n Utf8 string to add - * @return index of entry + * @param n Utf8 string to add. + * @return index of entry. */ public int addUtf8(final String n) { int ret; @@ -569,22 +581,28 @@ private int computeIfAbsent(final Map map, final String key, fi } /** - * @param i index in constant pool - * @return constant pool entry at index i + * Gets a constant pool entry at the specified index. + * + * @param i index in constant pool. + * @return constant pool entry at index i. */ public Constant getConstant(final int i) { return constants[i]; } /** - * @return intermediate constant pool + * Gets the intermediate constant pool. + * + * @return intermediate constant pool. */ public ConstantPool getConstantPool() { return new ConstantPool(constants); } /** - * @return constant pool with proper length + * Gets the constant pool with proper length. + * + * @return constant pool with proper length. */ public ConstantPool getFinalConstantPool() { return new ConstantPool(Arrays.copyOf(constants, index)); @@ -595,7 +613,9 @@ private int getIndex(final Map map, final String key) { } /** - * @return current size of constant pool + * Gets the current size of constant pool. + * + * @return current size of constant pool. */ public int getSize() { return index; @@ -604,8 +624,8 @@ public int getSize() { /** * Look for ConstantClass in ConstantPool named 'str'. * - * @param str String to search for - * @return index on success, -1 otherwise + * @param str String to search for. + * @return index on success, -1 otherwise. */ public int lookupClass(final String str) { return getIndex(classTable, Utility.packageToPath(str)); @@ -614,8 +634,8 @@ public int lookupClass(final String str) { /** * Look for ConstantDouble in ConstantPool. * - * @param n Double number to look for - * @return index on success, -1 otherwise + * @param n Double number to look for. + * @return index on success, -1 otherwise. */ public int lookupDouble(final double n) { final long bits = Double.doubleToLongBits(n); @@ -633,20 +653,20 @@ public int lookupDouble(final double n) { /** * Look for ConstantFieldref in ConstantPool. * - * @param className Where to find method - * @param fieldName Guess what - * @param signature return and argument types - * @return index on success, -1 otherwise + * @param className Where to find method. + * @param fieldName Guess what. + * @param signature return and argument types. + * @return index on success, -1 otherwise. */ public int lookupFieldref(final String className, final String fieldName, final String signature) { - return getIndex(cpTable, className + FIELDREF_DELIM + fieldName + FIELDREF_DELIM + signature); + return getIndex(cpTable, toKey(FIELDREF_DELIM, className, fieldName, signature)); } /** * Look for ConstantFloat in ConstantPool. * - * @param n Float number to look for - * @return index on success, -1 otherwise + * @param n Float number to look for. + * @return index on success, -1 otherwise. */ public int lookupFloat(final float n) { final int bits = Float.floatToIntBits(n); @@ -664,8 +684,8 @@ public int lookupFloat(final float n) { /** * Look for ConstantInteger in ConstantPool. * - * @param n integer number to look for - * @return index on success, -1 otherwise + * @param n integer number to look for. + * @return index on success, -1 otherwise. */ public int lookupInteger(final int n) { for (int i = 1; i < index; i++) { @@ -679,6 +699,12 @@ public int lookupInteger(final int n) { return -1; } + /** + * Looks up an InterfaceMethodref in the ConstantPool. + * + * @param method The method to look for. + * @return index on success, -1 otherwise. + */ public int lookupInterfaceMethodref(final MethodGen method) { return lookupInterfaceMethodref(method.getClassName(), method.getName(), method.getSignature()); } @@ -686,20 +712,20 @@ public int lookupInterfaceMethodref(final MethodGen method) { /** * Look for ConstantInterfaceMethodref in ConstantPool. * - * @param className Where to find method - * @param methodName Guess what - * @param signature return and argument types - * @return index on success, -1 otherwise + * @param className Where to find method. + * @param methodName Guess what. + * @param signature return and argument types. + * @return index on success, -1 otherwise. */ public int lookupInterfaceMethodref(final String className, final String methodName, final String signature) { - return getIndex(cpTable, className + IMETHODREF_DELIM + methodName + IMETHODREF_DELIM + signature); + return getIndex(cpTable, toKey(IMETHODREF_DELIM, className, methodName, signature)); } /** * Look for ConstantLong in ConstantPool. * - * @param n Long number to look for - * @return index on success, -1 otherwise + * @param n Long number to look for. + * @return index on success, -1 otherwise. */ public int lookupLong(final long n) { for (int i = 1; i < index; i++) { @@ -713,6 +739,12 @@ public int lookupLong(final long n) { return -1; } + /** + * Looks up a Methodref in the ConstantPool. + * + * @param method The method to look for. + * @return index on success, -1 otherwise. + */ public int lookupMethodref(final MethodGen method) { return lookupMethodref(method.getClassName(), method.getName(), method.getSignature()); } @@ -720,31 +752,31 @@ public int lookupMethodref(final MethodGen method) { /** * Look for ConstantMethodref in ConstantPool. * - * @param className Where to find method - * @param methodName Guess what - * @param signature return and argument types - * @return index on success, -1 otherwise + * @param className Where to find method. + * @param methodName Guess what. + * @param signature return and argument types. + * @return index on success, -1 otherwise. */ public int lookupMethodref(final String className, final String methodName, final String signature) { - return getIndex(cpTable, className + METHODREF_DELIM + methodName + METHODREF_DELIM + signature); + return getIndex(cpTable, toKey(METHODREF_DELIM, className, methodName, signature)); } /** * Look for ConstantNameAndType in ConstantPool. * - * @param name of variable/method - * @param signature of variable/method - * @return index on success, -1 otherwise + * @param name of variable/method. + * @param signature of variable/method. + * @return index on success, -1 otherwise. */ public int lookupNameAndType(final String name, final String signature) { - return getIndex(natTable, name + NAT_DELIM + signature); + return getIndex(natTable, toKey(name, signature)); } /** * Look for ConstantString in ConstantPool containing String 'str'. * - * @param str String to search for - * @return index on success, -1 otherwise + * @param str String to search for. + * @return index on success, -1 otherwise. */ public int lookupString(final String str) { return getIndex(stringTable, str); @@ -753,8 +785,8 @@ public int lookupString(final String str) { /** * Look for ConstantUtf8 in ConstantPool. * - * @param n Utf8 string to look for - * @return index on success, -1 otherwise + * @param n Utf8 string to look for. + * @return index on success, -1 otherwise. */ public int lookupUtf8(final String n) { return getIndex(utf8Table, n); @@ -763,8 +795,8 @@ public int lookupUtf8(final String n) { /** * Use with care! * - * @param i index in constant pool - * @param c new constant pool entry at index i + * @param i index in constant pool. + * @param c new constant pool entry at index i. */ public void setConstant(final int i, final Constant c) { constants[i] = c; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPushInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPushInstruction.java index 69114bf46281..e43e2c0d5e25 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPushInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConstantPushInstruction.java @@ -30,5 +30,10 @@ */ public interface ConstantPushInstruction extends PushInstruction, TypedInstruction { + /** + * Gets the value to push onto the stack. + * + * @return The value to push onto the stack. + */ Number getValue(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConversionInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConversionInstruction.java index 7937bbe46bcc..1107b088acb2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConversionInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ConversionInstruction.java @@ -35,14 +35,16 @@ public abstract class ConversionInstruction extends Instruction implements Typed } /** - * @param opcode opcode of instruction + * Constructs a ConversionInstruction. + * + * @param opcode opcode of instruction. */ protected ConversionInstruction(final short opcode) { super(opcode, (short) 1); } /** - * @return type associated with the instruction + * @return type associated with the instruction. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2F.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2F.java index 45ee7158c3c3..cb5a3e867ded 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2F.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2F.java @@ -24,9 +24,9 @@ /** * D2F - Convert double to float * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result
- * 
+ *
*/ public class D2F extends ConversionInstruction { @@ -39,9 +39,9 @@ public D2F() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2I.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2I.java index 343076d71592..76d66f8531e3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2I.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2I.java @@ -24,9 +24,9 @@ /** * D2I - Convert double to int * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result
- * 
+ *
*/ public class D2I extends ConversionInstruction { @@ -39,9 +39,9 @@ public D2I() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2L.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2L.java index 0a8b09c1d935..cc37c7002326 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2L.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/D2L.java @@ -24,9 +24,9 @@ /** * D2L - Convert double to long * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class D2L extends ConversionInstruction { @@ -39,9 +39,9 @@ public D2L() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DADD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DADD.java index 55c6e05fe5a7..fd934ffce1cb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DADD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DADD.java @@ -24,9 +24,9 @@ /** * DADD - Add doubles * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result1.word2 */ @@ -41,9 +41,9 @@ public DADD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DALOAD.java index e875b35171bf..dfea43291fc1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DALOAD.java @@ -24,9 +24,9 @@ /** * DALOAD - Load double from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., result.word1, result.word2
- * 
+ *
*/ public class DALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public DALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DASTORE.java index 63a855900e19..3843fc9d24a3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DASTORE.java @@ -24,9 +24,9 @@ /** * DASTORE - Store into double array * - *
+ * 
  * Stack: ..., arrayref, index, value.word1, value.word2 -> ...
- * 
+ *
*/ public class DASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public DASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPG.java index aa1353ef569e..4995a8859500 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPG.java @@ -24,21 +24,22 @@ /** * DCMPG - Compare doubles: value1 > value2 * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 -> ..., result
- * 
+ *
*/ public class DCMPG extends Instruction implements TypedInstruction, StackProducer, StackConsumer { + /** Constructs a DCMPG instruction. */ public DCMPG() { super(com.sun.org.apache.bcel.internal.Const.DCMPG, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -49,7 +50,7 @@ public void accept(final Visitor v) { } /** - * @return Type.DOUBLE + * @return Type.DOUBLE. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPL.java index b43380bdbf84..19f1c2ddce2e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCMPL.java @@ -24,21 +24,22 @@ /** * DCMPL - Compare doubles: value1 < value2 * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 -> ..., result
- * 
+ *
*/ public class DCMPL extends Instruction implements TypedInstruction, StackProducer, StackConsumer { + /** Constructs a DCMPL instruction. */ public DCMPL() { super(com.sun.org.apache.bcel.internal.Const.DCMPL, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -49,7 +50,7 @@ public void accept(final Visitor v) { } /** - * @return Type.DOUBLE + * @return Type.DOUBLE. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCONST.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCONST.java index 313277185fe7..31103f7218f3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCONST.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DCONST.java @@ -23,10 +23,9 @@ /** * DCONST - Push 0.0 or 1.0, other values cause an exception * - *
+ * 
  * Stack: ... -> ...,
- * 
- * @LastModified: Jan 2020 + *
*/ public class DCONST extends Instruction implements ConstantPushInstruction { @@ -39,6 +38,12 @@ public class DCONST extends Instruction implements ConstantPushInstruction { this(0); } + /** + * Constructs a DCONST instruction. + * + * @param f The constant value (must be 0.0 or 1.0). + * @throws ClassGenException Thrown if f is not 0.0 or 1.0. + */ public DCONST(final double f) { super(com.sun.org.apache.bcel.internal.Const.DCONST_0, (short) 1); if (f == 0.0) { @@ -53,9 +58,9 @@ public DCONST(final double f) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -67,7 +72,7 @@ public void accept(final Visitor v) { } /** - * @return Type.DOUBLE + * @return Type.DOUBLE. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DDIV.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DDIV.java index 29c008e7ccb3..9584a0dd3532 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DDIV.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DDIV.java @@ -24,9 +24,9 @@ /** * DDIV - Divide doubles * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ @@ -41,9 +41,9 @@ public DDIV() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DLOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DLOAD.java index 9b61fd6697ca..24679ebb86e7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DLOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DLOAD.java @@ -24,9 +24,9 @@ /** * DLOAD - Load double from local variable * - *
+ * 
  * Stack ... -> ..., result.word1, result.word2
- * 
+ *
*/ public class DLOAD extends LoadInstruction { @@ -40,7 +40,7 @@ public class DLOAD extends LoadInstruction { /** * Load double from local variable * - * @param n index of local variable + * @param n index of local variable. */ public DLOAD(final int n) { super(com.sun.org.apache.bcel.internal.Const.DLOAD, com.sun.org.apache.bcel.internal.Const.DLOAD_0, n); @@ -48,9 +48,9 @@ public DLOAD(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DMUL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DMUL.java index 6dc65ffa0823..8719690d6423 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DMUL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DMUL.java @@ -24,9 +24,9 @@ /** * DMUL - Multiply doubles * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ @@ -41,9 +41,9 @@ public DMUL() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DNEG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DNEG.java index 8999f6fbaa32..e75d4a8ae954 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DNEG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DNEG.java @@ -24,21 +24,22 @@ /** * DNEG - Negate double * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class DNEG extends ArithmeticInstruction { + /** Constructs a DNEG instruction. */ public DNEG() { super(com.sun.org.apache.bcel.internal.Const.DNEG); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DREM.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DREM.java index b478f6ca94a2..bf5e0440b85a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DREM.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DREM.java @@ -24,9 +24,9 @@ /** * DREM - Remainder of doubles * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ @@ -41,9 +41,9 @@ public DREM() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DRETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DRETURN.java index 749d92246dd7..432a1ac60060 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DRETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DRETURN.java @@ -24,9 +24,9 @@ /** * DRETURN - Return double from method * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> <empty>
- * 
+ *
*/ public class DRETURN extends ReturnInstruction { @@ -39,9 +39,9 @@ public DRETURN() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSTORE.java index bd4e130c7e81..01b294d69521 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSTORE.java @@ -26,7 +26,7 @@ * *
  * Stack: ..., value.word1, value.word2 -> ...
- * 
+ * */ public class DSTORE extends StoreInstruction { @@ -40,7 +40,7 @@ public class DSTORE extends StoreInstruction { /** * Store double into local variable * - * @param n index of local variable + * @param n index of local variable. */ public DSTORE(final int n) { super(com.sun.org.apache.bcel.internal.Const.DSTORE, com.sun.org.apache.bcel.internal.Const.DSTORE_0, n); @@ -48,9 +48,9 @@ public DSTORE(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSUB.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSUB.java index 080a325d7435..29825c594b15 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSUB.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DSUB.java @@ -24,9 +24,9 @@ /** * DSUB - Substract doubles * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ @@ -41,9 +41,9 @@ public DSUB() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP.java index 30cc6821c286..f63bab81ad60 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP.java @@ -24,21 +24,22 @@ /** * DUP - Duplicate top operand stack word * - *
+ * 
  * Stack: ..., word -> ..., word, word
- * 
+ *
*/ public class DUP extends StackInstruction implements PushInstruction { + /** Constructs a DUP instruction. */ public DUP() { super(com.sun.org.apache.bcel.internal.Const.DUP); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2.java index 8b01a0606a07..f2b6646dfa99 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2.java @@ -24,21 +24,22 @@ /** * DUP2 - Duplicate two top operand stack words * - *
+ * 
  * Stack: ..., word2, word1 -> ..., word2, word1, word2, word1
- * 
+ *
*/ public class DUP2 extends StackInstruction implements PushInstruction { + /** Constructs a DUP2 instruction. */ public DUP2() { super(com.sun.org.apache.bcel.internal.Const.DUP2); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X1.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X1.java index 69043ab87dc2..1f16e0d025e0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X1.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X1.java @@ -24,21 +24,22 @@ /** * DUP2_X1 - Duplicate two top operand stack words and put three down * - *
+ * 
  * Stack: ..., word3, word2, word1 -> ..., word2, word1, word3, word2, word1
- * 
+ *
*/ public class DUP2_X1 extends StackInstruction { + /** Constructs a DUP2_X1 instruction. */ public DUP2_X1() { super(com.sun.org.apache.bcel.internal.Const.DUP2_X1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X2.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X2.java index e9b807ffc308..e7cb06a00c35 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X2.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP2_X2.java @@ -24,21 +24,22 @@ /** * DUP2_X2 - Duplicate two top operand stack words and put four down * - *
+ * 
  * Stack: ..., word4, word3, word2, word1 -> ..., word2, word1, word4, word3, word2, word1
- * 
+ *
*/ public class DUP2_X2 extends StackInstruction { + /** Constructs a DUP2_X2 instruction. */ public DUP2_X2() { super(com.sun.org.apache.bcel.internal.Const.DUP2_X2); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X1.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X1.java index ce2316baa88e..38f1d97a099a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X1.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X1.java @@ -24,21 +24,22 @@ /** * DUP_X1 - Duplicate top operand stack word and put two down * - *
+ * 
  * Stack: ..., word2, word1 -> ..., word1, word2, word1
- * 
+ *
*/ public class DUP_X1 extends StackInstruction { + /** Constructs a DUP_X1 instruction. */ public DUP_X1() { super(com.sun.org.apache.bcel.internal.Const.DUP_X1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X2.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X2.java index 735437e1f80d..49cd8063d495 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X2.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/DUP_X2.java @@ -24,21 +24,22 @@ /** * DUP_X2 - Duplicate top operand stack word and put three down * - *
+ * 
  * Stack: ..., word3, word2, word1 -> ..., word1, word3, word2, word1
- * 
+ *
*/ public class DUP_X2 extends StackInstruction { + /** Constructs a DUP_X2 instruction. */ public DUP_X2() { super(com.sun.org.apache.bcel.internal.Const.DUP_X2); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValueGen.java index 11b6b014a057..5476629c7d18 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValueGen.java @@ -33,38 +33,58 @@ import com.sun.org.apache.bcel.internal.classfile.SimpleElementValue; /** + * Generates element values in annotations. + * * @since 6.0 - * @LastModified: May 2021 */ public abstract class ElementValueGen { + + /** Element value type: string. */ public static final int STRING = 's'; + /** Element value type: enum constant. */ public static final int ENUM_CONSTANT = 'e'; + /** Element value type: class. */ public static final int CLASS = 'c'; + /** Element value type: annotation. */ public static final int ANNOTATION = '@'; + /** Element value type: array. */ public static final int ARRAY = '['; + /** Element value type: primitive int. */ public static final int PRIMITIVE_INT = 'I'; + /** Element value type: primitive byte. */ public static final int PRIMITIVE_BYTE = 'B'; + /** Element value type: primitive char. */ public static final int PRIMITIVE_CHAR = 'C'; + /** Element value type: primitive double. */ public static final int PRIMITIVE_DOUBLE = 'D'; + /** Element value type: primitive float. */ public static final int PRIMITIVE_FLOAT = 'F'; + /** Element value type: primitive long. */ public static final int PRIMITIVE_LONG = 'J'; + /** Element value type: primitive short. */ public static final int PRIMITIVE_SHORT = 'S'; + /** Element value type: primitive boolean. */ public static final int PRIMITIVE_BOOLEAN = 'Z'; /** * Creates an (modifiable) ElementValueGen copy of an (immutable) ElementValue - constant pool is assumed correct. + * + * @param value The element value to copy. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. + * @return A copy of the element value. */ public static ElementValueGen copy(final ElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { switch (value.getElementValueType()) { @@ -91,6 +111,14 @@ public static ElementValueGen copy(final ElementValue value, final ConstantPoolG } } + /** + * Reads an element value from a DataInput. + * + * @param dis The data input stream. + * @param cpGen The constant pool. + * @return The element value read. + * @throws IOException Thrown if an I/O error occurs. + */ public static ElementValueGen readElementValue(final DataInput dis, final ConstantPoolGen cpGen) throws IOException { final int type = dis.readUnsignedByte(); switch (type) { @@ -145,25 +173,54 @@ public static ElementValueGen readElementValue(final DataInput dis, final Consta @Deprecated protected ConstantPoolGen cpGen; + /** + * Constructs an ElementValueGen. + * + * @param type The element value type. + * @param cpGen The constant pool. + */ protected ElementValueGen(final int type, final ConstantPoolGen cpGen) { this.type = type; this.cpGen = cpGen; } + /** + * Dumps this element value to a DataOutputStream. + * + * @param dos The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ public abstract void dump(DataOutputStream dos) throws IOException; + /** + * Gets the constant pool. + * + * @return The constant pool. + */ protected ConstantPoolGen getConstantPool() { return cpGen; } /** - * Subtypes return an immutable variant of the ElementValueGen + * Subtypes return an immutable variant of the ElementValueGen. + * + * @return An immutable variant of the ElementValueGen. */ public abstract ElementValue getElementValue(); + /** + * Gets the element value type. + * + * @return The element value type. + */ public int getElementValueType() { return type; } + /** + * Returns a string representation of the element value. + * + * @return A string representation of the element value. + */ public abstract String stringifyValue(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValuePairGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValuePairGen.java index 878f392b6b77..70c6fbdb0ec8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValuePairGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ElementValuePairGen.java @@ -29,6 +29,8 @@ import com.sun.org.apache.bcel.internal.classfile.ElementValuePair; /** + * Generates element value pairs in annotations. + * * @since 6.0 */ public class ElementValuePairGen { @@ -38,6 +40,13 @@ public class ElementValuePairGen { private final ConstantPoolGen constantPoolGen; + /** + * Constructs an ElementValuePairGen from an ElementValuePair. + * + * @param nvp The element value pair. + * @param cpool The constant pool. + * @param copyPoolEntries whether to copy pool entries. + */ public ElementValuePairGen(final ElementValuePair nvp, final ConstantPoolGen cpool, final boolean copyPoolEntries) { this.constantPoolGen = cpool; // J5ASSERT: @@ -56,40 +65,77 @@ public ElementValuePairGen(final ElementValuePair nvp, final ConstantPoolGen cpo value = ElementValueGen.copy(nvp.getValue(), cpool, copyPoolEntries); } + /** + * Constructs an ElementValuePairGen. + * + * @param idx The name index. + * @param value The element value. + * @param cpool The constant pool. + */ protected ElementValuePairGen(final int idx, final ElementValueGen value, final ConstantPoolGen cpool) { this.nameIdx = idx; this.value = value; this.constantPoolGen = cpool; } + /** + * Constructs an ElementValuePairGen. + * + * @param name The name. + * @param value The element value. + * @param cpool The constant pool. + */ public ElementValuePairGen(final String name, final ElementValueGen value, final ConstantPoolGen cpool) { this.nameIdx = cpool.addUtf8(name); this.value = value; this.constantPoolGen = cpool; } + /** + * Dumps this element value pair to a DataOutputStream. + * + * @param dos The output stream. + * @throws IOException Thrown if an I/O error occurs. + */ protected void dump(final DataOutputStream dos) throws IOException { dos.writeShort(nameIdx); // u2 name of the element value.dump(dos); } /** - * Retrieve an immutable version of this ElementNameValuePairGen + * Retrieves an immutable version of this ElementValuePairGen. + * + * @return An immutable ElementValuePair. */ public ElementValuePair getElementNameValuePair() { final ElementValue immutableValue = value.getElementValue(); return new ElementValuePair(nameIdx, immutableValue, constantPoolGen.getConstantPool()); } + /** + * Gets the name index. + * + * @return The name index. + */ public int getNameIndex() { return nameIdx; } + /** + * Gets the name string. + * + * @return The name string. + */ public final String getNameString() { // ConstantString cu8 = (ConstantString) constantPoolGen.getConstant(nameIdx); return ((ConstantUtf8) constantPoolGen.getConstant(nameIdx)).getBytes(); } + /** + * Gets the value. + * + * @return The element value. + */ public final ElementValueGen getValue() { return value; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EmptyVisitor.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EmptyVisitor.java index b76944416cb9..102daedd9a77 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EmptyVisitor.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EmptyVisitor.java @@ -26,6 +26,10 @@ */ public abstract class EmptyVisitor implements Visitor { + /** Constructs an EmptyVisitor. */ + public EmptyVisitor() { + } + @Override public void visitAALOAD(final AALOAD obj) { } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EnumElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EnumElementValueGen.java index 95c00ed38132..5a03e60a78bb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EnumElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/EnumElementValueGen.java @@ -29,6 +29,8 @@ import com.sun.org.apache.bcel.internal.classfile.EnumElementValue; /** + * Generates enum element values in annotations. + * * @since 6.0 */ public class EnumElementValueGen extends ElementValueGen { @@ -37,6 +39,13 @@ public class EnumElementValueGen extends ElementValueGen { private final int valueIdx; + /** + * Constructs an EnumElementValueGen from an EnumElementValue. + * + * @param value The enum element value. + * @param cpool The constant pool. + * @param copyPoolEntries whether to copy pool entries. + */ public EnumElementValueGen(final EnumElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { super(ENUM_CONSTANT, cpool); if (copyPoolEntries) { @@ -49,8 +58,12 @@ public EnumElementValueGen(final EnumElementValue value, final ConstantPoolGen c } /** - * This ctor assumes the constant pool already contains the right type and value - as indicated by typeIdx and valueIdx. - * This ctor is used for deserialization + * This constructor assumes the constant pool already contains the right type and value - as indicated by typeIdx and valueIdx. + * This constructor is used for deserialization. + * + * @param typeIdx The type index. + * @param valueIdx The value index. + * @param cpool The constant pool. */ protected EnumElementValueGen(final int typeIdx, final int valueIdx, final ConstantPoolGen cpool) { super(ENUM_CONSTANT, cpool); @@ -61,6 +74,13 @@ protected EnumElementValueGen(final int typeIdx, final int valueIdx, final Const this.valueIdx = valueIdx; } + /** + * Constructs an EnumElementValueGen. + * + * @param t The object type. + * @param value The value. + * @param cpool The constant pool. + */ public EnumElementValueGen(final ObjectType t, final String value, final ConstantPoolGen cpool) { super(ENUM_CONSTANT, cpool); typeIdx = cpool.addUtf8(t.getSignature()); // was addClass(t); @@ -75,7 +95,9 @@ public void dump(final DataOutputStream dos) throws IOException { } /** - * Return immutable variant of this EnumElementValue + * Returns immutable variant of this EnumElementValueGen. + * + * @return immutable variant. */ @Override public ElementValue getElementValue() { @@ -83,8 +105,11 @@ public ElementValue getElementValue() { return new EnumElementValue(super.getElementValueType(), typeIdx, valueIdx, getConstantPool().getConstantPool()); } - // BCELBUG: Should we need to call utility.signatureToString() on the output - // here? + /** + * Gets the enum type string. + * + * @return The enum type string. + */ public String getEnumTypeString() { // Constant cc = getConstantPool().getConstant(typeIdx); // ConstantClass cu8 = @@ -95,6 +120,11 @@ public String getEnumTypeString() { // return Utility.signatureToString(cu8.getBytes()); } + /** + * Gets the enum value string. + * + * @return The enum value string. + */ public String getEnumValueString() { return ((ConstantUtf8) getConstantPool().getConstant(valueIdx)).getBytes(); // ConstantString cu8 = @@ -103,10 +133,20 @@ public String getEnumValueString() { // ((ConstantUtf8) getConstantPool().getConstant(cu8.getStringIndex())).getBytes(); } + /** + * Gets the type index. + * + * @return The type index. + */ public int getTypeIndex() { return typeIdx; } + /** + * Gets the value index. + * + * @return The value index. + */ public int getValueIndex() { return valueIdx; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ExceptionThrower.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ExceptionThrower.java index 2a488c85edeb..23a728b30d0d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ExceptionThrower.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ExceptionThrower.java @@ -25,7 +25,7 @@ * Denote an instruction that may throw a run-time or a linking exception (or both) during execution. This is not quite * the truth as such; because all instructions may throw a {@link VirtualMachineError}. These exceptions are omitted. * - * The Lava Language Specification specifies exactly which RUN-TIME and which LINKING exceptions each + * The Lava Language Specification specifies exactly which RUN-TIME and which LINKING exceptions each * instruction may throw which is reflected by the implementers. Due to the structure of the JVM specification, it may * be possible that an Instruction implementing this interface returns a Class[] of size 0. * @@ -34,5 +34,10 @@ */ public interface ExceptionThrower { + /** + * Gets the exceptions that may be thrown by this instruction. + * + * @return The exceptions that may be thrown by this instruction. + */ Class[] getExceptions(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2D.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2D.java index 3697ae379d51..c581cce1c8f9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2D.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2D.java @@ -24,9 +24,9 @@ /** * F2D - Convert float to double * - *
+ * 
  * Stack: ..., value -> ..., result.word1, result.word2
- * 
+ *
*/ public class F2D extends ConversionInstruction { @@ -39,9 +39,9 @@ public F2D() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2I.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2I.java index 552ab176a295..805f96e80eec 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2I.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2I.java @@ -24,9 +24,9 @@ /** * F2I - Convert float to int * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class F2I extends ConversionInstruction { @@ -39,9 +39,9 @@ public F2I() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2L.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2L.java index 73b4edf7a2c6..d61a0406cdca 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2L.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/F2L.java @@ -24,9 +24,9 @@ /** * F2L - Convert float to long * - *
+ * 
  * Stack: ..., value -> ..., result.word1, result.word2
- * 
+ *
*/ public class F2L extends ConversionInstruction { @@ -39,9 +39,9 @@ public F2L() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FADD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FADD.java index a1e4e466b15b..5ca3bbb591f4 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FADD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FADD.java @@ -24,9 +24,9 @@ /** * FADD - Add floats * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class FADD extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public FADD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FALOAD.java index 7d00b4c57645..3b0e1c81d085 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FALOAD.java @@ -24,9 +24,9 @@ /** * FALOAD - Load float from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value
- * 
+ *
*/ public class FALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public FALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FASTORE.java index 0215fd74bef7..dae1bd99ba76 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FASTORE.java @@ -24,9 +24,9 @@ /** * FASTORE - Store into float array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class FASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public FASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPG.java index bbeb1e2ed23e..93fa17fae5ba 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPG.java @@ -24,21 +24,22 @@ /** * FCMPG - Compare floats: value1 > value2 * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class FCMPG extends Instruction implements TypedInstruction, StackProducer, StackConsumer { + /** Constructs an FCMPG instruction. */ public FCMPG() { super(com.sun.org.apache.bcel.internal.Const.FCMPG, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -49,7 +50,7 @@ public void accept(final Visitor v) { } /** - * @return Type.FLOAT + * @return Type.FLOAT. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPL.java index 0b7cec09388c..a5ae2c9badd0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCMPL.java @@ -24,21 +24,22 @@ /** * FCMPL - Compare floats: value1 < value2 * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class FCMPL extends Instruction implements TypedInstruction, StackProducer, StackConsumer { + /** Constructs an FCMPL instruction. */ public FCMPL() { super(com.sun.org.apache.bcel.internal.Const.FCMPL, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -49,7 +50,7 @@ public void accept(final Visitor v) { } /** - * @return Type.FLOAT + * @return Type.FLOAT. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCONST.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCONST.java index 7c8116e8cbf9..72709b686eb8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCONST.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FCONST.java @@ -23,10 +23,9 @@ /** * FCONST - Push 0.0, 1.0 or 2.0, other values cause an exception * - *
+ * 
  * Stack: ... -> ...,
- * 
- * @LastModified: Jan 2020 + *
*/ public class FCONST extends Instruction implements ConstantPushInstruction { @@ -39,6 +38,11 @@ public class FCONST extends Instruction implements ConstantPushInstruction { this(0); } + /** + * Constructs an FCONST instruction. + * + * @param f The float value. + */ public FCONST(final float f) { super(com.sun.org.apache.bcel.internal.Const.FCONST_0, (short) 1); if (f == 0.0) { @@ -55,9 +59,9 @@ public FCONST(final float f) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -69,7 +73,7 @@ public void accept(final Visitor v) { } /** - * @return Type.FLOAT + * @return Type.FLOAT. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FDIV.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FDIV.java index 010c9d9960a3..6ee21a03d7da 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FDIV.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FDIV.java @@ -24,9 +24,9 @@ /** * FDIV - Divide floats * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class FDIV extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public FDIV() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FLOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FLOAD.java index e8abc13d642f..583a3636eecb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FLOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FLOAD.java @@ -24,9 +24,9 @@ /** * FLOAD - Load float from local variable * - *
+ * 
  * Stack ... -> ..., result
- * 
+ *
*/ public class FLOAD extends LoadInstruction { @@ -40,7 +40,7 @@ public class FLOAD extends LoadInstruction { /** * Load float from local variable * - * @param n index of local variable + * @param n index of local variable. */ public FLOAD(final int n) { super(com.sun.org.apache.bcel.internal.Const.FLOAD, com.sun.org.apache.bcel.internal.Const.FLOAD_0, n); @@ -48,9 +48,9 @@ public FLOAD(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FMUL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FMUL.java index a1d67147755f..25d05d6427c2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FMUL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FMUL.java @@ -24,9 +24,9 @@ /** * FMUL - Multiply floats * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class FMUL extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public FMUL() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FNEG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FNEG.java index eb134d9940f8..3af9dc674df0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FNEG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FNEG.java @@ -24,21 +24,24 @@ /** * FNEG - Negate float * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class FNEG extends ArithmeticInstruction { + /** + * Constructs an FNEG instruction. + */ public FNEG() { super(com.sun.org.apache.bcel.internal.Const.FNEG); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FREM.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FREM.java index 39e0740cfbc2..38a8896a5f9b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FREM.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FREM.java @@ -24,9 +24,9 @@ /** * FREM - Remainder of floats * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class FREM extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public FREM() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FRETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FRETURN.java index 3f7ba0c9a751..2a3407ef2f93 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FRETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FRETURN.java @@ -24,9 +24,9 @@ /** * FRETURN - Return float from method * - *
+ * 
  * Stack: ..., value -> <empty>
- * 
+ *
*/ public class FRETURN extends ReturnInstruction { @@ -39,9 +39,9 @@ public FRETURN() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSTORE.java index 868f9211f032..34eadaf64cf6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSTORE.java @@ -24,9 +24,9 @@ /** * FSTORE - Store float into local variable * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class FSTORE extends StoreInstruction { @@ -40,7 +40,7 @@ public class FSTORE extends StoreInstruction { /** * Store float into local variable * - * @param n index of local variable + * @param n index of local variable. */ public FSTORE(final int n) { super(com.sun.org.apache.bcel.internal.Const.FSTORE, com.sun.org.apache.bcel.internal.Const.FSTORE_0, n); @@ -48,9 +48,9 @@ public FSTORE(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSUB.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSUB.java index 9f2a3607a3dd..1ab47774d100 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSUB.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FSUB.java @@ -24,9 +24,9 @@ /** * FSUB - Substract floats * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class FSUB extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public FSUB() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGen.java index 30786370d290..8b314f127a57 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGen.java @@ -40,7 +40,6 @@ * to a field (which must of course be compatible with to the declared type). * * @see Field - * @LastModified: Sept 2025 */ public class FieldGen extends FieldGenOrMethodGen { @@ -58,6 +57,8 @@ public int hashCode(final FieldGen o) { }; /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -65,6 +66,8 @@ public static BCELComparator getComparator() { } /** + * Sets the comparison strategy object. + * * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { @@ -100,10 +103,10 @@ public FieldGen(final Field field, final ConstantPoolGen cp) { * Declare a field. If it is static (isStatic() == true) and has a basic type like int or String it may have an initial * value associated with it as defined by setInitValue(). * - * @param accessFlags access qualifiers - * @param type field type - * @param name field name - * @param cp constant pool + * @param accessFlags access qualifiers. + * @param type field type. + * @param name field name. + * @param cp constant pool. */ public FieldGen(final int accessFlags, final Type type, final String name, final ConstantPoolGen cp) { super(accessFlags); @@ -139,6 +142,8 @@ private int addConstant() { /** * Add observer for this object. + * + * @param o The observer to add. */ public void addObserver(final FieldObserver o) { if (observers == null) { @@ -160,7 +165,7 @@ private void checkType(final Type atype) { throw new ClassGenException("You haven't defined the type of the field yet"); } if (!isFinal()) { - throw new ClassGenException("Only final fields may have an initial value!"); + throw new ClassGenException("Only final fields may have an initial value."); } if (!superType.equals(atype)) { throw new ClassGenException("Types are not compatible: " + superType + " vs. " + atype); @@ -168,7 +173,10 @@ private void checkType(final Type atype) { } /** - * @return deep copy of this field + * Creates a deep copy of this field. + * + * @param cp The constant pool. + * @return deep copy of this field. */ public FieldGen copy(final ConstantPoolGen cp) { final FieldGen fg = (FieldGen) clone(); @@ -189,6 +197,8 @@ public boolean equals(final Object obj) { /** * Gets field object after having set up all necessary values. + * + * @return The field object. */ public Field getField() { final String signature = getSignature(); @@ -203,6 +213,11 @@ public Field getField() { return new Field(super.getAccessFlags(), nameIndex, signatureIndex, getAttributes(), super.getConstantPool().getConstantPool()); // sic } + /** + * Gets the initial value. + * + * @return The initial value. + */ public String getInitValue() { return Objects.toString(value, null); } @@ -225,6 +240,8 @@ public int hashCode() { /** * Remove observer for this object. + * + * @param o The observer to remove. */ public void removeObserver(final FieldObserver o) { if (observers != null) { @@ -232,6 +249,11 @@ public void removeObserver(final FieldObserver o) { } } + /** + * Sets the initial value. + * + * @param b The boolean value. + */ public void setInitValue(final boolean b) { checkType(Type.BOOLEAN); if (b) { @@ -239,6 +261,11 @@ public void setInitValue(final boolean b) { } } + /** + * Sets the initial value. + * + * @param b The byte value. + */ public void setInitValue(final byte b) { checkType(Type.BYTE); if (b != 0) { @@ -246,6 +273,11 @@ public void setInitValue(final byte b) { } } + /** + * Sets the initial value. + * + * @param c The char value. + */ public void setInitValue(final char c) { checkType(Type.CHAR); if (c != 0) { @@ -253,6 +285,11 @@ public void setInitValue(final char c) { } } + /** + * Sets the initial value. + * + * @param d The double value. + */ public void setInitValue(final double d) { checkType(Type.DOUBLE); if (d != 0.0) { @@ -260,6 +297,11 @@ public void setInitValue(final double d) { } } + /** + * Sets the initial value. + * + * @param f The float value. + */ public void setInitValue(final float f) { checkType(Type.FLOAT); if (f != 0.0) { @@ -267,6 +309,11 @@ public void setInitValue(final float f) { } } + /** + * Sets the initial value. + * + * @param i The int value. + */ public void setInitValue(final int i) { checkType(Type.INT); if (i != 0) { @@ -274,6 +321,11 @@ public void setInitValue(final int i) { } } + /** + * Sets the initial value. + * + * @param l The long value. + */ public void setInitValue(final long l) { checkType(Type.LONG); if (l != 0L) { @@ -281,6 +333,11 @@ public void setInitValue(final long l) { } } + /** + * Sets the initial value. + * + * @param s The short value. + */ public void setInitValue(final short s) { checkType(Type.SHORT); if (s != 0) { @@ -290,6 +347,8 @@ public void setInitValue(final short s) { /** * Sets (optional) initial value of field, otherwise it will be set to null/0/false by the JVM automatically. + * + * @param str The string value. */ public void setInitValue(final String str) { checkType(ObjectType.getInstance("java.lang.String")); @@ -305,19 +364,17 @@ private void setValue(final int index) { } /** - * Return string representation close to declaration format, 'public static final short MAX = 100', e.g.. + * Return string representation close to declaration format, for example: 'public static final short MAX = 100'. * - * @return String representation of field + * @return String representation of field. */ @Override public final String toString() { - String name; - String signature; - String access; // Short cuts to constant pool - access = Utility.accessToString(super.getAccessFlags()); + // Short cuts to constant pool + String access = Utility.accessToString(super.getAccessFlags()); access = access.isEmpty() ? "" : access + " "; - signature = super.getType().toString(); - name = getName(); + final String signature = super.getType().toString(); + final String name = getName(); final StringBuilder buf = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber buf.append(access).append(signature).append(" ").append(name); final String value = getInitValue(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGenOrMethodGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGenOrMethodGen.java index bc1fbc8627e2..93afde778203 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGenOrMethodGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldGenOrMethodGen.java @@ -29,8 +29,6 @@ /** * Super class for FieldGen and MethodGen objects, since they have some methods in common! - * - * @LastModified: Sept 2025 */ public abstract class FieldGenOrMethodGen extends AccessFlags implements NamedAndTyped, Cloneable { @@ -57,16 +55,27 @@ public abstract class FieldGenOrMethodGen extends AccessFlags implements NamedAn // @since 6.0 private final List annotationList = new ArrayList<>(); + /** + * Constructs a FieldGenOrMethodGen. + */ protected FieldGenOrMethodGen() { } /** + * Constructs a FieldGenOrMethodGen. + * + * @param accessFlags The access flags. * @since 6.0 */ protected FieldGenOrMethodGen(final int accessFlags) { // TODO could this be package protected? super(accessFlags); } + /** + * Adds all attributes from an array. + * + * @param attributes The attributes to add. + */ protected void addAll(final Attribute[] attributes) { if (attributes != null) { Collections.addAll(attributeList, attributes); @@ -74,6 +83,9 @@ protected void addAll(final Attribute[] attributes) { } /** + * Adds an annotation entry. + * + * @param ag The annotation entry. * @since 6.0 */ public void addAnnotationEntry(final AnnotationEntryGen ag) { @@ -84,7 +96,7 @@ public void addAnnotationEntry(final AnnotationEntryGen ag) { * Add an attribute to this method. Currently, the JVM knows about the 'Code', 'ConstantValue', 'Synthetic' and * 'Exceptions' attributes. Other attributes will be ignored by the JVM but do no harm. * - * @param a attribute to be added + * @param a attribute to be added. */ public void addAttribute(final Attribute a) { attributeList.add(a); @@ -99,17 +111,29 @@ public Object clone() { } } + /** + * Gets all annotation entries. + * + * @return all annotation entries. + */ public AnnotationEntryGen[] getAnnotationEntries() { return annotationList.toArray(AnnotationEntryGen.EMPTY_ARRAY); } /** + * Gets all attributes of this method or field. + * * @return all attributes of this method. */ public Attribute[] getAttributes() { return attributeList.toArray(Attribute.EMPTY_ARRAY); } + /** + * Gets the constant pool. + * + * @return The constant pool. + */ public ConstantPoolGen getConstantPool() { return cp; } @@ -123,6 +147,8 @@ public String getName() { } /** + * Gets the signature of method or field. + * * @return signature of method/field. */ public abstract String getSignature(); @@ -133,6 +159,8 @@ public Type getType() { } /** + * Removes all annotation entries. + * * @since 6.0 */ public void removeAnnotationEntries() { @@ -140,6 +168,9 @@ public void removeAnnotationEntries() { } /** + * Removes an annotation entry. + * + * @param ag The annotation entry to remove. * @since 6.0 */ public void removeAnnotationEntry(final AnnotationEntryGen ag) { @@ -147,19 +178,26 @@ public void removeAnnotationEntry(final AnnotationEntryGen ag) { } /** - * Remove an attribute. + * Removes an attribute. + * + * @param a The attribute to remove. */ public void removeAttribute(final Attribute a) { attributeList.remove(a); } /** - * Remove all attributes. + * Removes all attributes. */ public void removeAttributes() { attributeList.clear(); } + /** + * Sets the constant pool. + * + * @param cp The constant pool. + */ public void setConstantPool(final ConstantPoolGen cp) { // TODO could be package-protected? this.cp = cp; } @@ -172,7 +210,7 @@ public void setName(final String name) { // TODO could be package-protected? @Override public void setType(final Type type) { // TODO could be package-protected? if (type.getType() == Const.T_ADDRESS) { - throw new IllegalArgumentException("Type can not be " + type); + throw new IllegalArgumentException("Type cannot be " + type); } this.type = type; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldInstruction.java index 368d07ec99f8..96356f13c6cd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldInstruction.java @@ -35,13 +35,19 @@ public abstract class FieldInstruction extends FieldOrMethod { } /** - * @param index to constant pool + * Constructs a FieldInstruction. + * + * @param opcode The opcode. + * @param index to constant pool. */ protected FieldInstruction(final short opcode, final int index) { super(opcode, index); } /** + * Gets the name of referenced field. + * + * @param cpg The constant pool generator. * @return name of referenced field. */ public String getFieldName(final ConstantPoolGen cpg) { @@ -49,21 +55,27 @@ public String getFieldName(final ConstantPoolGen cpg) { } /** - * @return size of field (1 or 2) + * Gets the size of field. + * + * @param cpg The constant pool generator. + * @return size of field (1 or 2). */ protected int getFieldSize(final ConstantPoolGen cpg) { return Type.size(Type.getTypeSize(getSignature(cpg))); } /** - * @return type of field + * Gets the type of field. + * + * @param cpg The constant pool generator. + * @return type of field. */ public Type getFieldType(final ConstantPoolGen cpg) { return Type.getType(getSignature(cpg)); } /** - * @return return type of referenced field + * @return return type of referenced field. */ @Override public Type getType(final ConstantPoolGen cpg) { @@ -71,7 +83,7 @@ public Type getType(final ConstantPoolGen cpg) { } /** - * @return mnemonic for instruction with symbolic references resolved + * @return mnemonic for instruction with symbolic references resolved. */ @Override public String toString(final ConstantPool cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldObserver.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldObserver.java index a207a098522c..5232635fe8e7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldObserver.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldObserver.java @@ -27,5 +27,10 @@ */ public interface FieldObserver { + /** + * Notifies observer of a field change. + * + * @param field The field that changed. + */ void notify(FieldGen field); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldOrMethod.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldOrMethod.java index 87ba4cb913ea..cb06de0a17cd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldOrMethod.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/FieldOrMethod.java @@ -41,16 +41,22 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { } /** - * @param index to constant pool + * Constructs a FieldOrMethod. + * + * @param opcode The opcode. + * @param index to constant pool. */ protected FieldOrMethod(final short opcode, final int index) { super(opcode, index); } /** - * @return name of the referenced class/interface + * Gets the name of the referenced class/interface. + * + * @param cpg The constant pool generator. + * @return name of the referenced class/interface. * @deprecated If the instruction references an array class, this method will return "java.lang.Object". For code - * generated by Java 1.5, this answer is sometimes wrong (e.g., if the "clone()" method is called on an + * generated by Java 1.5, this answer is sometimes wrong (for example, if the "clone()" method is called on an * array). A better idea is to use the {@link #getReferenceType(ConstantPoolGen)} method, which correctly * distinguishes between class types and array types. */ @@ -67,7 +73,10 @@ public String getClassName(final ConstantPoolGen cpg) { } /** - * @return type of the referenced class/interface + * Gets the type of the referenced class/interface. + * + * @param cpg The constant pool generator. + * @return type of the referenced class/interface. * @deprecated If the instruction references an array class, the ObjectType returned will be invalid. Use * getReferenceType() instead. */ @@ -79,8 +88,9 @@ public ObjectType getClassType(final ConstantPoolGen cpg) { /** * Gets the ObjectType of the method return or field. * - * @return type of the referenced class/interface - * @throws ClassGenException when the field is (or method returns) an array, + * @param cpg The constant pool generator. + * @return type of the referenced class/interface. + * @throws ClassGenException Thrown when the field is (or method returns) an array. */ @Override public ObjectType getLoadClassType(final ConstantPoolGen cpg) { @@ -95,6 +105,9 @@ public ObjectType getLoadClassType(final ConstantPoolGen cpg) { } /** + * Gets the name of referenced method or field. + * + * @param cpg The constant pool generator. * @return name of referenced method/field. */ public String getName(final ConstantPoolGen cpg) { @@ -107,8 +120,8 @@ public String getName(final ConstantPoolGen cpg) { /** * Gets the reference type representing the class, interface, or array class referenced by the instruction. * - * @param cpg the ConstantPoolGen used to create the instruction - * @return an ObjectType (if the referenced class type is a class or interface), or an ArrayType (if the referenced + * @param cpg The ConstantPoolGen used to create the instruction. + * @return An ObjectType (if the referenced class type is a class or interface), or an ArrayType (if the referenced * class type is an array class) */ public ReferenceType getReferenceType(final ConstantPoolGen cpg) { @@ -123,6 +136,9 @@ public ReferenceType getReferenceType(final ConstantPoolGen cpg) { } /** + * Gets the signature of referenced method or field. + * + * @param cpg The constant pool generator. * @return signature of referenced method/field. */ public String getSignature(final ConstantPoolGen cpg) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETFIELD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETFIELD.java index bc4e5b11674f..dbf7f3de8bbc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETFIELD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETFIELD.java @@ -26,15 +26,15 @@ /** * GETFIELD - Fetch field from object * - *
+ * 
  * Stack: ..., objectref -> ..., value
- * 
+ *
* * OR * - *
+ * 
  * Stack: ..., objectref -> ..., value.word1, value.word2
- * 
+ *
*/ public class GETFIELD extends FieldInstruction implements ExceptionThrower, StackConsumer, StackProducer { @@ -44,15 +44,20 @@ public class GETFIELD extends FieldInstruction implements ExceptionThrower, Stac GETFIELD() { } + /** + * Constructs a GETFIELD instruction. + * + * @param index The constant pool index. + */ public GETFIELD(final int index) { super(Const.GETFIELD, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETSTATIC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETSTATIC.java index b8c4a4a3560c..89bafe39b970 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETSTATIC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GETSTATIC.java @@ -27,15 +27,15 @@ /** * GETSTATIC - Fetch static field from class * - *
+ * 
  * Stack: ..., -> ..., value
- * 
+ *
* * OR * - *
+ * 
  * Stack: ..., -> ..., value.word1, value.word2
- * 
+ *
*/ public class GETSTATIC extends FieldInstruction implements PushInstruction, ExceptionThrower { @@ -45,15 +45,20 @@ public class GETSTATIC extends FieldInstruction implements PushInstruction, Exce GETSTATIC() { } + /** + * Constructs a GETSTATIC instruction. + * + * @param index The constant pool index. + */ public GETSTATIC(final int index) { super(Const.GETSTATIC, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO.java index cd76aae79819..a790d098c3b7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO.java @@ -35,15 +35,20 @@ public class GOTO extends GotoInstruction implements VariableLengthInstruction { GOTO() { } + /** + * Constructs a GOTO instruction. + * + * @param target The target instruction. + */ public GOTO(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.GOTO, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,9 +60,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -76,9 +81,9 @@ public void dump(final DataOutputStream out) throws IOException { * Called in pass 2 of InstructionList.setPositions() in order to update the branch target, that may shift due to * variable length instructions. * - * @param offset additional offset caused by preceding (variable length) instructions - * @param maxOffset the maximum offset that may be caused by these instructions - * @return additional offset caused by possible change of this instruction's length + * @param offset additional offset caused by preceding (variable length) instructions. + * @param maxOffset The maximum offset that may be caused by these instructions. + * @return additional offset caused by possible change of this instruction's length. */ @Override protected int updatePosition(final int offset, final int maxOffset) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO_W.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO_W.java index df4c06be09a3..4a130c85ebdf 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO_W.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/GOTO_W.java @@ -37,6 +37,11 @@ public class GOTO_W extends GotoInstruction { GOTO_W() { } + /** + * Constructs a GOTO_W instruction. + * + * @param target The target instruction. + */ public GOTO_W(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.GOTO_W, target); super.setLength(5); @@ -44,9 +49,9 @@ public GOTO_W(final InstructionHandle target) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -57,9 +62,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -69,7 +74,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2B.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2B.java index 0b8c9dd529ea..2ea8595f1c2b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2B.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2B.java @@ -24,9 +24,9 @@ /** * I2B - Convert int to byte * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class I2B extends ConversionInstruction { @@ -39,9 +39,9 @@ public I2B() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2C.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2C.java index b5c6532a592a..c5b855cd730b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2C.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2C.java @@ -24,9 +24,9 @@ /** * I2C - Convert int to char * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class I2C extends ConversionInstruction { @@ -39,9 +39,9 @@ public I2C() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2D.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2D.java index e73270a58740..16df3fa3f616 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2D.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2D.java @@ -24,9 +24,9 @@ /** * I2D - Convert int to double * - *
+ * 
  * Stack: ..., value -> ..., result.word1, result.word2
- * 
+ *
*/ public class I2D extends ConversionInstruction { @@ -39,9 +39,9 @@ public I2D() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2F.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2F.java index dc7df8c6d48d..fcc8556efbed 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2F.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2F.java @@ -24,14 +24,14 @@ /** * I2F - Convert int to float * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class I2F extends ConversionInstruction { /** - * Convert int to float + * Convert int to float. */ public I2F() { super(com.sun.org.apache.bcel.internal.Const.I2F); @@ -39,9 +39,9 @@ public I2F() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2L.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2L.java index e0a8e81e1cd6..a6d0d8486cc6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2L.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2L.java @@ -24,9 +24,9 @@ /** * I2L - Convert int to long * - *
+ * 
  * Stack: ..., value -> ..., result.word1, result.word2
- * 
+ *
*/ public class I2L extends ConversionInstruction { @@ -39,9 +39,9 @@ public I2L() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2S.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2S.java index 04fa0e62a064..8ed2b53010dc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2S.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/I2S.java @@ -24,21 +24,24 @@ /** * I2S - Convert int to short * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class I2S extends ConversionInstruction { + /** + * Constructs an I2S instruction. + */ public I2S() { super(com.sun.org.apache.bcel.internal.Const.I2S); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IADD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IADD.java index ad5e109af8ca..0f5c60c54641 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IADD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IADD.java @@ -24,9 +24,9 @@ /** * IADD - Add ints * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class IADD extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public IADD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IALOAD.java index b9f39c13d510..8da34f055c18 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IALOAD.java @@ -24,9 +24,9 @@ /** * IALOAD - Load int from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value
- * 
+ *
*/ public class IALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public IALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IAND.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IAND.java index 4fe036cc5508..16369fb37771 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IAND.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IAND.java @@ -24,21 +24,24 @@ /** * IAND - Bitwise AND int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class IAND extends ArithmeticInstruction { + /** + * Constructs an IAND instruction. + */ public IAND() { super(com.sun.org.apache.bcel.internal.Const.IAND); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IASTORE.java index 62cded23fe46..01bd76de71b0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IASTORE.java @@ -24,9 +24,9 @@ /** * IASTORE - Store into int array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class IASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public IASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ICONST.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ICONST.java index bfec96e1af75..34fccb9fd0d4 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ICONST.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ICONST.java @@ -22,9 +22,9 @@ /** * ICONST - Push value between -1, ..., 5, other values cause an exception * - *
+ * 
  * Stack: ... -> ...,
- * 
+ *
*/ public class ICONST extends Instruction implements ConstantPushInstruction { @@ -37,6 +37,11 @@ public class ICONST extends Instruction implements ConstantPushInstruction { this(0); } + /** + * Constructs an ICONST instruction. + * + * @param i The integer value. + */ public ICONST(final int i) { super(com.sun.org.apache.bcel.internal.Const.ICONST_0, (short) 1); if (i < -1 || i > 5) { @@ -48,9 +53,9 @@ public ICONST(final int i) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -62,7 +67,7 @@ public void accept(final Visitor v) { } /** - * @return Type.INT + * @return Type.INT. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IDIV.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IDIV.java index e23968c9ae30..04db0a909192 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IDIV.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IDIV.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,10 +25,10 @@ /** * IDIV - Divide ints * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
- * @LastModified: Jan 2020 + *
+ * @LastModified: Nov 2026 */ public class IDIV extends ArithmeticInstruction implements ExceptionThrower { @@ -41,9 +41,9 @@ public IDIV() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -56,7 +56,7 @@ public void accept(final Visitor v) { } /** - * @return exceptions this instruction may cause + * @return exceptions this instruction may cause. */ @Override public Class[] getExceptions() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFEQ.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFEQ.java index c44d0f57dfe4..4cacff6776cb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFEQ.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFEQ.java @@ -24,9 +24,9 @@ /** * IFEQ - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFEQ extends IfInstruction { @@ -36,15 +36,20 @@ public class IFEQ extends IfInstruction { IFEQ() { } + /** + * Constructs an IFEQ instruction. + * + * @param target The target instruction. + */ public IFEQ(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFEQ, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction, e.g. IFEQ.negate() == IFNE + * @return negation of instruction, for example IFEQ.negate() == IFNE. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGE.java index 53e32a57ba30..a70f316c5858 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGE.java @@ -24,9 +24,9 @@ /** * IFGE - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFGE extends IfInstruction { @@ -36,15 +36,20 @@ public class IFGE extends IfInstruction { IFGE() { } + /** + * Constructs an IFGE instruction. + * + * @param target The target instruction. + */ public IFGE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFGE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGT.java index 23ab44754f65..8340f1e181b2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFGT.java @@ -24,9 +24,9 @@ /** * IFGT - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFGT extends IfInstruction { @@ -36,15 +36,20 @@ public class IFGT extends IfInstruction { IFGT() { } + /** + * Constructs an IFGT instruction. + * + * @param target The target instruction. + */ public IFGT(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFGT, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLE.java index 0bd68bd1be7b..6afda0b95f23 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLE.java @@ -24,9 +24,9 @@ /** * IFLE - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFLE extends IfInstruction { @@ -36,15 +36,20 @@ public class IFLE extends IfInstruction { IFLE() { } + /** + * Constructs an IFLE instruction. + * + * @param target The target instruction. + */ public IFLE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFLE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLT.java index 0c1589e95b84..6e42270764b1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFLT.java @@ -24,9 +24,9 @@ /** * IFLT - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFLT extends IfInstruction { @@ -36,15 +36,20 @@ public class IFLT extends IfInstruction { IFLT() { } + /** + * Constructs an IFLT instruction. + * + * @param target The target instruction. + */ public IFLT(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFLT, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNE.java index 91075bc66d80..6563d742d5c7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNE.java @@ -24,9 +24,9 @@ /** * IFNE - Branch if int comparison with zero succeeds * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class IFNE extends IfInstruction { @@ -36,15 +36,20 @@ public class IFNE extends IfInstruction { IFNE() { } + /** + * Constructs an IFNE instruction. + * + * @param target The target instruction. + */ public IFNE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFNE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNONNULL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNONNULL.java index 342779a9b4ff..b3a278d2123b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNONNULL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNONNULL.java @@ -24,9 +24,9 @@ /** * IFNONNULL - Branch if reference is not null * - *
+ * 
  * Stack: ..., reference -> ...
- * 
+ *
*/ public class IFNONNULL extends IfInstruction { @@ -36,15 +36,20 @@ public class IFNONNULL extends IfInstruction { IFNONNULL() { } + /** + * Constructs an IFNONNULL instruction. + * + * @param target The target instruction. + */ public IFNONNULL(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFNONNULL, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNULL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNULL.java index b680033096d8..f2fa43cf6215 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNULL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IFNULL.java @@ -24,9 +24,9 @@ /** * IFNULL - Branch if reference is not null * - *
+ * 
  * Stack: ..., reference -> ...
- * 
+ *
*/ public class IFNULL extends IfInstruction { @@ -36,15 +36,20 @@ public class IFNULL extends IfInstruction { IFNULL() { } + /** + * Constructs an IFNULL instruction. + * + * @param target The target instruction. + */ public IFNULL(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IFNULL, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPEQ.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPEQ.java index 9f14fb589093..eb17767e2ca9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPEQ.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPEQ.java @@ -24,9 +24,9 @@ /** * IF_ACMPEQ - Branch if reference comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ACMPEQ extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ACMPEQ extends IfInstruction { IF_ACMPEQ() { } + /** + * Constructs an IF_ACMPEQ instruction. + * + * @param target The target instruction. + */ public IF_ACMPEQ(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ACMPEQ, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPNE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPNE.java index 536abe40d640..e0a641184515 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPNE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ACMPNE.java @@ -24,9 +24,9 @@ /** * IF_ACMPNE - Branch if reference comparison doesn't succeed * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ACMPNE extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ACMPNE extends IfInstruction { IF_ACMPNE() { } + /** + * Constructs an IF_ACMPNE instruction. + * + * @param target The target instruction. + */ public IF_ACMPNE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ACMPNE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPEQ.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPEQ.java index a3fa883dfb29..2c84c61e58c1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPEQ.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPEQ.java @@ -24,9 +24,9 @@ /** * IF_ICMPEQ - Branch if int comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPEQ extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPEQ extends IfInstruction { IF_ICMPEQ() { } + /** + * Constructs an IF_ICMPEQ instruction. + * + * @param target The target instruction. + */ public IF_ICMPEQ(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPEQ, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGE.java index 8848da01b494..b1cc8fb18ffc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGE.java @@ -24,9 +24,9 @@ /** * IF_ICMPGE - Branch if int comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPGE extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPGE extends IfInstruction { IF_ICMPGE() { } + /** + * Constructs an IF_ICMPGE instruction. + * + * @param target The target instruction. + */ public IF_ICMPGE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPGE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGT.java index b1145cc9491b..1d48e6403c1c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPGT.java @@ -24,9 +24,9 @@ /** * IF_ICMPGT - Branch if int comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPGT extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPGT extends IfInstruction { IF_ICMPGT() { } + /** + * Constructs an IF_ICMPGT instruction. + * + * @param target The target instruction. + */ public IF_ICMPGT(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPGT, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLE.java index 54eed61742d0..3eb612a4604e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLE.java @@ -24,9 +24,9 @@ /** * IF_ICMPLE - Branch if int comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPLE extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPLE extends IfInstruction { IF_ICMPLE() { } + /** + * Constructs an IF_ICMPLE instruction. + * + * @param target The target instruction. + */ public IF_ICMPLE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPLE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLT.java index 7c159f4b56aa..384d7054b1d0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPLT.java @@ -24,9 +24,9 @@ /** * IF_ICMPLT - Branch if int comparison succeeds * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPLT extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPLT extends IfInstruction { IF_ICMPLT() { } + /** + * Constructs an IF_ICMPLT instruction. + * + * @param target The target instruction. + */ public IF_ICMPLT(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPLT, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPNE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPNE.java index 1c1f9800a473..96f85cd69930 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPNE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IF_ICMPNE.java @@ -24,9 +24,9 @@ /** * IF_ICMPNE - Branch if int comparison doesn't succeed * - *
+ * 
  * Stack: ..., value1, value2 -> ...
- * 
+ *
*/ public class IF_ICMPNE extends IfInstruction { @@ -36,15 +36,20 @@ public class IF_ICMPNE extends IfInstruction { IF_ICMPNE() { } + /** + * Constructs an IF_ICMPNE instruction. + * + * @param target The target instruction. + */ public IF_ICMPNE(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.IF_ICMPNE, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,7 +60,7 @@ public void accept(final Visitor v) { } /** - * @return negation of instruction + * @return negation of instruction. */ @Override public IfInstruction negate() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IINC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IINC.java index aeaa2d8cdd20..c48ab1074658 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IINC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IINC.java @@ -42,8 +42,10 @@ public class IINC extends LocalVariableInstruction { } /** - * @param n index of local variable - * @param c increment factor + * Constructs an IINC instruction. + * + * @param n index of local variable. + * @param c increment factor. */ public IINC(final int n, final int c) { // Default behavior of LocalVariableInstruction causes error @@ -55,9 +57,9 @@ public IINC(final int n, final int c) { /** * Calls corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -68,7 +70,7 @@ public void accept(final Visitor v) { /** * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -86,14 +88,18 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return increment factor + * Gets the increment factor. + * + * @return increment factor. */ public final int getIncrement() { return c; } /** - * @return int type + * Gets the int type. + * + * @return int type. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -101,7 +107,7 @@ public Type getType(final ConstantPoolGen cp) { } /** - * Reads needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -119,21 +125,30 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws /** * Sets increment factor. + * + * @param c The increment factor. + * @throws ClassGenException Thrown if the increment is out of bounds. */ public final void setIncrement(final int c) { + if (!isValidShort(c)) { + throw new ClassGenException("Illegal increment: " + c); + } this.c = c; setWide(); } /** * Sets index of local variable. + * + * @param index index of local variable. + * @throws ClassGenException Thrown if index is out of bounds. */ @Override - public final void setIndex(final int n) { - if (n < 0) { - throw new ClassGenException("Negative index value: " + n); + public final void setIndex(final int index) { + if (!isNonNegativeUShort(index)) { + throw new ClassGenException("Illegal index: " + index); } - super.setIndexOnly(n); + super.setIndexOnly(index); setWide(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ILOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ILOAD.java index 1ecc3aae4cc8..fa6639664c26 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ILOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ILOAD.java @@ -24,9 +24,9 @@ /** * ILOAD - Load int from local variable onto stack * - *
+ * 
  * Stack: ... -> ..., result
- * 
+ *
*/ public class ILOAD extends LoadInstruction { @@ -40,7 +40,7 @@ public class ILOAD extends LoadInstruction { /** * Load int from local variable * - * @param n index of local variable + * @param n index of local variable. */ public ILOAD(final int n) { super(com.sun.org.apache.bcel.internal.Const.ILOAD, com.sun.org.apache.bcel.internal.Const.ILOAD_0, n); @@ -48,9 +48,9 @@ public ILOAD(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP1.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP1.java index 62fc89299a96..85df66c9b8fe 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP1.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP1.java @@ -26,15 +26,18 @@ */ public class IMPDEP1 extends Instruction { + /** + * Constructs an IMPDEP1 instruction. + */ public IMPDEP1() { super(com.sun.org.apache.bcel.internal.Const.IMPDEP1, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP2.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP2.java index cef4e08c794e..1aeee6a16a9c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP2.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMPDEP2.java @@ -26,15 +26,18 @@ */ public class IMPDEP2 extends Instruction { + /** + * Constructs an IMPDEP2 instruction. + */ public IMPDEP2() { super(com.sun.org.apache.bcel.internal.Const.IMPDEP2, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMUL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMUL.java index 9f7ff3dbf6cb..37c2638e2e28 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMUL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IMUL.java @@ -24,9 +24,9 @@ /** * IMUL - Multiply ints * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class IMUL extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public IMUL() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INEG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INEG.java index d881260b66e4..15fb0623e320 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INEG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INEG.java @@ -24,21 +24,24 @@ /** * INEG - Negate int * - *
+ * 
  * Stack: ..., value -> ..., result
- * 
+ *
*/ public class INEG extends ArithmeticInstruction { + /** + * Constructs an INEG instruction. + */ public INEG() { super(com.sun.org.apache.bcel.internal.Const.INEG); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INSTANCEOF.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INSTANCEOF.java index 10d5f2c0f659..791bd843d1ce 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INSTANCEOF.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INSTANCEOF.java @@ -26,9 +26,9 @@ /** * INSTANCEOF - Determine if object is of given type * - *
+ * 
  * Stack: ..., objectref -> ..., result
- * 
+ *
*/ public class INSTANCEOF extends CPInstruction implements LoadClass, ExceptionThrower, StackProducer, StackConsumer { @@ -38,15 +38,20 @@ public class INSTANCEOF extends CPInstruction implements LoadClass, ExceptionThr INSTANCEOF() { } + /** + * Constructs an INSTANCEOF instruction. + * + * @param index The constant pool index. + */ public INSTANCEOF(final int index) { super(com.sun.org.apache.bcel.internal.Const.INSTANCEOF, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEDYNAMIC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEDYNAMIC.java index 998d072e0673..cd92efa374a2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEDYNAMIC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEDYNAMIC.java @@ -47,15 +47,21 @@ public class INVOKEDYNAMIC extends InvokeInstruction { INVOKEDYNAMIC() { } + /** + * Constructs an INVOKEDYNAMIC instruction. + * + * @param index index into constant pool. + */ public INVOKEDYNAMIC(final int index) { super(Const.INVOKEDYNAMIC, index); + super.setLength(5); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -71,9 +77,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -107,8 +113,8 @@ public Class[] getExceptions() { * Since InvokeDynamic doesn't refer to a reference type, just return {@link Object}, as that is the only type we can * say for sure the reference will be. * - * @param cpg the ConstantPoolGen used to create the instruction - * @return an ObjectType for {@link Object} + * @param cpg The ConstantPoolGen used to create the instruction. + * @return An ObjectType for {@link Object}. * @since 6.1 */ @Override @@ -117,7 +123,7 @@ public ReferenceType getReferenceType(final ConstantPoolGen cpg) { } /** - * Read needed data (i.e., index) from file. + * Reads needed data (that is, index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java index 7f1858c5766e..f1a3fa7713d3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java @@ -32,9 +32,9 @@ /** * INVOKEINTERFACE - Invoke interface method * - *
+ * 
  * Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
- * 
+ *
* * @see The * invokeinterface instruction in The Java Virtual Machine Specification @@ -49,20 +49,26 @@ public final class INVOKEINTERFACE extends InvokeInstruction { INVOKEINTERFACE() { } + /** + * Constructs an INVOKEINTERFACE instruction. + * + * @param index index into constant pool. + * @param nargs number of arguments. + */ public INVOKEINTERFACE(final int index, final int nargs) { super(Const.INVOKEINTERFACE, index); super.setLength(5); - if (nargs < 1) { - throw new ClassGenException("Number of arguments must be > 0 " + nargs); + if (nargs < 1 || nargs > Const.MAX_BYTE) { + throw new ClassGenException("Number of arguments out of range (1 - " + Const.MAX_BYTE + "): " + nargs); } this.nargs = nargs; } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -83,9 +89,9 @@ public int consumeStack(final ConstantPoolGen cpg) { // nargs is given in byte-c } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -96,7 +102,9 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * The count argument according to the Java Language Specification, Second Edition. + * The count argument according to the Java Language Specification, Second Edition. + * + * @return The count argument. */ public int getCount() { return nargs; @@ -109,7 +117,7 @@ public Class[] getExceptions() { } /** - * Read needed data (i.e., index) from file. + * Reads needed data (that is, index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -120,7 +128,7 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @return mnemonic for instruction with symbolic references resolved + * @return mnemonic for instruction with symbolic references resolved. */ @Override public String toString(final ConstantPool cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESPECIAL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESPECIAL.java index 4fdff394241c..0f68e6277a43 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESPECIAL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESPECIAL.java @@ -31,9 +31,9 @@ * INVOKESPECIAL - Invoke instance method; special handling for superclass, private and instance initialization method * invocations * - *
+ * 
  * Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
- * 
+ *
* * @see The * invokespecial instruction in The Java Virtual Machine Specification @@ -46,15 +46,20 @@ public class INVOKESPECIAL extends InvokeInstruction { INVOKESPECIAL() { } + /** + * Constructs an INVOKESPECIAL instruction. + * + * @param index index into constant pool. + */ public INVOKESPECIAL(final int index) { super(Const.INVOKESPECIAL, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -70,9 +75,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESTATIC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESTATIC.java index c9c7dcdab63c..c21f0e61b6a3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESTATIC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKESTATIC.java @@ -30,9 +30,9 @@ /** * INVOKESTATIC - Invoke a class (static) method * - *
+ * 
  * Stack: ..., [arg1, [arg2 ...]] -> ...
- * 
+ *
* * @see The invokestatic * instruction in The Java Virtual Machine Specification @@ -45,15 +45,20 @@ public class INVOKESTATIC extends InvokeInstruction { INVOKESTATIC() { } + /** + * Constructs an INVOKESTATIC instruction. + * + * @param index index into constant pool. + */ public INVOKESTATIC(final int index) { super(Const.INVOKESTATIC, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -69,9 +74,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEVIRTUAL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEVIRTUAL.java index 09961236e2dc..ebb5e6b376e7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEVIRTUAL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/INVOKEVIRTUAL.java @@ -30,9 +30,9 @@ /** * INVOKEVIRTUAL - Invoke instance method; dispatch based on class * - *
+ * 
  * Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
- * 
+ *
* * @see The * invokevirtual instruction in The Java Virtual Machine Specification @@ -45,15 +45,20 @@ public class INVOKEVIRTUAL extends InvokeInstruction { INVOKEVIRTUAL() { } + /** + * Constructs an INVOKEVIRTUAL instruction. + * + * @param index index into constant pool. + */ public INVOKEVIRTUAL(final int index) { super(Const.INVOKEVIRTUAL, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -69,9 +74,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IOR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IOR.java index 9f9ee094e2d8..af1197a5296f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IOR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IOR.java @@ -24,21 +24,24 @@ /** * IOR - Bitwise OR int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class IOR extends ArithmeticInstruction { + /** + * Constructs an IOR instruction. + */ public IOR() { super(com.sun.org.apache.bcel.internal.Const.IOR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IREM.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IREM.java index 34b11f42d0e8..a54282173bd6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IREM.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IREM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,10 +25,10 @@ /** * IREM - Remainder of int * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
- * @LastModified: Jan 2020 + *
+ * @LastModified: Nov 2026 */ public class IREM extends ArithmeticInstruction implements ExceptionThrower { @@ -41,9 +41,9 @@ public IREM() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -56,7 +56,7 @@ public void accept(final Visitor v) { } /** - * @return exceptions this instruction may cause + * @return exceptions this instruction may cause. */ @Override public Class[] getExceptions() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IRETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IRETURN.java index 80c3bfba744f..9b6e098bb86e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IRETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IRETURN.java @@ -24,9 +24,9 @@ /** * IRETURN - Return int from method * - *
+ * 
  * Stack: ..., value -> <empty>
- * 
+ *
*/ public class IRETURN extends ReturnInstruction { @@ -39,9 +39,9 @@ public IRETURN() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHL.java index 2e762db89695..87d9b5eb9afd 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHL.java @@ -24,21 +24,24 @@ /** * ISHL - Arithmetic shift left int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class ISHL extends ArithmeticInstruction { + /** + * Constructs an ISHL instruction. + */ public ISHL() { super(com.sun.org.apache.bcel.internal.Const.ISHL); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHR.java index c5e3906173a9..da45382c7ce3 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISHR.java @@ -24,21 +24,24 @@ /** * ISHR - Arithmetic shift right int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class ISHR extends ArithmeticInstruction { + /** + * Constructs an ISHR instruction. + */ public ISHR() { super(com.sun.org.apache.bcel.internal.Const.ISHR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISTORE.java index 76d8f930f8dc..bf710720ac18 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISTORE.java @@ -24,9 +24,9 @@ /** * ISTORE - Store int from stack into local variable * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
*/ public class ISTORE extends StoreInstruction { @@ -40,7 +40,7 @@ public class ISTORE extends StoreInstruction { /** * Store int into local variable * - * @param n index of local variable + * @param n index of local variable. */ public ISTORE(final int n) { super(com.sun.org.apache.bcel.internal.Const.ISTORE, com.sun.org.apache.bcel.internal.Const.ISTORE_0, n); @@ -48,9 +48,9 @@ public ISTORE(final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISUB.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISUB.java index 571751ce33e8..f04f025ac792 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISUB.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ISUB.java @@ -24,9 +24,9 @@ /** * ISUB - Substract ints * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
+ *
*/ public class ISUB extends ArithmeticInstruction { @@ -39,9 +39,9 @@ public ISUB() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IUSHR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IUSHR.java index 89236a0afa9c..46285e4ec93c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IUSHR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IUSHR.java @@ -24,21 +24,24 @@ /** * IUSHR - Logical shift right int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class IUSHR extends ArithmeticInstruction { + /** + * Constructs an IUSHR instruction. + */ public IUSHR() { super(com.sun.org.apache.bcel.internal.Const.IUSHR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IXOR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IXOR.java index 1006f3d3841a..59a80d3b8455 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IXOR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IXOR.java @@ -24,21 +24,24 @@ /** * IXOR - Bitwise XOR int * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class IXOR extends ArithmeticInstruction { + /** + * Constructs an IXOR instruction. + */ public IXOR() { super(com.sun.org.apache.bcel.internal.Const.IXOR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IfInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IfInstruction.java index b4be83ebdc2c..a219bd6de6c2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IfInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IfInstruction.java @@ -33,15 +33,19 @@ public abstract class IfInstruction extends BranchInstruction implements StackCo } /** - * @param opcode opcode of instruction - * @param target Target instruction to branch to + * Constructs an IfInstruction. + * + * @param opcode opcode of instruction. + * @param target Target instruction to branch to. */ protected IfInstruction(final short opcode, final InstructionHandle target) { super(opcode, target); } /** - * @return negation of instruction, e.g. IFEQ.negate() == IFNE + * Gets the negation of this instruction. + * + * @return negation of instruction, for example IFEQ.negate() == IFNE. */ public abstract IfInstruction negate(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IndexedInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IndexedInstruction.java index f9846297614a..569619f8490b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IndexedInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/IndexedInstruction.java @@ -22,11 +22,21 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Denote entity that refers to an index, e.g. local variable instructions, RET, CPInstruction, etc. + * Denote entity that refers to an index, for example local variable instructions, RET, CPInstruction, etc. */ public interface IndexedInstruction { + /** + * Gets the index. + * + * @return The index. + */ int getIndex(); + /** + * Sets the index. + * + * @param index The index. + */ void setIndex(int index); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Instruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Instruction.java index a7124409f124..4cc1d15d9291 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Instruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Instruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -19,6 +19,7 @@ */ package com.sun.org.apache.bcel.internal.generic; +import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -29,7 +30,7 @@ /** * Abstract super class for all Java byte codes. * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public abstract class Instruction implements Cloneable { @@ -40,7 +41,7 @@ public abstract class Instruction implements Cloneable { /** * Gets Comparator object used in the equals() method to determine equality of instructions. * - * @return currently used comparator for equals() + * @return currently used comparator for equals(). * @deprecated (6.0) use the built in comparator, or wrap this class in another object that implements these methods */ @Deprecated @@ -49,10 +50,20 @@ public static InstructionComparator getComparator() { } /** - * Tests if the value can fit in a byte (signed) + * Tests if the value can fit in a non-negative short. * - * @param value the value to check - * @return true if the value is in range + * @param value The value to check. + * @return true if the value is in range. + */ + static boolean isNonNegativeUShort(final int value) { + return value >= 0 && value <= Const.MAX_SHORT; + } + + /** + * Tests if the value can fit in a byte (signed). + * + * @param value The value to check. + * @return true if the value is in range. * @since 6.0 */ public static boolean isValidByte(final int value) { @@ -60,23 +71,37 @@ public static boolean isValidByte(final int value) { } /** - * Tests if the value can fit in a short (signed) + * Tests if the value can fit in a short (signed). * - * @param value the value to check - * @return true if the value is in range + * @param value The value to check. + * @return true if the value is in range. * @since 6.0 */ public static boolean isValidShort(final int value) { return value >= Short.MIN_VALUE && value <= Short.MAX_VALUE; } + /** + * Reads an instruction from (byte code) input stream and return the appropriate object. + * + * @param code byte array containing the instruction to read. + * @return instruction object being read. + * @throws IOException Thrown when an I/O exception of some sort has occurred. + */ + static Instruction readInstruction(final byte[] code) throws IOException { + try (ByteSequence bytes = new ByteSequence(code)) { + return readInstruction(bytes); + } + } + /** * Reads an instruction from (byte code) input stream and return the appropriate object. *

* If the Instruction is defined in {@link InstructionConst}, then the singleton instance is returned. *

- * @param bytes input stream bytes - * @return instruction object being read + * + * @param bytes input stream bytes. + * @return instruction object being read. * @throws IOException Thrown when an I/O exception of some sort has occurred. * @see InstructionConst#getInstruction(int) */ @@ -93,7 +118,6 @@ public static Instruction readInstruction(final ByteSequence bytes) throws IOExc if (instruction != null) { return instruction; // Used predefined immutable object, if available } - switch (opcode) { case Const.BIPUSH: obj = new BIPUSH(); @@ -402,6 +426,7 @@ public static Instruction readInstruction(final ByteSequence bytes) throws IOExc /** * Sets comparator to be used for equals(). * + * @param c The comparator. * @deprecated (6.0) use the built in comparator, or wrap this class in another object that implements these methods */ @Deprecated @@ -427,16 +452,22 @@ public static void setComparator(final InstructionComparator c) { Instruction() { } + /** + * Constructs an Instruction. + * + * @param opcode The opcode. + * @param length The instruction length. + */ public Instruction(final short opcode, final short length) { - this.length = length; this.opcode = opcode; + this.length = length; } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ public abstract void accept(Visitor v); @@ -444,8 +475,9 @@ public Instruction(final short opcode, final short length) { * This method also gives right results for instructions whose effect on the stack depends on the constant pool entry * they reference. * - * @return Number of words consumed from stack by this instruction, or Constants.UNPREDICTABLE, if this can not be - * computed statically + * @param cpg The constant pool generator. + * @return Number of words consumed from stack by this instruction, or Constants.UNPREDICTABLE, if this cannot be + * computed statically. */ public int consumeStack(final ConstantPoolGen cpg) { return Const.getConsumeStack(opcode); @@ -455,8 +487,8 @@ public int consumeStack(final ConstantPoolGen cpg) { * Use with caution, since 'BranchInstruction's have a 'target' reference which is not copied correctly (only basic * types are). This also applies for 'Select' instructions with their multiple branch targets. * + * @return (shallow) copy of an instruction. * @see BranchInstruction - * @return (shallow) copy of an instruction */ public Instruction copy() { Instruction i = null; @@ -482,17 +514,31 @@ void dispose() { /** * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public void dump(final DataOutputStream out) throws IOException { out.writeByte(opcode); // Common for all instructions } + /** + * Dumps this instruction to a byte array. + * + * @return the byte array containing the dumped instruction + * @throws IOException Thrown if an I/O error occurs. + */ + byte[] dumpToByteArray() throws IOException { + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (DataOutputStream dos = new DataOutputStream(bos)) { + dump(dos); + } + return bos.toByteArray(); + } + /** * Tests for equality, delegated to comparator * - * @return true if that is an Instruction and has the same opcode + * @return true if that is an Instruction and has the same opcode. */ @Override public boolean equals(final Object that) { @@ -500,21 +546,27 @@ public boolean equals(final Object that) { } /** - * @return length (in bytes) of instruction + * Gets the length (in bytes) of instruction. + * + * @return length (in bytes) of instruction. */ public int getLength() { return length; } /** - * @return name of instruction, i.e., opcode name + * Gets the name of instruction, that is, opcode name. + * + * @return name of instruction, that is, opcode name. */ public String getName() { return Const.getOpcodeName(opcode); } /** - * @return this instructions opcode + * Gets this instruction's opcode. + * + * @return this instruction's opcode. */ public short getOpcode() { return opcode; @@ -523,7 +575,7 @@ public short getOpcode() { /** * Gets the hashCode of this object. * - * @return the hashCode + * @return The hashCode. * @since 6.0 */ @Override @@ -532,11 +584,11 @@ public int hashCode() { } /** - * Reads needed data (e.g. index) from file. + * Reads needed data (for example index) from file. * - * @param bytes byte sequence to read from - * @param wide "wide" instruction flag - * @throws IOException may be thrown if the implementation needs to read data from the file + * @param bytes byte sequence to read from. + * @param wide "wide" instruction flag. + * @throws IOException Thrown if the implementation needs to read data from the file */ @SuppressWarnings("unused") // thrown by subclasses protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -546,8 +598,9 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws * This method also gives right results for instructions whose effect on the stack depends on the constant pool entry * they reference. * - * @return Number of words produced onto stack by this instruction, or Constants.UNPREDICTABLE, if this can not be - * computed statically + * @param cpg The constant pool generator. + * @return Number of words produced onto stack by this instruction, or Constants.UNPREDICTABLE, if this cannot be + * computed statically. */ public int produceStack(final ConstantPoolGen cpg) { return Const.getProduceStack(opcode); @@ -563,14 +616,14 @@ final void setLength(final int length) { } /** - * Needed in readInstruction and subclasses in this package + * Needed in readInstruction and subclasses in this package. */ void setOpcode(final short opcode) { this.opcode = opcode; } /** - * @return mnemonic for instruction in verbose format + * @return mnemonic for instruction in verbose format. */ @Override public String toString() { @@ -582,8 +635,8 @@ public String toString() { * * <name of opcode> "["<opcode number>"]" "("<length of instruction>")" * - * @param verbose long/short format switch - * @return mnemonic for instruction + * @param verbose long/short format switch. + * @return mnemonic for instruction. */ public String toString(final boolean verbose) { if (verbose) { @@ -593,7 +646,10 @@ public String toString(final boolean verbose) { } /** - * @return mnemonic for instruction with sumbolic references resolved + * Gets the mnemonic for instruction with symbolic references resolved. + * + * @param cp The constant pool. + * @return mnemonic for instruction with symbolic references resolved. */ public String toString(final ConstantPool cp) { return toString(false); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionComparator.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionComparator.java index 9f806a2d3d71..e5adabf11eac 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionComparator.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionComparator.java @@ -34,6 +34,9 @@ */ public interface InstructionComparator { + /** + * Default instruction comparator. + */ InstructionComparator DEFAULT = (i1, i2) -> { if (i1.getOpcode() == i2.getOpcode()) { if (i1 instanceof BranchInstruction) { @@ -56,5 +59,12 @@ public interface InstructionComparator { return false; }; + /** + * Compares two instructions for equality. + * + * @param i1 The first instruction. + * @param i2 The second instruction. + * @return true if the instructions are equal, false otherwise. + */ boolean equals(Instruction i1, Instruction i2); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionConst.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionConst.java index 7b95bfc99b17..3941b312e53b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionConst.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionConst.java @@ -26,147 +26,381 @@ /** * Contains shareable instruction objects. *

- * In order to save memory you can use some instructions multiply, since they have an immutable state and are directly - * derived from Instruction. I.e. they have no instance fields that could be changed. Since some of these instructions - * like ICONST_0 occur very frequently this can save a lot of time and space. This feature is an adaptation of the - * FlyWeight design pattern, we just use an array instead of a factory. + * In order to save memory you can use some instructions multiply, since they have an immutable state and are directly derived from Instruction. I.e. they have + * no instance fields that could be changed. Since some of these instructions like ICONST_0 occur very frequently this can save a lot of time and space. This + * feature is an adaptation of the FlyWeight design pattern, we just use an array instead of a factory. *

*

- * The Instructions can also accessed directly under their names, so it's possible to write - * il.append(Instruction.ICONST_0); + * The Instructions can also accessed directly under their names, so it's possible to write il.append(Instruction.ICONST_0); *

*/ public final class InstructionConst { /** - * Predefined instruction objects. - * - * NOTE these are not currently immutable, because Instruction has mutable protected fields opcode and length. + * Predefined instruction objects. NOTE these are not currently immutable, because Instruction has mutable protected fields opcode and length. */ + + /** NOP instruction. */ public static final Instruction NOP = new NOP(); + + /** ACONST_NULL instruction. */ public static final Instruction ACONST_NULL = new ACONST_NULL(); + + /** ICONST_M1 instruction. */ public static final Instruction ICONST_M1 = new ICONST(-1); + + /** ICONST_0 instruction. */ public static final Instruction ICONST_0 = new ICONST(0); + + /** ICONST_1 instruction. */ public static final Instruction ICONST_1 = new ICONST(1); + + /** ICONST_2 instruction. */ public static final Instruction ICONST_2 = new ICONST(2); + + /** ICONST_3 instruction. */ public static final Instruction ICONST_3 = new ICONST(3); + + /** ICONST_4 instruction. */ public static final Instruction ICONST_4 = new ICONST(4); + + /** ICONST_5 instruction. */ public static final Instruction ICONST_5 = new ICONST(5); + + /** LCONST_0 instruction. */ public static final Instruction LCONST_0 = new LCONST(0); + + /** LCONST_1 instruction. */ public static final Instruction LCONST_1 = new LCONST(1); + + /** FCONST_0 instruction. */ public static final Instruction FCONST_0 = new FCONST(0); + + /** FCONST_1 instruction. */ public static final Instruction FCONST_1 = new FCONST(1); + + /** FCONST_2 instruction. */ public static final Instruction FCONST_2 = new FCONST(2); + + /** DCONST_0 instruction. */ public static final Instruction DCONST_0 = new DCONST(0); + + /** DCONST_1 instruction. */ public static final Instruction DCONST_1 = new DCONST(1); + + /** IALOAD instruction. */ public static final ArrayInstruction IALOAD = new IALOAD(); + + /** LALOAD instruction. */ public static final ArrayInstruction LALOAD = new LALOAD(); + + /** FALOAD instruction. */ public static final ArrayInstruction FALOAD = new FALOAD(); + + /** DALOAD instruction. */ public static final ArrayInstruction DALOAD = new DALOAD(); + + /** AALOAD instruction. */ public static final ArrayInstruction AALOAD = new AALOAD(); + + /** BALOAD instruction. */ public static final ArrayInstruction BALOAD = new BALOAD(); + + /** CALOAD instruction. */ public static final ArrayInstruction CALOAD = new CALOAD(); + + /** SALOAD instruction. */ public static final ArrayInstruction SALOAD = new SALOAD(); + + /** IASTORE instruction. */ public static final ArrayInstruction IASTORE = new IASTORE(); + + /** LASTORE instruction. */ public static final ArrayInstruction LASTORE = new LASTORE(); + + /** FASTORE instruction. */ public static final ArrayInstruction FASTORE = new FASTORE(); + + /** DASTORE instruction. */ public static final ArrayInstruction DASTORE = new DASTORE(); + + /** AASTORE instruction. */ public static final ArrayInstruction AASTORE = new AASTORE(); + + /** BASTORE instruction. */ public static final ArrayInstruction BASTORE = new BASTORE(); + + /** CASTORE instruction. */ public static final ArrayInstruction CASTORE = new CASTORE(); + + /** SASTORE instruction. */ public static final ArrayInstruction SASTORE = new SASTORE(); + + /** POP instruction. */ public static final StackInstruction POP = new POP(); + + /** POP2 instruction. */ public static final StackInstruction POP2 = new POP2(); + + /** DUP instruction. */ public static final StackInstruction DUP = new DUP(); + + /** DUP_X1 instruction. */ public static final StackInstruction DUP_X1 = new DUP_X1(); + + /** DUP_X2 instruction. */ public static final StackInstruction DUP_X2 = new DUP_X2(); + + /** DUP2 instruction. */ public static final StackInstruction DUP2 = new DUP2(); + + /** DUP2_X1 instruction. */ public static final StackInstruction DUP2_X1 = new DUP2_X1(); + + /** DUP2_X2 instruction. */ public static final StackInstruction DUP2_X2 = new DUP2_X2(); + + /** SWAP instruction. */ public static final StackInstruction SWAP = new SWAP(); + + /** IADD instruction. */ public static final ArithmeticInstruction IADD = new IADD(); + + /** LADD instruction. */ public static final ArithmeticInstruction LADD = new LADD(); + + /** FADD instruction. */ public static final ArithmeticInstruction FADD = new FADD(); + + /** DADD instruction. */ public static final ArithmeticInstruction DADD = new DADD(); + + /** ISUB instruction. */ public static final ArithmeticInstruction ISUB = new ISUB(); + + /** LSUB instruction. */ public static final ArithmeticInstruction LSUB = new LSUB(); + + /** FSUB instruction. */ public static final ArithmeticInstruction FSUB = new FSUB(); + + /** DSUB instruction. */ public static final ArithmeticInstruction DSUB = new DSUB(); + + /** IMUL instruction. */ public static final ArithmeticInstruction IMUL = new IMUL(); + + /** LMUL instruction. */ public static final ArithmeticInstruction LMUL = new LMUL(); + + /** FMUL instruction. */ public static final ArithmeticInstruction FMUL = new FMUL(); + + /** DMUL instruction. */ public static final ArithmeticInstruction DMUL = new DMUL(); + + /** IDIV instruction. */ public static final ArithmeticInstruction IDIV = new IDIV(); + + /** LDIV instruction. */ public static final ArithmeticInstruction LDIV = new LDIV(); + + /** FDIV instruction. */ public static final ArithmeticInstruction FDIV = new FDIV(); + + /** DDIV instruction. */ public static final ArithmeticInstruction DDIV = new DDIV(); + + /** IREM instruction. */ public static final ArithmeticInstruction IREM = new IREM(); + + /** LREM instruction. */ public static final ArithmeticInstruction LREM = new LREM(); + + /** FREM instruction. */ public static final ArithmeticInstruction FREM = new FREM(); + + /** DREM instruction. */ public static final ArithmeticInstruction DREM = new DREM(); + + /** INEG instruction. */ public static final ArithmeticInstruction INEG = new INEG(); + + /** LNEG instruction. */ public static final ArithmeticInstruction LNEG = new LNEG(); + + /** FNEG instruction. */ public static final ArithmeticInstruction FNEG = new FNEG(); + + /** DNEG instruction. */ public static final ArithmeticInstruction DNEG = new DNEG(); + + /** ISHL instruction. */ public static final ArithmeticInstruction ISHL = new ISHL(); + + /** LSHL instruction. */ public static final ArithmeticInstruction LSHL = new LSHL(); + + /** ISHR instruction. */ public static final ArithmeticInstruction ISHR = new ISHR(); + + /** LSHR instruction. */ public static final ArithmeticInstruction LSHR = new LSHR(); + + /** IUSHR instruction. */ public static final ArithmeticInstruction IUSHR = new IUSHR(); + + /** LUSHR instruction. */ public static final ArithmeticInstruction LUSHR = new LUSHR(); + + /** IAND instruction. */ public static final ArithmeticInstruction IAND = new IAND(); + + /** LAND instruction. */ public static final ArithmeticInstruction LAND = new LAND(); + + /** IOR instruction. */ public static final ArithmeticInstruction IOR = new IOR(); + + /** LOR instruction. */ public static final ArithmeticInstruction LOR = new LOR(); + + /** IXOR instruction. */ public static final ArithmeticInstruction IXOR = new IXOR(); + + /** LXOR instruction. */ public static final ArithmeticInstruction LXOR = new LXOR(); + + /** I2L instruction. */ public static final ConversionInstruction I2L = new I2L(); + + /** I2F instruction. */ public static final ConversionInstruction I2F = new I2F(); + + /** I2D instruction. */ public static final ConversionInstruction I2D = new I2D(); + + /** L2I instruction. */ public static final ConversionInstruction L2I = new L2I(); + + /** L2F instruction. */ public static final ConversionInstruction L2F = new L2F(); + + /** L2D instruction. */ public static final ConversionInstruction L2D = new L2D(); + + /** F2I instruction. */ public static final ConversionInstruction F2I = new F2I(); + + /** F2L instruction. */ public static final ConversionInstruction F2L = new F2L(); + + /** F2D instruction. */ public static final ConversionInstruction F2D = new F2D(); + + /** D2I instruction. */ public static final ConversionInstruction D2I = new D2I(); + + /** D2L instruction. */ public static final ConversionInstruction D2L = new D2L(); + + /** D2F instruction. */ public static final ConversionInstruction D2F = new D2F(); + + /** I2B instruction. */ public static final ConversionInstruction I2B = new I2B(); + + /** I2C instruction. */ public static final ConversionInstruction I2C = new I2C(); + + /** I2S instruction. */ public static final ConversionInstruction I2S = new I2S(); + + /** LCMP instruction. */ public static final Instruction LCMP = new LCMP(); + + /** FCMPL instruction. */ public static final Instruction FCMPL = new FCMPL(); + + /** FCMPG instruction. */ public static final Instruction FCMPG = new FCMPG(); + + /** DCMPL instruction. */ public static final Instruction DCMPL = new DCMPL(); + + /** DCMPG instruction. */ public static final Instruction DCMPG = new DCMPG(); + + /** IRETURN instruction. */ public static final ReturnInstruction IRETURN = new IRETURN(); + + /** LRETURN instruction. */ public static final ReturnInstruction LRETURN = new LRETURN(); + + /** FRETURN instruction. */ public static final ReturnInstruction FRETURN = new FRETURN(); + + /** DRETURN instruction. */ public static final ReturnInstruction DRETURN = new DRETURN(); + + /** ARETURN instruction. */ public static final ReturnInstruction ARETURN = new ARETURN(); + + /** RETURN instruction. */ public static final ReturnInstruction RETURN = new RETURN(); + + /** ARRAYLENGTH instruction. */ public static final Instruction ARRAYLENGTH = new ARRAYLENGTH(); + + /** ATHROW instruction. */ public static final Instruction ATHROW = new ATHROW(); + + /** MONITORENTER instruction. */ public static final Instruction MONITORENTER = new MONITORENTER(); + + /** MONITOREXIT instruction. */ public static final Instruction MONITOREXIT = new MONITOREXIT(); /** - * You can use these constants in multiple places safely, if you can guarantee that you will never alter their internal - * values, e.g. call setIndex(). + * You can use these constants in multiple places safely, if you can guarantee that you will never alter their internal values, for example call setIndex(). + * THIS instruction (ALOAD_0) */ public static final LocalVariableInstruction THIS = new ALOAD(0); + + /** ALOAD_0 instruction (same as THIS). */ public static final LocalVariableInstruction ALOAD_0 = THIS; + + /** ALOAD_1 instruction. */ public static final LocalVariableInstruction ALOAD_1 = new ALOAD(1); + + /** ALOAD_2 instruction. */ public static final LocalVariableInstruction ALOAD_2 = new ALOAD(2); + + /** ILOAD_0 instruction. */ public static final LocalVariableInstruction ILOAD_0 = new ILOAD(0); + + /** ILOAD_1 instruction. */ public static final LocalVariableInstruction ILOAD_1 = new ILOAD(1); + + /** ILOAD_2 instruction. */ public static final LocalVariableInstruction ILOAD_2 = new ILOAD(2); + + /** ASTORE_0 instruction. */ public static final LocalVariableInstruction ASTORE_0 = new ASTORE(0); + + /** ASTORE_1 instruction. */ public static final LocalVariableInstruction ASTORE_1 = new ASTORE(1); + + /** ASTORE_2 instruction. */ public static final LocalVariableInstruction ASTORE_2 = new ASTORE(2); + + /** ISTORE_0 instruction. */ public static final LocalVariableInstruction ISTORE_0 = new ISTORE(0); + + /** ISTORE_1 instruction. */ public static final LocalVariableInstruction ISTORE_1 = new ISTORE(1); + + /** ISTORE_2 instruction. */ public static final LocalVariableInstruction ISTORE_2 = new ISTORE(2); /** @@ -287,8 +521,8 @@ public final class InstructionConst { /** * Gets the Instruction. * - * @param index the index, e.g. {@link Const#RETURN} - * @return the entry from the private INSTRUCTIONS table + * @param index The index, for example {@link Const#RETURN}. + * @return The entry from the private INSTRUCTIONS table. */ public static Instruction getInstruction(final int index) { return INSTRUCTIONS[index]; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionFactory.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionFactory.java index 3c4b3e9f9da6..6fc6777d1e3e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionFactory.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionFactory.java @@ -22,7 +22,7 @@ import com.sun.org.apache.bcel.internal.Const; /** - * Instances of this class may be used, e.g., to generate typed versions of instructions. Its main purpose is to be used + * Instances of this class may be used, for example, to generate typed versions of instructions. Its main purpose is to be used * as the byte code generating backend of a compiler. You can subclass it to add your own create methods. *

* Note: The static createXXX methods return singleton instances from the {@link InstructionConst} class. @@ -71,7 +71,10 @@ private static final class MethodObject { new MethodObject(FQCN_STRING_BUFFER, APPEND, Type.STRINGBUFFER, new Type[] { Type.LONG })}; /** - * @param type type of elements of array, i.e., array.getElementType() + * Creates an array load instruction for the given type. + * + * @param type type of elements of array, that is, array.getElementType(). + * @return The array load instruction. */ public static ArrayInstruction createArrayLoad(final Type type) { switch (type.getType()) { @@ -99,7 +102,10 @@ public static ArrayInstruction createArrayLoad(final Type type) { } /** - * @param type type of elements of array, i.e., array.getElementType() + * Creates an array store instruction for the given type. + * + * @param type type of elements of array, that is, array.getElementType(). + * @return The array store instruction. */ public static ArrayInstruction createArrayStore(final Type type) { switch (type.getType()) { @@ -190,10 +196,10 @@ private static ArithmeticInstruction createBinaryIntOp(final char first, final S /** * Create an invokedynamic instruction. * - * @param bootstrap_index index into the bootstrap_methods array - * @param name name of the called method - * @param ret_type return type of method - * @param argTypes argument types of method + * @param bootstrap_index index into the bootstrap_methods array. + * @param name name of the called method. + * @param ret_type return type of method. + * @param argTypes argument types of method. * @see Const */ @@ -238,6 +244,8 @@ private static ArithmeticInstruction createBinaryLongOp(final char first, final * Create binary operation for simple basic types, such as int and float. * * @param op operation, such as "+", "*", "<<", etc. + * @param type The operand type. + * @return The binary arithmetic instruction. */ public static ArithmeticInstruction createBinaryOperation(final String op, final Type type) { final char first = op.charAt(0); @@ -261,6 +269,10 @@ public static ArithmeticInstruction createBinaryOperation(final String op, final /** * Create branch instruction by given opcode, except LOOKUPSWITCH and TABLESWITCH. For those you should use the SWITCH * compound instruction. + * + * @param opcode The branch opcode. + * @param target The target instruction handle. + * @return The branch instruction. */ public static BranchInstruction createBranchInstruction(final short opcode, final InstructionHandle target) { switch (opcode) { @@ -310,28 +322,41 @@ public static BranchInstruction createBranchInstruction(final short opcode, fina } /** - * @param size size of operand, either 1 (int, e.g.) or 2 (double) + * Creates a DUP instruction. + * + * @param size size of operand, either 1 (int, for example) or 2 (double). + * @return The DUP instruction. */ public static StackInstruction createDup(final int size) { return size == 2 ? InstructionConst.DUP2 : InstructionConst.DUP; } /** - * @param size size of operand, either 1 (int, e.g.) or 2 (double) + * Creates a DUP_X1 instruction. + * + * @param size size of operand, either 1 (int, for example) or 2 (double). + * @return The DUP instruction. */ public static StackInstruction createDup_1(final int size) { return size == 2 ? InstructionConst.DUP2_X1 : InstructionConst.DUP_X1; } /** - * @param size size of operand, either 1 (int, e.g.) or 2 (double) + * Creates a DUP_X2 instruction. + * + * @param size size of operand, either 1 (int, for example) or 2 (double). + * @return The DUP instruction. */ public static StackInstruction createDup_2(final int size) { return size == 2 ? InstructionConst.DUP2_X2 : InstructionConst.DUP_X2; } /** - * @param index index of local variable + * Creates a load instruction for the given type. + * + * @param type The variable type. + * @param index index of local variable. + * @return The load instruction. */ public static LocalVariableInstruction createLoad(final Type type, final int index) { switch (type.getType()) { @@ -356,7 +381,10 @@ public static LocalVariableInstruction createLoad(final Type type, final int ind } /** - * Create "null" value for reference types, 0 for basic types like int + * Create "null" value for reference types, 0 for basic types like int. + * + * @param type The type. + * @return The null or zero instruction. */ public static Instruction createNull(final Type type) { switch (type.getType()) { @@ -383,14 +411,20 @@ public static Instruction createNull(final Type type) { } /** - * @param size size of operand, either 1 (int, e.g.) or 2 (double) + * Creates a pop instruction. + * + * @param size size of operand, either 1 (int, for example) or 2 (double). + * @return The pop instruction. */ public static StackInstruction createPop(final int size) { return size == 2 ? InstructionConst.POP2 : InstructionConst.POP; } /** - * Create typed return + * Create typed return. + * + * @param type The return type. + * @return The return instruction. */ public static ReturnInstruction createReturn(final Type type) { switch (type.getType()) { @@ -417,7 +451,11 @@ public static ReturnInstruction createReturn(final Type type) { } /** - * @param index index of local variable + * Creates a store instruction. + * + * @param type The variable type. + * @param index index of local variable. + * @return The store instruction. */ public static LocalVariableInstruction createStore(final Type type, final int index) { switch (type.getType()) { @@ -442,7 +480,9 @@ public static LocalVariableInstruction createStore(final Type type, final int in } /** - * Create reference to 'this' + * Create reference to 'this'. + * + * @return reference to 'this'. */ public static Instruction createThis() { return new ALOAD(0); @@ -465,24 +505,40 @@ private static boolean isString(final Type type) { protected ConstantPoolGen cp; /** - * Initialize with ClassGen object + * Initialize with ClassGen object. + * + * @param cg The class generator. */ public InstructionFactory(final ClassGen cg) { this(cg, cg.getConstantPool()); } + /** + * Constructs an InstructionFactory. + * + * @param cg The class generator. + * @param cp The constant pool generator. + */ public InstructionFactory(final ClassGen cg, final ConstantPoolGen cp) { this.cg = cg; this.cp = cp; } /** - * Initialize just with ConstantPoolGen object + * Initialize just with ConstantPoolGen object. + * + * @param cp The constant pool generator. */ public InstructionFactory(final ConstantPoolGen cp) { this(null, cp); } + /** + * Creates an append instruction for the given type. + * + * @param type The type to append. + * @return The append instruction. + */ public Instruction createAppend(final Type type) { final byte t = type.getType(); if (isString(type)) { @@ -507,8 +563,12 @@ public Instruction createAppend(final Type type) { } /** - * Create conversion operation for two stack operands, this may be an I2C, instruction, e.g., if the operands are basic + * Create conversion operation for two stack operands, this may be an I2C, instruction, for example, if the operands are basic * types and CHECKCAST if they are reference types. + * + * @param srcType The source type. + * @param destType The destination type. + * @return The conversion instruction. */ public Instruction createCast(final Type srcType, final Type destType) { if (srcType instanceof BasicType && destType instanceof BasicType) { @@ -520,7 +580,7 @@ public Instruction createCast(final Type srcType, final Type destType) { final String name = "com.sun.org.apache.bcel.internal.generic." + SHORT_NAMES[src - Const.T_CHAR] + "2" + SHORT_NAMES[dest - Const.T_CHAR]; Instruction i = null; try { - i = (Instruction) Class.forName(name).getDeclaredConstructor().newInstance();; + i = (Instruction) Class.forName(name).getConstructor().newInstance(); } catch (final Exception e) { throw new IllegalArgumentException("Could not find instruction: " + name, e); } @@ -535,6 +595,12 @@ public Instruction createCast(final Type srcType, final Type destType) { return new CHECKCAST(cp.addClass(((ObjectType) destType).getClassName())); } + /** + * Creates a CHECKCAST instruction. + * + * @param t The reference type. + * @return The CHECKCAST instruction. + */ public CHECKCAST createCheckCast(final ReferenceType t) { if (t instanceof ArrayType) { return new CHECKCAST(cp.addArrayClass((ArrayType) t)); @@ -545,10 +611,11 @@ public CHECKCAST createCheckCast(final ReferenceType t) { /** * Uses PUSH to push a constant value onto the stack. * - * @param value must be of type Number, Boolean, Character or String + * @param value must be of type Number, Boolean, Character or String. + * @return The instruction. */ public Instruction createConstant(final Object value) { - PUSH push; + final PUSH push; if (value instanceof Number) { push = new PUSH(cp, (Number) value); } else if (value instanceof String) { @@ -566,16 +633,16 @@ public Instruction createConstant(final Object value) { /** * Create a field instruction. * - * @param className name of the accessed class - * @param name name of the referenced field - * @param type type of field - * @param kind how to access, i.e., GETFIELD, PUTFIELD, GETSTATIC, PUTSTATIC + * @param className class name containing the field. + * @param name name of the referenced field. + * @param type type of field. + * @param kind how to access, that is, GETFIELD, PUTFIELD, GETSTATIC, PUTSTATIC. + * @return A field instruction. * @see Const */ public FieldInstruction createFieldAccess(final String className, final String name, final Type type, final short kind) { - int index; final String signature = type.getSignature(); - index = cp.addFieldref(className, name, signature); + final int index = cp.addFieldref(className, name, signature); switch (kind) { case Const.GETFIELD: return new GETFIELD(index); @@ -590,14 +657,36 @@ public FieldInstruction createFieldAccess(final String className, final String n } } + /** + * Creates a GETFIELD instruction. + * + * @param className The class name. + * @param name The field name. + * @param t The field type. + * @return The GETFIELD instruction. + */ public GETFIELD createGetField(final String className, final String name, final Type t) { return new GETFIELD(cp.addFieldref(className, name, t.getSignature())); } + /** + * Creates a GETSTATIC instruction. + * + * @param className The class name. + * @param name The field name. + * @param t The field type. + * @return The GETSTATIC instruction. + */ public GETSTATIC createGetStatic(final String className, final String name, final Type t) { return new GETSTATIC(cp.addFieldref(className, name, t.getSignature())); } + /** + * Creates an INSTANCEOF instruction. + * + * @param t The reference type. + * @return The INSTANCEOF instruction. + */ public INSTANCEOF createInstanceOf(final ReferenceType t) { if (t instanceof ArrayType) { return new INSTANCEOF(cp.addArrayClass((ArrayType) t)); @@ -612,11 +701,12 @@ private InvokeInstruction createInvoke(final MethodObject m, final short kind) { /** * Create an invoke instruction. (Except for invokedynamic.) * - * @param className name of the called class - * @param name name of the called method - * @param retType return type of method - * @param argTypes argument types of method - * @param kind how to invoke, i.e., INVOKEINTERFACE, INVOKESTATIC, INVOKEVIRTUAL, or INVOKESPECIAL + * @param className name of the called class. + * @param name name of the called method. + * @param retType return type of method. + * @param argTypes argument types of method. + * @param kind how to invoke, that is, INVOKEINTERFACE, INVOKESTATIC, INVOKEVIRTUAL, or INVOKESPECIAL. + * @return The invoke instruction. * @see Const */ public InvokeInstruction createInvoke(final String className, final String name, final Type retType, final Type[] argTypes, final short kind) { @@ -626,12 +716,12 @@ public InvokeInstruction createInvoke(final String className, final String name, /** * Create an invoke instruction. (Except for invokedynamic.) * - * @param className name of the called class - * @param name name of the called method - * @param retType return type of method - * @param argTypes argument types of method - * @param kind how to invoke: INVOKEINTERFACE, INVOKESTATIC, INVOKEVIRTUAL, or INVOKESPECIAL - * @param useInterface force use of InterfaceMethodref + * @param className name of the called class. + * @param name name of the called method. + * @param retType return type of method. + * @param argTypes argument types of method. + * @param kind how to invoke: INVOKEINTERFACE, INVOKESTATIC, INVOKEVIRTUAL, or INVOKESPECIAL. + * @param useInterface force use of InterfaceMethodref. * @return A new InvokeInstruction. * @since 6.5.0 */ @@ -641,7 +731,7 @@ public InvokeInstruction createInvoke(final String className, final String name, && kind != Const.INVOKEDYNAMIC) { throw new IllegalArgumentException("Unknown invoke kind: " + kind); } - int index; + final int index; int nargs = 0; final String signature = Type.getMethodSignature(retType, argTypes); if (argTypes != null) { @@ -671,10 +761,22 @@ public InvokeInstruction createInvoke(final String className, final String name, } } + /** + * Creates a NEW instruction. + * + * @param t The object type. + * @return The NEW instruction. + */ public NEW createNew(final ObjectType t) { return new NEW(cp.addClass(t)); } + /** + * Creates a NEW instruction. + * + * @param s The class name. + * @return The NEW instruction. + */ public NEW createNew(final String s) { return createNew(ObjectType.getInstance(s)); } @@ -682,7 +784,9 @@ public NEW createNew(final String s) { /** * Create new array of given size and type. * - * @return an instruction that creates the corresponding array at runtime, i.e. is an AllocationInstruction + * @param t The array element type. + * @param dim The array dimensions. + * @return An instruction that creates the corresponding array at runtime, for example is an AllocationInstruction. */ public Instruction createNewArray(final Type t, final short dim) { if (dim == 1) { @@ -694,7 +798,7 @@ public Instruction createNewArray(final Type t, final short dim) { } return new NEWARRAY(t.getType()); } - ArrayType at; + final ArrayType at; if (t instanceof ArrayType) { at = (ArrayType) t; } else { @@ -706,7 +810,8 @@ public Instruction createNewArray(final Type t, final short dim) { /** * Create a call to the most popular System.out.println() method. * - * @param s the string to print + * @param s The string to print. + * @return The instruction list. */ public InstructionList createPrintln(final String s) { final InstructionList il = new InstructionList(); @@ -717,26 +822,62 @@ public InstructionList createPrintln(final String s) { return il; } + /** + * Creates a PUTFIELD instruction. + * + * @param className The class name. + * @param name The field name. + * @param t The field type. + * @return The PUTFIELD instruction. + */ public PUTFIELD createPutField(final String className, final String name, final Type t) { return new PUTFIELD(cp.addFieldref(className, name, t.getSignature())); } + /** + * Creates a PUTSTATIC instruction. + * + * @param className The class name. + * @param name The field name. + * @param t The field type. + * @return The PUTSTATIC instruction. + */ public PUTSTATIC createPutStatic(final String className, final String name, final Type t) { return new PUTSTATIC(cp.addFieldref(className, name, t.getSignature())); } + /** + * Gets the class generator. + * + * @return The class generator. + */ public ClassGen getClassGen() { return cg; } + /** + * Gets the constant pool generator. + * + * @return The constant pool generator. + */ public ConstantPoolGen getConstantPool() { return cp; } + /** + * Sets the class generator. + * + * @param c The class generator. + */ public void setClassGen(final ClassGen c) { cg = c; } + /** + * Sets the constant pool generator. + * + * @param c The constant pool generator. + */ public void setConstantPool(final ConstantPoolGen c) { cp = c; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionHandle.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionHandle.java index 2c94b770265a..89027e4beb03 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionHandle.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionHandle.java @@ -31,14 +31,13 @@ * Instances of this class give users a handle to the instructions contained in an InstructionList. Instruction objects * may be used more than once within a list, this is useful because it saves memory and may be much faster. * - * Within an InstructionList an InstructionHandle object is wrapped around all instructions, i.e., it implements a cell + * Within an InstructionList an InstructionHandle object is wrapped around all instructions, that is, it implements a cell * in a doubly-linked list. From the outside only the next and the previous instruction (handle) are accessible. One can * traverse the list via an Enumeration returned by InstructionList.elements(). * * @see Instruction * @see BranchHandle * @see InstructionList - * @LastModified: Sept 2025 */ public class InstructionHandle { @@ -75,6 +74,11 @@ static InstructionHandle getInstructionHandle(final Instruction i) { private Map attributes; + /** + * Constructs an InstructionHandle. + * + * @param i The instruction. + */ protected InstructionHandle(final Instruction i) { setInstruction(i); } @@ -82,7 +86,7 @@ protected InstructionHandle(final Instruction i) { /** * Convenience method, simply calls accept() on the contained instruction. * - * @param v Visitor object + * @param v Visitor object. */ public void accept(final Visitor v) { instruction.accept(v); @@ -91,8 +95,8 @@ public void accept(final Visitor v) { /** * Add an attribute to an instruction handle. * - * @param key the key object to store/retrieve the attribute - * @param attr the attribute to associate with this handle + * @param key The key object to store/retrieve the attribute. + * @param attr The attribute to associate with this handle. */ public void addAttribute(final Object key, final Object attr) { if (attributes == null) { @@ -113,6 +117,8 @@ protected void addHandle() { /** * Denote this handle is being referenced by t. + * + * @param t The instruction targeter. */ public void addTargeter(final InstructionTargeter t) { if (targeters == null) { @@ -123,7 +129,7 @@ public void addTargeter(final InstructionTargeter t) { } /** - * Delete contents, i.e., remove user access. + * Delete contents, removes user access. */ void dispose() { next = prev = null; @@ -137,14 +143,17 @@ void dispose() { /** * Gets attribute of an instruction handle. * - * @param key the key object to store/retrieve the attribute + * @param key The key object to store/retrieve the attribute. + * @return The attribute value. */ public Object getAttribute(final Object key) { return attributes != null ? attributes.get(key) : null; } /** - * @return all attributes associated with this handle + * Gets all attributes associated with this handle. + * + * @return all attributes associated with this handle. */ public Collection getAttributes() { if (attributes == null) { @@ -153,28 +162,47 @@ public Collection getAttributes() { return attributes.values(); } + /** + * Gets the instruction. + * + * @return The instruction. + */ public final Instruction getInstruction() { return instruction; } + /** + * Gets the next instruction handle. + * + * @return The next instruction handle. + */ public final InstructionHandle getNext() { return next; } /** - * @return the position, i.e., the byte code offset of the contained instruction. This is accurate only after + * Gets the position. + * + * @return The position, the byte code offset of the contained instruction. This is accurate only after * InstructionList.setPositions() has been called. */ public int getPosition() { return i_position; } + /** + * Gets the previous instruction handle. + * + * @return The previous instruction handle. + */ public final InstructionHandle getPrev() { return prev; } /** - * @return null, if there are no targeters + * Gets the targeters. + * + * @return null, if there are no targeters. */ public InstructionTargeter[] getTargeters() { if (!hasTargeters()) { @@ -185,6 +213,11 @@ public InstructionTargeter[] getTargeters() { return t; } + /** + * Checks if this handle has targeters. + * + * @return true if this handle has targeters, false otherwise. + */ public boolean hasTargeters() { return targeters != null && !targeters.isEmpty(); } @@ -201,7 +234,7 @@ public void removeAllTargeters() { /** * Delete an attribute of an instruction handle. * - * @param key the key object to retrieve the attribute + * @param key The key object to retrieve the attribute. */ public void removeAttribute(final Object key) { if (attributes != null) { @@ -211,6 +244,8 @@ public void removeAttribute(final Object key) { /** * Denote this handle isn't referenced anymore by t. + * + * @param t The instruction targeter. */ public void removeTargeter(final InstructionTargeter t) { if (targeters != null) { @@ -220,6 +255,8 @@ public void removeTargeter(final InstructionTargeter t) { /** * Replace current instruction contained in this handle. Old instruction is disposed using Instruction.dispose(). + * + * @param i The new instruction. */ public void setInstruction(final Instruction i) { // Overridden in BranchHandle TODO could be package-protected? if (i == null) { @@ -235,7 +272,10 @@ public void setInstruction(final Instruction i) { // Overridden in BranchHandle } /** - * @param next the next to set + * Sets the next instruction handle. + * + * @param next The next to set. + * @return The next instruction handle. * @since 6.0 */ final InstructionHandle setNext(final InstructionHandle next) { @@ -244,14 +284,19 @@ final InstructionHandle setNext(final InstructionHandle next) { } /** - * Sets the position, i.e., the byte code offset of the contained instruction. + * Sets the position, the byte code offset of the contained instruction. + * + * @param pos The position. */ void setPosition(final int pos) { i_position = pos; } /** - * @param prev the prev to set + * Sets the previous instruction handle. + * + * @param prev The prev to set. + * @return The previous instruction handle. * @since 6.0 */ final InstructionHandle setPrev(final InstructionHandle prev) { @@ -265,6 +310,9 @@ final InstructionHandle setPrev(final InstructionHandle prev) { *

* Warning: if this is used on a BranchHandle then some methods such as getPosition() will still refer to the original * cached instruction, whereas other BH methods may affect the cache and the replacement instruction. + * + * @param i The replacement instruction. + * @return The old instruction. */ // See BCEL-273 // TODO remove this method in any redesign of BCEL @@ -275,7 +323,9 @@ public Instruction swapInstruction(final Instruction i) { } /** - * @return a string representation of the contained instruction. + * Gets a string representation of the contained instruction. + * + * @return A string representation of the contained instruction. */ @Override public String toString() { @@ -283,7 +333,10 @@ public String toString() { } /** - * @return a (verbose) string representation of the contained instruction. + * Gets a verbose string representation of the contained instruction. + * + * @param verbose whether to be verbose. + * @return A (verbose) string representation of the contained instruction. */ public String toString(final boolean verbose) { return Utility.format(i_position, 4, false, ' ') + ": " + instruction.toString(verbose); @@ -294,9 +347,9 @@ public String toString(final boolean verbose) { * length instructions 'setPositions()' performs multiple passes over the instruction list to calculate the correct * (byte) positions and offsets by calling this function. * - * @param offset additional offset caused by preceding (variable length) instructions - * @param maxOffset the maximum offset that may be caused by these instructions - * @return additional offset caused by possible change of this instruction's length + * @param offset additional offset caused by preceding (variable length) instructions. + * @param maxOffset The maximum offset that may be caused by these instructions. + * @return additional offset caused by possible change of this instruction's length. */ protected int updatePosition(final int offset, final int maxOffset) { i_position += offset; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionList.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionList.java index 579efc9fe3b8..c6af0454311b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionList.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -36,29 +36,28 @@ import jdk.xml.internal.Utils; /** - * This class is a container for a list of Instruction objects. Instructions can be - * appended, inserted, moved, deleted, etc.. Instructions are being wrapped into - * InstructionHandles objects that are returned upon append/insert operations. They - * give the user (read only) access to the list structure, such that it can be traversed and manipulated in a controlled - * way. - * + * This class is a container for a list of Instruction objects. Instructions can be appended, inserted, moved, deleted, and so + * on. Instructions are being wrapped into InstructionHandles objects that are returned upon append/insert operations. They + * give the user (read only) access to the list structure, such that it can be traversed and manipulated in a controlled way. + *

* A list is finally dumped to a byte code array with getByteCode. + *

* * @see Instruction * @see InstructionHandle * @see BranchHandle - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class InstructionList implements Iterable { /** * Find the target instruction (handle) that corresponds to the given target position (byte code offset). * - * @param ihs array of instruction handles, i.e. il.getInstructionHandles() - * @param pos array of positions corresponding to ihs, i.e. il.getInstructionPositions() - * @param count length of arrays - * @param target target position to search for - * @return target position's instruction handle if available + * @param ihs array of instruction handles, for example il.getInstructionHandles(). + * @param pos array of positions corresponding to ihs, for example il.getInstructionPositions(). + * @param count length of arrays. + * @param target target position to search for. + * @return target position's instruction handle if available. */ public static InstructionHandle findHandle(final InstructionHandle[] ihs, final int[] pos, final int count, final int target) { if (ihs != null && pos != null) { @@ -100,7 +99,7 @@ public InstructionList() { /** * Create instruction list containing one instruction. * - * @param i initial instruction + * @param i initial instruction. */ public InstructionList(final BranchInstruction i) { append(i); @@ -109,12 +108,12 @@ public InstructionList(final BranchInstruction i) { /** * Initialize instruction list from byte array. * - * @param code byte array containing the instructions + * @param code byte array containing the instructions. */ public InstructionList(final byte[] code) { int count = 0; // Contains actual length - int[] pos; - InstructionHandle[] ihs; + final int[] pos; + final InstructionHandle[] ihs; try (ByteSequence bytes = new ByteSequence(code)) { ihs = new InstructionHandle[code.length]; pos = new int[code.length]; // Can't be more than that @@ -126,10 +125,10 @@ public InstructionList(final byte[] code) { final int off = bytes.getIndex(); pos[count] = off; /* - * Read one instruction from the byte stream, the byte position is set accordingly. + * Reads one instruction from the byte stream, the byte position is set accordingly. */ final Instruction i = Instruction.readInstruction(bytes); - InstructionHandle ih; + final InstructionHandle ih; if (i instanceof BranchInstruction) { ih = append((BranchInstruction) i); } else { @@ -144,7 +143,7 @@ public InstructionList(final byte[] code) { } bytePositions = Arrays.copyOf(pos, count); // Trim to proper size /* - * Pass 2: Look for BranchInstruction and update their targets, i.e., convert offsets to instruction handles. + * Pass 2: Look for BranchInstruction and update their targets, that is, convert offsets to instruction handles. */ for (int i = 0; i < count; i++) { if (ihs[i] instanceof BranchHandle) { @@ -176,9 +175,9 @@ public InstructionList(final byte[] code) { } /** - * Initialize list with (nonnull) compound instruction. Consumes argument list, i.e., it becomes empty. + * Initialize list with (nonnull) compound instruction. Consumes argument list, that is, it becomes empty. * - * @param c compound instruction (list) + * @param c compound instruction (list). */ public InstructionList(final CompoundInstruction c) { append(c.getInstructionList()); @@ -187,7 +186,7 @@ public InstructionList(final CompoundInstruction c) { /** * Create instruction list containing one instruction. * - * @param i initial instruction + * @param i initial instruction. */ public InstructionList(final Instruction i) { append(i); @@ -195,6 +194,8 @@ public InstructionList(final Instruction i) { /** * Add observer for this object. + * + * @param o The observer to add. */ public void addObserver(final InstructionListObserver o) { if (observers == null) { @@ -206,8 +207,8 @@ public void addObserver(final InstructionListObserver o) { /** * Append a branch instruction to the end of this list. * - * @param i branch instruction to append - * @return branch instruction handle of the appended instruction + * @param i branch instruction to append. + * @return branch instruction handle of the appended instruction. */ public BranchHandle append(final BranchInstruction i) { final BranchHandle ih = BranchHandle.getBranchHandle(i); @@ -218,8 +219,8 @@ public BranchHandle append(final BranchInstruction i) { /** * Append a compound instruction. * - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first appended instruction + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first appended instruction. */ public InstructionHandle append(final CompoundInstruction c) { return append(c.getInstructionList()); @@ -228,8 +229,8 @@ public InstructionHandle append(final CompoundInstruction c) { /** * Append an instruction to the end of this list. * - * @param i instruction to append - * @return instruction handle of the appended instruction + * @param i instruction to append. + * @return instruction handle of the appended instruction. */ public InstructionHandle append(final Instruction i) { final InstructionHandle ih = InstructionHandle.getInstructionHandle(i); @@ -240,9 +241,9 @@ public InstructionHandle append(final Instruction i) { /** * Append a compound instruction, after instruction i. * - * @param i Instruction in list - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first appended instruction + * @param i Instruction in list. + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first appended instruction. */ public InstructionHandle append(final Instruction i, final CompoundInstruction c) { return append(i, c.getInstructionList()); @@ -251,23 +252,23 @@ public InstructionHandle append(final Instruction i, final CompoundInstruction c /** * Append a single instruction j after another instruction i, which must be in this list of course! * - * @param i Instruction in list - * @param j Instruction to append after i in list - * @return instruction handle of the first appended instruction + * @param i Instruction in list. + * @param j Instruction to append after i in list. + * @return instruction handle of the first appended instruction. */ public InstructionHandle append(final Instruction i, final Instruction j) { return append(i, new InstructionList(j)); } /** - * Append another list after instruction i contained in this list. Consumes argument list, i.e., it becomes empty. + * Append another list after instruction i contained in this list. Consumes argument list, that is, it becomes empty. * - * @param i where to append the instruction list - * @param il Instruction list to append to this one - * @return instruction handle pointing to the first appended instruction + * @param i where to append the instruction list. + * @param il Instruction list to append to this one. + * @return instruction handle pointing to the first appended instruction. */ public InstructionHandle append(final Instruction i, final InstructionList il) { - InstructionHandle ih; + final InstructionHandle ih; if ((ih = findInstruction2(i)) == null) { throw new ClassGenException("Instruction " + i + " is not contained in this list."); } @@ -277,7 +278,7 @@ public InstructionHandle append(final Instruction i, final InstructionList il) { /** * Append an instruction to the end of this list. * - * @param ih instruction to append + * @param ih instruction to append. */ private void append(final InstructionHandle ih) { if (isEmpty()) { @@ -295,9 +296,9 @@ private void append(final InstructionHandle ih) { /** * Append an instruction after instruction (handle) ih contained in this list. * - * @param ih where to append the instruction list - * @param i Instruction to append - * @return instruction handle pointing to the first appended instruction + * @param ih where to append the instruction list. + * @param i Instruction to append. + * @return instruction handle pointing to the first appended instruction. */ public BranchHandle append(final InstructionHandle ih, final BranchInstruction i) { final BranchHandle bh = BranchHandle.getBranchHandle(i); @@ -310,9 +311,9 @@ public BranchHandle append(final InstructionHandle ih, final BranchInstruction i /** * Append a compound instruction. * - * @param ih where to append the instruction list - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first appended instruction + * @param ih where to append the instruction list. + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first appended instruction. */ public InstructionHandle append(final InstructionHandle ih, final CompoundInstruction c) { return append(ih, c.getInstructionList()); @@ -321,21 +322,21 @@ public InstructionHandle append(final InstructionHandle ih, final CompoundInstru /** * Append an instruction after instruction (handle) ih contained in this list. * - * @param ih where to append the instruction list - * @param i Instruction to append - * @return instruction handle pointing to the first appended instruction + * @param ih where to append the instruction list. + * @param i Instruction to append. + * @return instruction handle pointing to the first appended instruction. */ public InstructionHandle append(final InstructionHandle ih, final Instruction i) { return append(ih, new InstructionList(i)); } /** - * Append another list after instruction (handle) ih contained in this list. Consumes argument list, i.e., it becomes + * Append another list after instruction (handle) ih contained in this list. Consumes argument list, that is, it becomes * empty. * - * @param ih where to append the instruction list - * @param il Instruction list to append to this one - * @return instruction handle pointing to the first appended instruction + * @param ih where to append the instruction list. + * @param il Instruction list to append to this one. + * @return instruction handle pointing to the first appended instruction. */ public InstructionHandle append(final InstructionHandle ih, final InstructionList il) { if (il == null) { @@ -360,10 +361,10 @@ public InstructionHandle append(final InstructionHandle ih, final InstructionLis } /** - * Append another list to this one. Consumes argument list, i.e., it becomes empty. + * Append another list to this one. Consumes argument list, that is, it becomes empty. * - * @param il list to append to end of this list - * @return instruction handle of the first appended instruction + * @param il list to append to end of this list. + * @return instruction handle of the first appended instruction. */ public InstructionHandle append(final InstructionList il) { if (il == null) { @@ -387,10 +388,22 @@ private void clear() { length = 0; } + /** + * Checks if the list contains the given instruction. + * + * @param i The instruction to check. + * @return true if the list contains the instruction. + */ public boolean contains(final Instruction i) { return findInstruction1(i) != null; } + /** + * Checks if the list contains the given instruction handle. + * + * @param i The instruction handle to check. + * @return true if the list contains the instruction handle. + */ public boolean contains(final InstructionHandle i) { if (i == null) { return false; @@ -404,14 +417,16 @@ public boolean contains(final InstructionHandle i) { } /** - * @return complete, i.e., deep copy of this list + * Creates a complete deep copy of this list. + * + * @return complete, that is, deep copy of this list. */ public InstructionList copy() { final Map map = new HashMap<>(); final InstructionList il = new InstructionList(); /* * Pass 1: Make copies of all instructions, append them to the new list and associate old instruction references with - * the new ones, i.e., a 1:1 mapping. + * the new ones, that is, a 1:1 mapping. */ for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { final Instruction i = ih.getInstruction(); @@ -453,10 +468,11 @@ public InstructionList copy() { /** * Remove instruction from this list. The corresponding Instruction handles must not be reused! * - * @param i instruction to remove + * @param i instruction to remove. + * @throws TargetLostException Thrown if target is lost. */ public void delete(final Instruction i) throws TargetLostException { - InstructionHandle ih; + final InstructionHandle ih; if ((ih = findInstruction1(i)) == null) { throw new ClassGenException("Instruction " + i + " is not contained in this list."); } @@ -467,12 +483,13 @@ public void delete(final Instruction i) throws TargetLostException { * Remove instructions from instruction 'from' to instruction 'to' contained in this list. The user must ensure that * 'from' is an instruction before 'to', or risk havoc. The corresponding Instruction handles must not be reused! * - * @param from where to start deleting (inclusive) - * @param to where to end deleting (inclusive) + * @param from where to start deleting (inclusive). + * @param to where to end deleting (inclusive). + * @throws TargetLostException Thrown if target is lost. */ public void delete(final Instruction from, final Instruction to) throws TargetLostException { - InstructionHandle fromIh; - InstructionHandle toIh; + final InstructionHandle fromIh; + final InstructionHandle toIh; if ((fromIh = findInstruction1(from)) == null) { throw new ClassGenException("Instruction " + from + " is not contained in this list."); } @@ -485,7 +502,8 @@ public void delete(final Instruction from, final Instruction to) throws TargetLo /** * Remove instruction from this list. The corresponding Instruction handles must not be reused! * - * @param ih instruction (handle) to remove + * @param ih instruction (handle) to remove. + * @throws TargetLostException Thrown if target is lost. */ public void delete(final InstructionHandle ih) throws TargetLostException { remove(ih.getPrev(), ih.getNext()); @@ -495,8 +513,9 @@ public void delete(final InstructionHandle ih) throws TargetLostException { * Remove instructions from instruction 'from' to instruction 'to' contained in this list. The user must ensure that * 'from' is an instruction before 'to', or risk havoc. The corresponding Instruction handles must not be reused! * - * @param from where to start deleting (inclusive) - * @param to where to end deleting (inclusive) + * @param from where to start deleting (inclusive). + * @param to where to end deleting (inclusive). + * @throws TargetLostException Thrown if target is lost. */ public void delete(final InstructionHandle from, final InstructionHandle to) throws TargetLostException { remove(from.getPrev(), to.getNext()); @@ -519,8 +538,8 @@ public void dispose() { * Gets instruction handle for instruction at byte code position pos. This only works properly, if the list is freshly * initialized from a byte array or setPositions() has been called before this method. * - * @param pos byte code position to search for - * @return target position's instruction handle if available + * @param pos byte code position to search for. + * @return target position's instruction handle if available. */ public InstructionHandle findHandle(final int pos) { final int[] positions = bytePositions; @@ -537,8 +556,8 @@ public InstructionHandle findHandle(final int pos) { /** * Search for given Instruction reference, start at beginning of list. * - * @param i instruction to search for - * @return instruction found on success, null otherwise + * @param i instruction to search for. + * @return instruction found on success, null otherwise. */ private InstructionHandle findInstruction1(final Instruction i) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { @@ -552,8 +571,8 @@ private InstructionHandle findInstruction1(final Instruction i) { /** * Search for given Instruction reference, start at end of list * - * @param i instruction to search for - * @return instruction found on success, null otherwise + * @param i instruction to search for. + * @return instruction found on success, null otherwise. */ private InstructionHandle findInstruction2(final Instruction i) { for (InstructionHandle ih = end; ih != null; ih = ih.getPrev()) { @@ -567,7 +586,7 @@ private InstructionHandle findInstruction2(final Instruction i) { /** * When everything is finished, use this method to convert the instruction list into an array of bytes. * - * @return the byte code ready to be dumped + * @return The byte code ready to be dumped. */ public byte[] getByteCode() { // Update position indices of instructions @@ -588,14 +607,18 @@ public byte[] getByteCode() { } /** - * @return end of list + * Gets the end of list. + * + * @return end of list. */ public InstructionHandle getEnd() { return end; } /** - * @return array containing all instructions (handles) + * Gets array containing all instructions. + * + * @return array containing all instructions (handles). */ public InstructionHandle[] getInstructionHandles() { final InstructionHandle[] ihs = new InstructionHandle[length]; @@ -611,14 +634,16 @@ public InstructionHandle[] getInstructionHandles() { * Gets positions (offsets) of all instructions in the list. This relies on that the list has been freshly created from * an byte code array, or that setPositions() has been called. Otherwise this may be inaccurate. * - * @return array containing all instruction's offset in byte code + * @return array containing all instruction's offset in byte code. */ public int[] getInstructionPositions() { return bytePositions; } /** - * @return an array of instructions without target information for branch instructions. + * Gets an array of instructions without target information for branch instructions. + * + * @return An array of instructions without target information for branch instructions. */ public Instruction[] getInstructions() { final List instructions = new ArrayList<>(); @@ -633,14 +658,18 @@ public Instruction[] getInstructions() { } /** - * @return length of list (Number of instructions, not bytes) + * Gets the length of list. + * + * @return length of list (Number of instructions, not bytes). */ public int getLength() { return length; } /** - * @return start of list + * Gets the start of list. + * + * @return start of list. */ public InstructionHandle getStart() { return start; @@ -649,8 +678,8 @@ public InstructionHandle getStart() { /** * Insert a branch instruction at start of this list. * - * @param i branch instruction to insert - * @return branch instruction handle of the appended instruction + * @param i branch instruction to insert. + * @return branch instruction handle of the appended instruction. */ public BranchHandle insert(final BranchInstruction i) { final BranchHandle ih = BranchHandle.getBranchHandle(i); @@ -661,8 +690,8 @@ public BranchHandle insert(final BranchInstruction i) { /** * Insert a compound instruction. * - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first inserted instruction + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final CompoundInstruction c) { return insert(c.getInstructionList()); @@ -671,8 +700,8 @@ public InstructionHandle insert(final CompoundInstruction c) { /** * Insert an instruction at start of this list. * - * @param i instruction to insert - * @return instruction handle of the inserted instruction + * @param i instruction to insert. + * @return instruction handle of the inserted instruction. */ public InstructionHandle insert(final Instruction i) { final InstructionHandle ih = InstructionHandle.getInstructionHandle(i); @@ -683,9 +712,9 @@ public InstructionHandle insert(final Instruction i) { /** * Insert a compound instruction before instruction i. * - * @param i Instruction in list - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first inserted instruction + * @param i Instruction in list. + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final Instruction i, final CompoundInstruction c) { return insert(i, c.getInstructionList()); @@ -694,23 +723,23 @@ public InstructionHandle insert(final Instruction i, final CompoundInstruction c /** * Insert a single instruction j before another instruction i, which must be in this list of course! * - * @param i Instruction in list - * @param j Instruction to insert before i in list - * @return instruction handle of the first inserted instruction + * @param i Instruction in list. + * @param j Instruction to insert before i in list. + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final Instruction i, final Instruction j) { return insert(i, new InstructionList(j)); } /** - * Insert another list before Instruction i contained in this list. Consumes argument list, i.e., it becomes empty. + * Insert another list before Instruction i contained in this list. Consumes argument list, that is, it becomes empty. * - * @param i where to append the instruction list - * @param il Instruction list to insert - * @return instruction handle pointing to the first inserted instruction, i.e., il.getStart() + * @param i where to append the instruction list. + * @param il Instruction list to insert. + * @return instruction handle pointing to the first inserted instruction, that is, il.getStart(). */ public InstructionHandle insert(final Instruction i, final InstructionList il) { - InstructionHandle ih; + final InstructionHandle ih; if ((ih = findInstruction1(i)) == null) { throw new ClassGenException("Instruction " + i + " is not contained in this list."); } @@ -720,7 +749,7 @@ public InstructionHandle insert(final Instruction i, final InstructionList il) { /** * Insert an instruction at start of this list. * - * @param ih instruction to insert + * @param ih instruction to insert. */ private void insert(final InstructionHandle ih) { if (isEmpty()) { @@ -738,9 +767,9 @@ private void insert(final InstructionHandle ih) { /** * Insert an instruction before instruction (handle) ih contained in this list. * - * @param ih where to insert to the instruction list - * @param i Instruction to insert - * @return instruction handle of the first inserted instruction + * @param ih where to insert to the instruction list. + * @param i Instruction to insert. + * @return instruction handle of the first inserted instruction. */ public BranchHandle insert(final InstructionHandle ih, final BranchInstruction i) { final BranchHandle bh = BranchHandle.getBranchHandle(i); @@ -753,9 +782,9 @@ public BranchHandle insert(final InstructionHandle ih, final BranchInstruction i /** * Insert a compound instruction. * - * @param ih where to insert the instruction list - * @param c The composite instruction (containing an InstructionList) - * @return instruction handle of the first inserted instruction + * @param ih where to insert the instruction list. + * @param c The composite instruction (containing an InstructionList). + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final InstructionHandle ih, final CompoundInstruction c) { return insert(ih, c.getInstructionList()); @@ -764,21 +793,21 @@ public InstructionHandle insert(final InstructionHandle ih, final CompoundInstru /** * Insert an instruction before instruction (handle) ih contained in this list. * - * @param ih where to insert to the instruction list - * @param i Instruction to insert - * @return instruction handle of the first inserted instruction + * @param ih where to insert to the instruction list. + * @param i Instruction to insert. + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final InstructionHandle ih, final Instruction i) { return insert(ih, new InstructionList(i)); } /** - * Insert another list before Instruction handle ih contained in this list. Consumes argument list, i.e., it becomes + * Insert another list before Instruction handle ih contained in this list. Consumes argument list, that is, it becomes * empty. * - * @param ih where to append the instruction list - * @param il Instruction list to insert - * @return instruction handle of the first inserted instruction + * @param ih where to append the instruction list. + * @param il Instruction list to insert. + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final InstructionHandle ih, final InstructionList il) { if (il == null) { @@ -805,8 +834,8 @@ public InstructionHandle insert(final InstructionHandle ih, final InstructionLis /** * Insert another list. * - * @param il list to insert before start of this list - * @return instruction handle of the first inserted instruction + * @param il list to insert before start of this list. + * @return instruction handle of the first inserted instruction. */ public InstructionHandle insert(final InstructionList il) { if (isEmpty()) { @@ -817,14 +846,16 @@ public InstructionHandle insert(final InstructionList il) { } /** - * Test for empty list. + * Tests for empty list. + * + * @return true if list is empty, false otherwise. */ public boolean isEmpty() { return start == null; } // && end == null /** - * @return iterator that lists all instructions (handles) + * @return iterator that lists all instructions (handles). */ @Override public Iterator iterator() { @@ -857,8 +888,8 @@ public void remove() { /** * Move a single instruction (handle) to a new location. * - * @param ih moved instruction - * @param target new location of moved instruction + * @param ih moved instruction. + * @param target new location of moved instruction. */ public void move(final InstructionHandle ih, final InstructionHandle target) { move(ih, ih, target); @@ -872,9 +903,9 @@ public void move(final InstructionHandle ih, final InstructionHandle target) { * Any instruction targeters pointing to handles within the block, keep their targets. *

* - * @param start of moved block - * @param end of moved block - * @param target of moved block + * @param start of moved block. + * @param end of moved block. + * @param target of moved block. */ public void move(final InstructionHandle start, final InstructionHandle end, final InstructionHandle target) { // Step 1: Check constraints @@ -927,10 +958,10 @@ public void move(final InstructionHandle start, final InstructionHandle end, fin } /** - * Redirect all references from oldTarget to newTarget, i.e., update targets of branch instructions. + * Redirect all references from oldTarget to newTarget, that is, update targets of branch instructions. * - * @param oldTarget the old target instruction handle - * @param newTarget the new target instruction handle + * @param oldTarget The old target instruction handle. + * @param newTarget The new target instruction handle. */ public void redirectBranches(final InstructionHandle oldTarget, final InstructionHandle newTarget) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { @@ -956,9 +987,9 @@ public void redirectBranches(final InstructionHandle oldTarget, final Instructio /** * Redirect all references of exception handlers from oldTarget to newTarget. * - * @param exceptions array of exception handlers - * @param oldTarget the old target instruction handle - * @param newTarget the new target instruction handle + * @param exceptions array of exception handlers. + * @param oldTarget The old target instruction handle. + * @param newTarget The new target instruction handle. * @see MethodGen */ public void redirectExceptionHandlers(final CodeExceptionGen[] exceptions, final InstructionHandle oldTarget, final InstructionHandle newTarget) { @@ -978,9 +1009,9 @@ public void redirectExceptionHandlers(final CodeExceptionGen[] exceptions, final /** * Redirect all references of local variables from oldTarget to newTarget. * - * @param lg array of local variables - * @param oldTarget the old target instruction handle - * @param newTarget the new target instruction handle + * @param lg array of local variables. + * @param oldTarget The old target instruction handle. + * @param newTarget The new target instruction handle. * @see MethodGen */ public void redirectLocalVariables(final LocalVariableGen[] lg, final InstructionHandle oldTarget, final InstructionHandle newTarget) { @@ -998,12 +1029,12 @@ public void redirectLocalVariables(final LocalVariableGen[] lg, final Instructio * Remove from instruction 'prev' to instruction 'next' both contained in this list. Throws TargetLostException when one * of the removed instruction handles is still being targeted. * - * @param prev where to start deleting (predecessor, exclusive) - * @param next where to end deleting (successor, exclusive) + * @param prev where to start deleting (predecessor, exclusive). + * @param next where to end deleting (successor, exclusive). */ private void remove(final InstructionHandle prev, InstructionHandle next) throws TargetLostException { - InstructionHandle first; - InstructionHandle last; // First and last deleted instruction + final InstructionHandle first; + final InstructionHandle last; // First and last deleted instruction if (prev == null && next == null) { first = start; last = end; @@ -1028,7 +1059,7 @@ private void remove(final InstructionHandle prev, InstructionHandle next) throws last.setNext(null); final List targetList = new ArrayList<>(); for (InstructionHandle ih = first; ih != null; ih = ih.getNext()) { - ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets + ih.getInstruction().dispose(); // for example BranchInstructions release their targets } final StringBuilder buf = new StringBuilder("{ "); for (InstructionHandle ih = first; ih != null; ih = next) { @@ -1050,6 +1081,8 @@ private void remove(final InstructionHandle prev, InstructionHandle next) throws /** * Remove observer for this object. + * + * @param o The observer to remove. */ public void removeObserver(final InstructionListObserver o) { if (observers != null) { @@ -1058,7 +1091,10 @@ public void removeObserver(final InstructionListObserver o) { } /** - * Replace all references to the old constant pool with references to the new constant pool + * Replace all references to the old constant pool with references to the new constant pool. + * + * @param oldCp The old constant pool. + * @param newCp The new constant pool. */ public void replaceConstantPool(final ConstantPoolGen oldCp, final ConstantPoolGen newCp) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { @@ -1071,14 +1107,17 @@ public void replaceConstantPool(final ConstantPoolGen oldCp, final ConstantPoolG } } + /** + * Sets positions with no sanity checks. + */ public void setPositions() { // TODO could be package-protected? (some test code would need to be repackaged) setPositions(false); } /** - * Give all instructions their position number (offset in byte stream), i.e., make the list ready to be dumped. + * Give all instructions their position number (offset in byte stream), that is, make the list ready to be dumped. * - * @param check Perform sanity checks, e.g. if all targeted instructions really belong to this list + * @param check Perform sanity checks, for example if all targeted instructions really belong to this list. */ public void setPositions(final boolean check) { // called by code in other packages int maxAdditionalBytes = 0; @@ -1160,7 +1199,9 @@ public void setPositions(final boolean check) { // called by code in other packa } /** - * @return length of list (Number of instructions, not bytes) + * Gets the length of list. + * + * @return length of list (Number of instructions, not bytes). */ public int size() { return length; @@ -1172,7 +1213,9 @@ public String toString() { } /** - * @param verbose toggle output format + * Gets string containing all instructions in this list. + * + * @param verbose toggle output format. * @return String containing all instructions in this list. */ public String toString(final boolean verbose) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionListObserver.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionListObserver.java index 758c455d659f..0d26ed0a1527 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionListObserver.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionListObserver.java @@ -27,5 +27,10 @@ */ public interface InstructionListObserver { + /** + * Notifies observer of changes. + * + * @param list The instruction list. + */ void notify(InstructionList list); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionTargeter.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionTargeter.java index 0681476b5eec..20328ad1f970 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionTargeter.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InstructionTargeter.java @@ -35,7 +35,7 @@ public interface InstructionTargeter { /** * Tests whether this targeter targets the specified instruction handle. * - * @param instructionHandle the instruction handle to test. + * @param instructionHandle The instruction handle to test. * @return whether this targeter targets the specified instruction handle. */ boolean containsTarget(InstructionHandle instructionHandle); @@ -43,9 +43,9 @@ public interface InstructionTargeter { /** * Replaces the target of this targeter from this old handle to the new handle. * - * @param oldIh the old handle - * @param newIh the new handle - * @throws ClassGenException if oldIh is not targeted by this object + * @param oldIh The old handle. + * @param newIh The new handle. + * @throws ClassGenException Thrown if oldIh is not targeted by this object */ void updateTarget(InstructionHandle oldIh, InstructionHandle newIh) throws ClassGenException; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InvokeInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InvokeInstruction.java index 0daa3abfc134..81cc4c86a244 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InvokeInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/InvokeInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -31,7 +31,7 @@ /** * Super class for the INVOKExxx family of instructions. * - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public abstract class InvokeInstruction extends FieldOrMethod implements ExceptionThrower, StackConsumer, StackProducer { @@ -42,7 +42,10 @@ public abstract class InvokeInstruction extends FieldOrMethod implements Excepti } /** - * @param index to constant pool + * Constructs an InvokeInstruction. + * + * @param opcode The opcode. + * @param index to constant pool. */ protected InvokeInstruction(final short opcode, final int index) { super(opcode, index); @@ -51,7 +54,7 @@ protected InvokeInstruction(final short opcode, final int index) { /** * Also works for instructions whose stack effect depends on the constant pool entry they reference. * - * @return Number of words consumed from stack by this instruction + * @return Number of words consumed from stack by this instruction. */ @Override public int consumeStack(final ConstantPoolGen cpg) { @@ -68,6 +71,9 @@ public int consumeStack(final ConstantPoolGen cpg) { } /** + * Gets the argument types of referenced method. + * + * @param cpg The constant pool generator. * @return argument types of referenced method. */ public Type[] getArgumentTypes(final ConstantPoolGen cpg) { @@ -77,8 +83,8 @@ public Type[] getArgumentTypes(final ConstantPoolGen cpg) { /** * This overrides the deprecated version as we know here that the referenced class may legally be an array. * - * @return name of the referenced class/interface - * @throws IllegalArgumentException if the referenced class is an array (this should not happen) + * @return name of the referenced class/interface. + * @throws IllegalArgumentException Thrown if the referenced class is an array (this should not happen) */ @Override @Deprecated @@ -90,6 +96,9 @@ public String getClassName( final ConstantPoolGen cpg ) { } /** + * Gets the name of referenced method. + * + * @param cpg The constant pool generator. * @return name of referenced method. */ public String getMethodName(final ConstantPoolGen cpg) { @@ -97,6 +106,9 @@ public String getMethodName(final ConstantPoolGen cpg) { } /** + * Gets the return type of referenced method. + * + * @param cpg The constant pool generator. * @return return type of referenced method. */ public Type getReturnType(final ConstantPoolGen cpg) { @@ -104,6 +116,9 @@ public Type getReturnType(final ConstantPoolGen cpg) { } /** + * Gets the return type of referenced method. + * + * @param cpg The constant pool generator. * @return return type of referenced method. */ @Override @@ -114,7 +129,7 @@ public Type getType(final ConstantPoolGen cpg) { /** * Also works for instructions whose stack effect depends on the constant pool entry they reference. * - * @return Number of words produced onto stack by this instruction + * @return Number of words produced onto stack by this instruction. */ @Override public int produceStack(final ConstantPoolGen cpg) { @@ -123,7 +138,7 @@ public int produceStack(final ConstantPoolGen cpg) { } /** - * @return mnemonic for instruction with symbolic references resolved + * @return mnemonic for instruction with symbolic references resolved. */ @Override public String toString(final ConstantPool cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR.java index 548b321d0bcd..1a799aa5c86f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR.java @@ -35,15 +35,20 @@ public class JSR extends JsrInstruction implements VariableLengthInstruction { JSR() { } + /** + * Constructs a JSR instruction. + * + * @param target branch target. + */ public JSR(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.JSR, target); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -55,9 +60,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR_W.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR_W.java index b51d05c67997..91035a44857d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR_W.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JSR_W.java @@ -37,6 +37,11 @@ public class JSR_W extends JsrInstruction { JSR_W() { } + /** + * Constructs a JSR_W instruction. + * + * @param target branch target. + */ public JSR_W(final InstructionHandle target) { super(com.sun.org.apache.bcel.internal.Const.JSR_W, target); super.setLength(5); @@ -44,9 +49,9 @@ public JSR_W(final InstructionHandle target) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -57,9 +62,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -69,7 +74,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JsrInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JsrInstruction.java index 1ecd736d3553..4e7d53b1d2b7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JsrInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/JsrInstruction.java @@ -37,7 +37,7 @@ public abstract class JsrInstruction extends BranchInstruction implements Uncond } /** - * @return return address type + * @return return address type. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -49,7 +49,7 @@ public Type getType(final ConstantPoolGen cp) { * JsrInstruction object must not be shared between multiple InstructionHandle objects! Formally, there must not be * InstructionHandle objects i, j where i != j and i.getInstruction() == this == j.getInstruction(). * - * @return an InstructionHandle to the "next" instruction that will be executed when RETurned from a subroutine. + * @return An InstructionHandle to the "next" instruction that will be executed when RETurned from a subroutine. */ public InstructionHandle physicalSuccessor() { InstructionHandle ih = super.getTarget(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2D.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2D.java index b82861f17592..29e49e0587f8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2D.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2D.java @@ -24,21 +24,24 @@ /** * L2D - Convert long to double * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class L2D extends ConversionInstruction { + /** + * Constructs an L2D instruction. + */ public L2D() { super(com.sun.org.apache.bcel.internal.Const.L2D); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2F.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2F.java index a264f8c3bc6c..0c0cbb40092a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2F.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2F.java @@ -24,21 +24,24 @@ /** * L2F - Convert long to float * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result
- * 
+ *
*/ public class L2F extends ConversionInstruction { + /** + * Constructs an L2F instruction. + */ public L2F() { super(com.sun.org.apache.bcel.internal.Const.L2F); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2I.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2I.java index a6fb121586a2..6de6b951590a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2I.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/L2I.java @@ -24,21 +24,24 @@ /** * L2I - Convert long to int * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result
- * 
+ *
*/ public class L2I extends ConversionInstruction { + /** + * Constructs an L2I instruction. + */ public L2I() { super(com.sun.org.apache.bcel.internal.Const.L2I); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LADD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LADD.java index 0f8163f6f138..589f896131a9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LADD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LADD.java @@ -24,23 +24,26 @@ /** * LADD - Add longs * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ public class LADD extends ArithmeticInstruction { + /** + * Constructs an LADD instruction. + */ public LADD() { super(com.sun.org.apache.bcel.internal.Const.LADD); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LALOAD.java index 70fd5255a114..399cec8c84db 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LALOAD.java @@ -24,9 +24,9 @@ /** * LALOAD - Load long from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value1, value2
- * 
+ *
*/ public class LALOAD extends ArrayInstruction implements StackProducer { @@ -39,9 +39,9 @@ public LALOAD() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LAND.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LAND.java index 75c18f9c40d6..b1da1c3a17db 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LAND.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LAND.java @@ -24,23 +24,26 @@ /** * LAND - Bitwise AND longs * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ public class LAND extends ArithmeticInstruction { + /** + * Constructs an LAND instruction. + */ public LAND() { super(com.sun.org.apache.bcel.internal.Const.LAND); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LASTORE.java index 96f3a9511708..bf84932ec3fb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LASTORE.java @@ -24,9 +24,9 @@ /** * LASTORE - Store into long array * - *
+ * 
  * Stack: ..., arrayref, index, value.word1, value.word2 -> ...
- * 
+ *
*/ public class LASTORE extends ArrayInstruction implements StackConsumer { @@ -39,9 +39,9 @@ public LASTORE() { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCMP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCMP.java index 188ac95f6efe..bce7f43afb1a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCMP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCMP.java @@ -24,21 +24,24 @@ /** * LCMP - Compare longs: * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 -> ..., result <= -1, 0, 1>
- * 
+ *
*/ public class LCMP extends Instruction implements TypedInstruction, StackProducer, StackConsumer { + /** + * Constructs an LCMP instruction. + */ public LCMP() { super(com.sun.org.apache.bcel.internal.Const.LCMP, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -49,7 +52,7 @@ public void accept(final Visitor v) { } /** - * @return Type.LONG + * @return Type.LONG. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCONST.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCONST.java index 76ff4a26e258..238017a084fe 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCONST.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LCONST.java @@ -23,9 +23,9 @@ /** * LCONST - Push 0 or 1, other values cause an exception * - *
+ * 
  * Stack: ... -> ...,
- * 
+ *
*/ public class LCONST extends Instruction implements ConstantPushInstruction { @@ -38,6 +38,11 @@ public class LCONST extends Instruction implements ConstantPushInstruction { this(0); } + /** + * Constructs an LCONST instruction. + * + * @param l long constant value. + */ public LCONST(final long l) { super(com.sun.org.apache.bcel.internal.Const.LCONST_0, (short) 1); if (l == 0) { @@ -52,9 +57,9 @@ public LCONST(final long l) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -66,7 +71,7 @@ public void accept(final Visitor v) { } /** - * @return Type.LONG + * @return Type.LONG. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC.java index 7c210773d33a..b1019b675640 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC.java @@ -29,10 +29,9 @@ /** * LDC - Push item from constant pool. * - *
+ * 
  * Stack: ... -> ..., item
- * 
- * @LastModified: May 2021 + *
*/ public class LDC extends CPInstruction implements PushInstruction, ExceptionThrower { @@ -42,6 +41,11 @@ public class LDC extends CPInstruction implements PushInstruction, ExceptionThro LDC() { } + /** + * Constructs an LDC instruction. + * + * @param index index into constant pool. + */ public LDC(final int index) { super(com.sun.org.apache.bcel.internal.Const.LDC_W, index); setSize(); @@ -49,9 +53,9 @@ public LDC(final int index) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -64,9 +68,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -101,6 +105,12 @@ public Type getType(final ConstantPoolGen cpg) { } } + /** + * Gets the constant value from the constant pool. + * + * @param cpg constant pool generator. + * @return The constant value. + */ public Object getValue(final ConstantPoolGen cpg) { com.sun.org.apache.bcel.internal.classfile.Constant c = cpg.getConstantPool().getConstant(super.getIndex()); switch (c.getTag()) { @@ -125,7 +135,7 @@ public Object getValue(final ConstantPoolGen cpg) { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -142,7 +152,9 @@ public final void setIndex(final int index) { setSize(); } - // Adjust to proper size + /** + * Adjusts to proper size. + */ protected final void setSize() { if (super.getIndex() <= com.sun.org.apache.bcel.internal.Const.MAX_BYTE) { // Fits in one byte? super.setOpcode(com.sun.org.apache.bcel.internal.Const.LDC); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC2_W.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC2_W.java index dc2ef43bea75..4b18a6ba21fa 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC2_W.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC2_W.java @@ -23,10 +23,9 @@ /** * LDC2_W - Push long or double from constant pool * - *
+ * 
  * Stack: ... -> ..., item.word1, item.word2
- * 
- * @LastModified: May 2021 + *
*/ public class LDC2_W extends CPInstruction implements PushInstruction { @@ -36,15 +35,20 @@ public class LDC2_W extends CPInstruction implements PushInstruction { LDC2_W() { } + /** + * Constructs an LDC2_W instruction. + * + * @param index index into constant pool. + */ public LDC2_W(final int index) { super(com.sun.org.apache.bcel.internal.Const.LDC2_W, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -67,6 +71,12 @@ public Type getType(final ConstantPoolGen cpg) { } } + /** + * Gets the constant value from the constant pool. + * + * @param cpg constant pool generator. + * @return The constant value as a Number. + */ public Number getValue(final ConstantPoolGen cpg) { final com.sun.org.apache.bcel.internal.classfile.Constant c = cpg.getConstantPool().getConstant(super.getIndex()); switch (c.getTag()) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC_W.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC_W.java index 07ea06e377c4..92c5f20852b0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC_W.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDC_W.java @@ -28,9 +28,9 @@ /** * LDC_W - Push item from constant pool (wide index) * - *
+ * 
  * Stack: ... -> ..., item.word1, item.word2
- * 
+ *
*/ public class LDC_W extends LDC { @@ -40,12 +40,17 @@ public class LDC_W extends LDC { LDC_W() { } + /** + * Constructs an LDC_W instruction. + * + * @param index index into constant pool. + */ public LDC_W(final int index) { super(index); } /** - * Read needed data (i.e., index) from file. + * Reads needed data (that is, index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDIV.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDIV.java index 819e98dc1e70..0d939c1f77a4 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDIV.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LDIV.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,24 +25,27 @@ /** * LDIV - Divide longs * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 - * @LastModified: Jan 2020 + * @LastModified: Nov 2026 */ public class LDIV extends ArithmeticInstruction implements ExceptionThrower { + /** + * Constructs an LDIV instruction. + */ public LDIV() { super(com.sun.org.apache.bcel.internal.Const.LDIV); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LLOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LLOAD.java index 7ae6dc5509d5..45090adbfe0c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LLOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LLOAD.java @@ -24,9 +24,9 @@ /** * LLOAD - Load long from local variable * - *
+ * 
  * Stack ... -> ..., result.word1, result.word2
- * 
+ *
*/ public class LLOAD extends LoadInstruction { @@ -37,15 +37,20 @@ public class LLOAD extends LoadInstruction { super(com.sun.org.apache.bcel.internal.Const.LLOAD, com.sun.org.apache.bcel.internal.Const.LLOAD_0); } + /** + * Load long from local variable. + * + * @param n index of local variable. + */ public LLOAD(final int n) { super(com.sun.org.apache.bcel.internal.Const.LLOAD, com.sun.org.apache.bcel.internal.Const.LLOAD_0, n); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LMUL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LMUL.java index 86972264fddb..b15916083911 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LMUL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LMUL.java @@ -24,23 +24,26 @@ /** * LMUL - Multiply longs * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ public class LMUL extends ArithmeticInstruction { + /** + * Constructs an LMUL instruction. + */ public LMUL() { super(com.sun.org.apache.bcel.internal.Const.LMUL); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LNEG.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LNEG.java index 69c0d3572dc4..538d16cda94a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LNEG.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LNEG.java @@ -24,21 +24,24 @@ /** * LNEG - Negate long * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class LNEG extends ArithmeticInstruction { + /** + * Constructs an LNEG instruction. + */ public LNEG() { super(com.sun.org.apache.bcel.internal.Const.LNEG); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOOKUPSWITCH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOOKUPSWITCH.java index b8e153ca276f..82af19efdcce 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOOKUPSWITCH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOOKUPSWITCH.java @@ -24,6 +24,7 @@ import java.io.DataOutputStream; import java.io.IOException; +import com.sun.org.apache.bcel.internal.classfile.ClassFormatException; import com.sun.org.apache.bcel.internal.util.ByteSequence; /** @@ -39,6 +40,13 @@ public class LOOKUPSWITCH extends Select { LOOKUPSWITCH() { } + /** + * Constructs a LOOKUPSWITCH instruction. + * + * @param match array of match values. + * @param targets array of branch targets. + * @param defaultTarget default branch target. + */ public LOOKUPSWITCH(final int[] match, final InstructionHandle[] targets, final InstructionHandle defaultTarget) { super(com.sun.org.apache.bcel.internal.Const.LOOKUPSWITCH, match, targets, defaultTarget); /* alignment remainder assumed 0 here, until dump time. */ @@ -49,9 +57,9 @@ public LOOKUPSWITCH(final int[] match, final InstructionHandle[] targets, final /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -63,9 +71,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -79,17 +87,21 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { super.initFromFile(bytes, wide); // reads padding final int matchLength = bytes.readInt(); + // Require the match table to actually fit into the remaining code bytes (8 bytes per match-offset pair). The npairs field is attacker-controlled in + // a malicious class file and could otherwise request a multi-gigabyte allocation, or a negative array size, before a single pair is read. + if (matchLength < 0 || matchLength > bytes.available() / 8) { + throw new ClassFormatException("Invalid lookupswitch: npairs=" + matchLength + ", but only " + bytes.available() + " bytes of code remain."); + } setMatchLength(matchLength); final short fixedLength = (short) (9 + matchLength * 8); setFixedLength(fixedLength); - final short length = (short) (matchLength + super.getPadding()); - super.setLength(length); + super.setLength((short) (fixedLength + super.getPadding())); super.setMatches(new int[matchLength]); super.setIndices(new int[matchLength]); super.setTargets(new InstructionHandle[matchLength]); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOR.java index 53d4e9bc1917..09ab5672c534 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LOR.java @@ -24,21 +24,24 @@ /** * LOR - Bitwise OR long * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class LOR extends ArithmeticInstruction { + /** + * Constructs an LOR instruction. + */ public LOR() { super(com.sun.org.apache.bcel.internal.Const.LOR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LREM.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LREM.java index 17a535df2d37..0089e29f7de6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LREM.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LREM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,22 +25,25 @@ /** * LREM - Remainder of long * - *
+ * 
  * Stack: ..., value1, value2 -> result
- * 
- * @LastModified: Jan 2020 + *
+ * @LastModified: Nov 2026 */ public class LREM extends ArithmeticInstruction implements ExceptionThrower { + /** + * Constructs an LREM instruction. + */ public LREM() { super(com.sun.org.apache.bcel.internal.Const.LREM); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LRETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LRETURN.java index 9d40c14f8636..d4c87f138585 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LRETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LRETURN.java @@ -24,21 +24,24 @@ /** * LRETURN - Return long from method * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> <empty>
- * 
+ *
*/ public class LRETURN extends ReturnInstruction { + /** + * Constructs an LRETURN instruction. + */ public LRETURN() { super(com.sun.org.apache.bcel.internal.Const.LRETURN); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHL.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHL.java index 72c2aeed22d4..ea63bb7889f6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHL.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHL.java @@ -24,21 +24,24 @@ /** * LSHL - Arithmetic shift left long * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class LSHL extends ArithmeticInstruction { + /** + * Constructs an LSHL instruction. + */ public LSHL() { super(com.sun.org.apache.bcel.internal.Const.LSHL); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHR.java index d7a51d3cffb8..06a581bfe97c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSHR.java @@ -24,21 +24,24 @@ /** * LSHR - Arithmetic shift right long * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2 -> ..., result.word1, result.word2
- * 
+ *
*/ public class LSHR extends ArithmeticInstruction { + /** + * Constructs an LSHR instruction. + */ public LSHR() { super(com.sun.org.apache.bcel.internal.Const.LSHR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSTORE.java index 0b49912dba3c..166e3232fb55 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSTORE.java @@ -24,9 +24,9 @@ /** * LSTORE - Store long into local variable * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ...
- * 
+ *
*/ public class LSTORE extends StoreInstruction { @@ -37,15 +37,20 @@ public class LSTORE extends StoreInstruction { super(com.sun.org.apache.bcel.internal.Const.LSTORE, com.sun.org.apache.bcel.internal.Const.LSTORE_0); } + /** + * Store long into local variable. + * + * @param n index of local variable. + */ public LSTORE(final int n) { super(com.sun.org.apache.bcel.internal.Const.LSTORE, com.sun.org.apache.bcel.internal.Const.LSTORE_0, n); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSUB.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSUB.java index 8ffdf4fc5a30..d4f2fafcd34d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSUB.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LSUB.java @@ -24,23 +24,26 @@ /** * LSUB - Substract longs * - *
+ * 
  * Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
- * 
+ *
* * ..., result.word1, result.word2 */ public class LSUB extends ArithmeticInstruction { + /** + * Constructs an LSUB instruction. + */ public LSUB() { super(com.sun.org.apache.bcel.internal.Const.LSUB); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LUSHR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LUSHR.java index 0d9d2eab53ce..7826b49f6217 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LUSHR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LUSHR.java @@ -24,21 +24,24 @@ /** * LUSHR - Logical shift right long * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class LUSHR extends ArithmeticInstruction { + /** + * Constructs an LUSHR instruction. + */ public LUSHR() { super(com.sun.org.apache.bcel.internal.Const.LUSHR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LXOR.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LXOR.java index cf6ac48074af..f5635061a9e0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LXOR.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LXOR.java @@ -24,21 +24,24 @@ /** * LXOR - Bitwise XOR long * - *
+ * 
  * Stack: ..., value1, value2 -> ..., result
- * 
+ *
*/ public class LXOR extends ArithmeticInstruction { + /** + * Constructs an LXOR instruction. + */ public LXOR() { super(com.sun.org.apache.bcel.internal.Const.LXOR); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LineNumberGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LineNumberGen.java index 68bb2abf5132..cbc2369fa78d 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LineNumberGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LineNumberGen.java @@ -26,7 +26,7 @@ import com.sun.org.apache.bcel.internal.classfile.LineNumber; /** - * This class represents a line number within a method, i.e., give an instruction a line number corresponding to the + * This class represents a line number within a method, that is, give an instruction a line number corresponding to the * source code line. * * @see LineNumber @@ -42,7 +42,8 @@ public class LineNumberGen implements InstructionTargeter, Cloneable { /** * Create a line number. * - * @param ih instruction handle to reference + * @param ih instruction handle to reference. + * @param srcLine source line number. */ public LineNumberGen(final InstructionHandle ih, final int srcLine) { setInstruction(ih); @@ -59,13 +60,18 @@ public Object clone() { } /** - * @return true, if ih is target of this line number + * @return true, if ih is target of this line number. */ @Override public boolean containsTarget(final InstructionHandle ih) { return this.ih == ih; } + /** + * Gets the instruction handle. + * + * @return The instruction handle. + */ public InstructionHandle getInstruction() { return ih; } @@ -75,28 +81,45 @@ public InstructionHandle getInstruction() { * * This relies on that the instruction list has already been dumped to byte code or that the 'setPositions' methods * has been called for the instruction list. + * + * @return The line number attribute. */ public LineNumber getLineNumber() { return new LineNumber(ih.getPosition(), srcLine); } + /** + * Gets the source line number. + * + * @return The source line number. + */ public int getSourceLine() { return srcLine; } + /** + * Sets the instruction handle. + * + * @param instructionHandle The instruction handle to set. + */ public void setInstruction(final InstructionHandle instructionHandle) { // TODO could be package-protected? Objects.requireNonNull(instructionHandle, "instructionHandle"); BranchInstruction.notifyTarget(this.ih, instructionHandle, this); this.ih = instructionHandle; } + /** + * Sets the source line number. + * + * @param srcLine The source line number to set. + */ public void setSourceLine(final int srcLine) { // TODO could be package-protected? this.srcLine = srcLine; } /** - * @param oldIh old target - * @param newIh new target + * @param oldIh old target. + * @param newIh new target. */ @Override public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadClass.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadClass.java index 9fad1d1595dd..98778cab1a9f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadClass.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadClass.java @@ -29,8 +29,8 @@ public interface LoadClass { /** * Returns the {@link ObjectType} of the referenced class or interface that may be loaded and resolved. * - * @param cpg A ConstantPoolGen - * @return object type that may be loaded or null if a primitive is referenced + * @param cpg A ConstantPoolGen. + * @return object type that may be loaded or null if a primitive is referenced. */ ObjectType getLoadClassType(ConstantPoolGen cpg); @@ -40,8 +40,8 @@ public interface LoadClass { * is defined. If no class is forced to be loaded, {@code null} is returned. An example for this is an {@link NEWARRAY} instruction that creates an * {@code int[][]}. * - * @param cpg A ConstantPoolGen - * @return the type associated with this instruction. + * @param cpg A ConstantPoolGen. + * @return The type associated with this instruction. * @see #getLoadClassType(ConstantPoolGen) */ Type getType(ConstantPoolGen cpg); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadInstruction.java index faaf9fad552f..173d1ab93df0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LoadInstruction.java @@ -22,7 +22,7 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Denotes an unparameterized instruction to load a value from a local variable, e.g. ILOAD. + * Denotes an unparameterized instruction to load a value from a local variable, for example ILOAD. */ public abstract class LoadInstruction extends LocalVariableInstruction implements PushInstruction { @@ -35,9 +35,11 @@ public abstract class LoadInstruction extends LocalVariableInstruction implement } /** - * @param opcode Instruction opcode - * @param cTag Instruction number for compact version, ALOAD_0, e.g. - * @param n local variable index (unsigned short) + * Constructs a LoadInstruction. + * + * @param opcode Instruction opcode. + * @param cTag Instruction number for compact version, ALOAD_0, for example. + * @param n local variable index (unsigned short). */ protected LoadInstruction(final short opcode, final short cTag, final int n) { super(opcode, cTag, n); @@ -45,9 +47,9 @@ protected LoadInstruction(final short opcode, final short cTag, final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableGen.java index 71cfa0cf1c21..38810692b768 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableGen.java @@ -44,11 +44,11 @@ public class LocalVariableGen implements InstructionTargeter, NamedAndTyped, Clo * Generate a local variable that with index 'index'. Note that double and long variables need two indexs. Index indices * have to be provided by the user. * - * @param index index of local variable - * @param name its name - * @param type its type - * @param start from where the instruction is valid (null means from the start) - * @param end until where the instruction is valid (null means to the end) + * @param index index of local variable. + * @param name its name. + * @param type its type. + * @param start from where the instruction is valid (null means from the start). + * @param end until where the instruction is valid (null means to the end). */ public LocalVariableGen(final int index, final String name, final Type type, final InstructionHandle start, final InstructionHandle end) { if (index < 0 || index > Const.MAX_SHORT) { @@ -67,12 +67,12 @@ public LocalVariableGen(final int index, final String name, final Type type, fin * Generates a local variable that with index 'index'. Note that double and long variables need two indexs. Index * indices have to be provided by the user. * - * @param index index of local variable - * @param name its name - * @param type its type - * @param start from where the instruction is valid (null means from the start) - * @param end until where the instruction is valid (null means to the end) - * @param origIndex index of local variable prior to any changes to index + * @param index index of local variable. + * @param name its name. + * @param type its type. + * @param start from where the instruction is valid (null means from the start). + * @param end until where the instruction is valid (null means to the end). + * @param origIndex index of local variable prior to any changes to index. */ public LocalVariableGen(final int index, final String name, final Type type, final InstructionHandle start, final InstructionHandle end, final int origIndex) { @@ -90,7 +90,7 @@ public Object clone() { } /** - * @return true, if ih is target of this variable + * @return true, if ih is target of this variable. */ @Override public boolean containsTarget(final InstructionHandle ih) { @@ -117,14 +117,29 @@ public boolean equals(final Object o) { return l.index == index && l.start == start && l.end == end; } + /** + * Gets the end instruction handle. + * + * @return The end instruction handle. + */ public InstructionHandle getEnd() { return end; } + /** + * Gets the index. + * + * @return The index. + */ public int getIndex() { return index; } + /** + * Gets whether the variable lives to the end. + * + * @return true if the variable lives to the end. + */ public boolean getLiveToEnd() { return liveToEnd; } @@ -139,7 +154,8 @@ public boolean getLiveToEnd() { * between a live range that ends BEFORE the last insturction of the method or a live range that ends AFTER the last * instruction of the method. Hence the liveToEnd flag to differentiate between these two cases. * - * @param cp constant pool + * @param cp constant pool. + * @return The local variable. */ public LocalVariable getLocalVariable(final ConstantPoolGen cp) { int startPc = 0; @@ -161,10 +177,20 @@ public String getName() { return name; } + /** + * Gets the original index. + * + * @return The original index. + */ public int getOrigIndex() { return origIndex; } + /** + * Gets the start instruction handle. + * + * @return The start instruction handle. + */ public InstructionHandle getStart() { return start; } @@ -177,19 +203,34 @@ public Type getType() { @Override public int hashCode() { // If the user changes the name or type, problems with the targeter hashmap will occur. - // Note: index cannot be part of hash as it may be changed by the user. + // Note: Index cannot be part of hash as it may be changed by the user. return name.hashCode() ^ type.hashCode(); } + /** + * Sets the end instruction handle. + * + * @param end The end instruction handle. + */ public void setEnd(final InstructionHandle end) { // TODO could be package-protected? BranchInstruction.notifyTarget(this.end, end, this); this.end = end; } + /** + * Sets the index. + * + * @param index The index. + */ public void setIndex(final int index) { this.index = index; } + /** + * Sets whether the variable lives to the end. + * + * @param liveToEnd true if the variable lives to the end. + */ public void setLiveToEnd(final boolean liveToEnd) { this.liveToEnd = liveToEnd; } @@ -199,6 +240,11 @@ public void setName(final String name) { this.name = name; } + /** + * Sets the start instruction handle. + * + * @param start The start instruction handle. + */ public void setStart(final InstructionHandle start) { // TODO could be package-protected? BranchInstruction.notifyTarget(this.start, start, this); this.start = start; @@ -215,8 +261,8 @@ public String toString() { } /** - * @param oldIh old target, either start or end - * @param newIh new target + * @param oldIh old target, either start or end. + * @param newIh new target. */ @Override public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableInstruction.java index f952a65880bb..9f2a99cbd837 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/LocalVariableInstruction.java @@ -27,8 +27,6 @@ /** * Abstract super class for instructions dealing with local variables. - * - * @LastModified: Sept 2025 */ public abstract class LocalVariableInstruction extends Instruction implements TypedInstruction, IndexedInstruction { @@ -57,9 +55,11 @@ public abstract class LocalVariableInstruction extends Instruction implements Ty } /** - * @param opcode Instruction opcode - * @param cTag Instruction number for compact version, ALOAD_0, e.g. - * @param n local variable index (unsigned short) + * Constructs a LocalVariableInstruction. + * + * @param opcode Instruction opcode. + * @param cTag Instruction number for compact version, ALOAD_0, for example. + * @param n local variable index (unsigned short). */ protected LocalVariableInstruction(final short opcode, final short cTag, final int n) { super(opcode, (short) 2); @@ -69,9 +69,9 @@ protected LocalVariableInstruction(final short opcode, final short cTag, final i } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -79,7 +79,7 @@ public void dump(final DataOutputStream out) throws IOException { out.writeByte(Const.WIDE); } out.writeByte(super.getOpcode()); - if (super.getLength() > 1) { // Otherwise ILOAD_n, instruction, e.g. + if (super.getLength() > 1) { // Otherwise ILOAD_n, instruction, for example. if (wide()) { out.writeShort(n); } else { @@ -89,7 +89,9 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return canonical tag for instruction, e.g., ALOAD for ALOAD_0 + * Gets the canonical tag for instruction, for example, ALOAD for ALOAD_0. + * + * @return canonical tag for instruction, for example, ALOAD for ALOAD_0. */ public short getCanonicalTag() { return canonTag; @@ -106,9 +108,9 @@ public final int getIndex() { /** * Returns the type associated with the instruction - in case of ALOAD or ASTORE Type.OBJECT is returned. This is just a * bit incorrect, because ALOAD and ASTORE may work on every ReferenceType (including Type.NULL) and ASTORE may even - * work on a ReturnaddressType . + * work on a ReturnaddressType. * - * @return type associated with the instruction + * @return type associated with the instruction. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -134,7 +136,7 @@ public Type getType(final ConstantPoolGen cp) { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. * *
      * (ILOAD <= tag <= ALOAD_3) || (ISTORE <= tag <= ASTORE_3)
@@ -144,7 +146,8 @@ public Type getType(final ConstantPoolGen cp) {
     protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException {
         if (wide) {
             n = bytes.readUnsignedShort();
-            super.setLength(4);
+            // dump() emits the wide prefix only when the index needs it, so match that width here.
+            super.setLength(wide() ? 4 : 2);
         } else {
             final short opcode = super.getOpcode();
             if (opcode >= Const.ILOAD && opcode <= Const.ALOAD || opcode >= Const.ISTORE && opcode <= Const.ASTORE) {
@@ -164,17 +167,19 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws
     /**
      * Sets the local variable index. also updates opcode and length TODO Why?
      *
+     * @param index local variable index (unsigned short).
+     * @throws ClassGenException Thrown if index is out of bounds.
      * @see #setIndexOnly(int)
      */
     @Override
-    public void setIndex(final int n) { // TODO could be package-protected?
-        if (n < 0 || n > Const.MAX_SHORT) {
-            throw new ClassGenException("Illegal value: " + n);
+    public void setIndex(final int index) { // TODO could be package-protected?
+        if (!isNonNegativeUShort(index)) {
+            throw new ClassGenException("Illegal value: " + index);
         }
-        this.n = n;
+        this.n = index;
         // Cannot be < 0 as this is checked above
-        if (n <= 3) { // Use more compact instruction xLOAD_n
-            super.setOpcode((short) (cTag + n));
+        if (index <= 3) { // Use more compact instruction xLOAD_n
+            super.setOpcode((short) (cTag + index));
             super.setLength(1);
         } else {
             super.setOpcode(canonTag);
@@ -202,8 +207,8 @@ final void setIndexOnly(final int n) {
      * <name of opcode> "["<opcode number>"]" "("<length of instruction>")" "<"< local variable
      * index>">"
      *
-     * @param verbose long/short format switch
-     * @return mnemonic for instruction
+     * @param verbose long/short format switch.
+     * @return mnemonic for instruction.
      */
     @Override
     public String toString(final boolean verbose) {
diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITORENTER.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITORENTER.java
index 6ea4f9185899..7ed4e5d3192b 100644
--- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITORENTER.java
+++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITORENTER.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -25,22 +25,25 @@
 /**
  * MONITORENTER - Enter monitor for object
  *
- * 
+ * 
  * Stack: ..., objectref -> ...
- * 
- * @LastModified: Jan 2020 + *
+ * @LastModified: Nov 2026 */ public class MONITORENTER extends Instruction implements ExceptionThrower, StackConsumer { + /** + * Constructs a MONITORENTER instruction. + */ public MONITORENTER() { super(com.sun.org.apache.bcel.internal.Const.MONITORENTER, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITOREXIT.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITOREXIT.java index 40daeb13ba68..b4e950bca834 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITOREXIT.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MONITOREXIT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,22 +25,25 @@ /** * MONITOREXIT - Exit monitor for object * - *
+ * 
  * Stack: ..., objectref -> ...
- * 
- * @LastModified: Jan 2020 + *
+ * @LastModified: Nov 2026 */ public class MONITOREXIT extends Instruction implements ExceptionThrower, StackConsumer { + /** + * Constructs a MONITOREXIT instruction. + */ public MONITOREXIT() { super(com.sun.org.apache.bcel.internal.Const.MONITOREXIT, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MULTIANEWARRAY.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MULTIANEWARRAY.java index 9f83842d2adb..9c1809a7f3b2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MULTIANEWARRAY.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MULTIANEWARRAY.java @@ -31,9 +31,9 @@ /** * MULTIANEWARRAY - Create new mutidimensional array of references * - *
+ * 
  * Stack: ..., count1, [count2, ...] -> ..., arrayref
- * 
+ *
*/ public class MULTIANEWARRAY extends CPInstruction implements LoadClass, AllocationInstruction, ExceptionThrower { @@ -45,9 +45,15 @@ public class MULTIANEWARRAY extends CPInstruction implements LoadClass, Allocati MULTIANEWARRAY() { } + /** + * Constructs a MULTIANEWARRAY instruction. + * + * @param index index into constant pool. + * @param dimensions number of dimensions. + */ public MULTIANEWARRAY(final int index, final short dimensions) { super(com.sun.org.apache.bcel.internal.Const.MULTIANEWARRAY, index); - if (dimensions < 1) { + if (dimensions < 1 || dimensions > com.sun.org.apache.bcel.internal.Const.MAX_BYTE) { throw new ClassGenException("Invalid dimensions value: " + dimensions); } this.dimensions = dimensions; @@ -56,9 +62,9 @@ public MULTIANEWARRAY(final int index, final short dimensions) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -73,7 +79,7 @@ public void accept(final Visitor v) { /** * Also works for instructions whose stack effect depends on the constant pool entry they reference. * - * @return Number of words consumed from stack by this instruction + * @return Number of words consumed from stack by this instruction. */ @Override public int consumeStack(final ConstantPoolGen cpg) { @@ -81,9 +87,9 @@ public int consumeStack(final ConstantPoolGen cpg) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -93,7 +99,9 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return number of dimensions to be created + * Gets the number of dimensions. + * + * @return number of dimensions to be created. */ public final short getDimensions() { return dimensions; @@ -115,17 +123,17 @@ public ObjectType getLoadClassType(final ConstantPoolGen cpg) { } /** - * Read needed data (i.e., no. dimension) from file. + * Reads needed data (that is, no. dimension) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { super.initFromFile(bytes, wide); - dimensions = bytes.readByte(); + dimensions = (short) bytes.readUnsignedByte(); super.setLength(4); } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { @@ -133,7 +141,7 @@ public String toString(final boolean verbose) { } /** - * @return mnemonic for instruction with symbolic references resolved + * @return mnemonic for instruction with symbolic references resolved. */ @Override public String toString(final ConstantPool cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodGen.java index be09b0a51591..89c7e2649c0b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodGen.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -59,7 +59,7 @@ * * @see InstructionList * @see Method - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class MethodGen extends FieldGenOrMethodGen { @@ -126,6 +126,8 @@ private static byte[] getByteCodes(final Method method) { } /** + * Gets the comparison strategy object. + * * @return Comparison strategy object. */ public static BCELComparator getComparator() { @@ -135,7 +137,10 @@ public static BCELComparator getComparator() { /** * Computes stack usage of an instruction list by performing control flow analysis. * - * @return maximum stack depth used by method + * @param cp The constant pool generator. + * @param il The instruction list. + * @param et The exception handlers. + * @return maximum stack depth used by method. */ public static int getMaxStack(final ConstantPoolGen cp, final InstructionList il, final CodeExceptionGen[] et) { final BranchStack branchTargets = new BranchStack(); @@ -205,6 +210,8 @@ public static int getMaxStack(final ConstantPoolGen cp, final InstructionList il } /** + * Sets the comparison strategy object. + * * @param comparator Comparison strategy object. */ public static void setComparator(final BCELComparator comparator) { @@ -246,14 +253,14 @@ public static void setComparator(final BCELComparator compa * For example one may not add a local variable and later remove the instructions it refers to without causing havoc. It * is safe however if you remove that local variable, too. * - * @param accessFlags access qualifiers - * @param returnType method type - * @param argTypes argument types - * @param argNames argument names (if this is null, default names will be provided for them) - * @param methodName name of method - * @param className class name containing this method (may be null, if you don't care) - * @param il instruction list associated with this method, may be null only for abstract or native methods - * @param cp constant pool + * @param accessFlags access qualifiers. + * @param returnType method type. + * @param argTypes argument types. + * @param argNames argument names (if this is null, default names will be provided for them). + * @param methodName name of method. + * @param className class name containing this method (may be null, if you don't care). + * @param il instruction list associated with this method, may be null only for abstract or native methods. + * @param cp constant pool. */ public MethodGen(final int accessFlags, final Type returnType, final Type[] argTypes, String[] argNames, final String methodName, final String className, final InstructionList il, final ConstantPoolGen cp) { @@ -307,9 +314,9 @@ public MethodGen(final int accessFlags, final Type returnType, final Type[] argT /** * Instantiate from existing method. * - * @param method method - * @param className class name containing this method - * @param cp constant pool + * @param method method. + * @param className class name containing this method. + * @param cp constant pool. */ public MethodGen(final Method method, final String className, final ConstantPoolGen cp) { this(method.getAccessFlags(), Type.getReturnType(method.getSignature()), Type.getArgumentTypes(method.getSignature()), @@ -374,6 +381,9 @@ public MethodGen(final Method method, final String className, final ConstantPool } /** + * Adds annotations as an attribute. + * + * @param cp The constant pool generator. * @since 6.0 */ public void addAnnotationsAsAttribute(final ConstantPoolGen cp) { @@ -385,7 +395,7 @@ public void addAnnotationsAsAttribute(final ConstantPoolGen cp) { * attributes, where the former two will be generated automatically and the latter is used for the MIDP only. Other * attributes will be ignored by the JVM but do no harm. * - * @param a attribute to be added + * @param a attribute to be added. */ public void addCodeAttribute(final Attribute a) { codeAttrsList.add(a); @@ -394,21 +404,21 @@ public void addCodeAttribute(final Attribute a) { /** * Add an exception possibly thrown by this method. * - * @param className (fully qualified) name of exception + * @param className (fully qualified) name of exception. */ public void addException(final String className) { throwsList.add(className); } /** - * Add an exception handler, i.e., specify region where a handler is active and an instruction where the actual handling + * Add an exception handler, that is, specify region where a handler is active and an instruction where the actual handling * is done. * - * @param startPc Start of region (inclusive) - * @param endPc End of region (inclusive) - * @param handlerPc Where handling is done - * @param catchType class type of handled exception or null if any exception is handled - * @return new exception handler object + * @param startPc Start of region (inclusive). + * @param endPc End of region (inclusive). + * @param handlerPc Where handling is done. + * @param catchType class type of handled exception or null if any exception is handled. + * @return new exception handler object. */ public CodeExceptionGen addExceptionHandler(final InstructionHandle startPc, final InstructionHandle endPc, final InstructionHandle handlerPc, final ObjectType catchType) { @@ -423,8 +433,9 @@ public CodeExceptionGen addExceptionHandler(final InstructionHandle startPc, fin /** * Give an instruction a line number corresponding to the source code line. * - * @param ih instruction to tag - * @return new line number object + * @param ih instruction to tag. + * @param srcLine The source line number. + * @return new line number object. * @see LineNumber */ public LineNumberGen addLineNumber(final InstructionHandle ih, final int srcLine) { @@ -436,11 +447,11 @@ public LineNumberGen addLineNumber(final InstructionHandle ih, final int srcLine /** * Adds a local variable to this method and assigns an index automatically. * - * @param name variable name - * @param type variable type - * @param start from where the variable is valid, if this is null, it is valid from the start - * @param end until where the variable is valid, if this is null, it is valid to the end - * @return new local variable object + * @param name variable name. + * @param type variable type. + * @param start from where the variable is valid, if this is null, it is valid from the start. + * @param end until where the variable is valid, if this is null, it is valid to the end. + * @return new local variable object. * @see LocalVariable */ public LocalVariableGen addLocalVariable(final String name, final Type type, final InstructionHandle start, final InstructionHandle end) { @@ -450,12 +461,12 @@ public LocalVariableGen addLocalVariable(final String name, final Type type, fin /** * Adds a local variable to this method. * - * @param name variable name - * @param type variable type - * @param slot the index of the local variable, if type is long or double, the next available index is slot+2 - * @param start from where the variable is valid - * @param end until where the variable is valid - * @return new local variable object + * @param name variable name. + * @param type variable type. + * @param slot The index of the local variable, if type is long or double, the next available index is slot+2. + * @param start from where the variable is valid. + * @param end until where the variable is valid. + * @return new local variable object. * @see LocalVariable */ public LocalVariableGen addLocalVariable(final String name, final Type type, final int slot, final InstructionHandle start, final InstructionHandle end) { @@ -465,13 +476,13 @@ public LocalVariableGen addLocalVariable(final String name, final Type type, fin /** * Adds a local variable to this method. * - * @param name variable name - * @param type variable type - * @param slot the index of the local variable, if type is long or double, the next available index is slot+2 - * @param start from where the variable is valid - * @param end until where the variable is valid - * @param origIndex the index of the local variable prior to any modifications - * @return new local variable object + * @param name variable name. + * @param type variable type. + * @param slot The index of the local variable, if type is long or double, the next available index is slot+2. + * @param start from where the variable is valid. + * @param end until where the variable is valid. + * @param origIndex The index of the local variable prior to any modifications. + * @return new local variable object. * @see LocalVariable */ public LocalVariableGen addLocalVariable(final String name, final Type type, final int slot, final InstructionHandle start, final InstructionHandle end, @@ -483,7 +494,7 @@ public LocalVariableGen addLocalVariable(final String name, final Type type, fin maxLocals = slot + add; } final LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end, origIndex); - int i; + final int i; if ((i = variableList.indexOf(l)) >= 0) { variableList.set(i, l); } else { @@ -496,6 +507,8 @@ public LocalVariableGen addLocalVariable(final String name, final Type type, fin /** * Add observer for this object. + * + * @param o The observer to add. */ public void addObserver(final MethodObserver o) { if (observers == null) { @@ -504,6 +517,12 @@ public void addObserver(final MethodObserver o) { observers.add(o); } + /** + * Adds a parameter annotation. + * + * @param parameterIndex The parameter index. + * @param annotation The annotation. + */ public void addParameterAnnotation(final int parameterIndex, final AnnotationEntryGen annotation) { ensureExistingParameterAnnotationsUnpacked(); if (!hasParameterAnnotations) { @@ -523,6 +542,9 @@ public void addParameterAnnotation(final int parameterIndex, final AnnotationEnt } /** + * Adds parameter annotations as an attribute. + * + * @param cp The constant pool generator. * @since 6.0 */ public void addParameterAnnotationsAsAttribute(final ConstantPoolGen cp) { @@ -565,7 +587,11 @@ private void adjustLocalVariableTypeTable(final LocalVariableTable lvt) { } /** - * @return deep copy of this method + * Creates a deep copy of this method. + * + * @param className The class name. + * @param cp The constant pool generator. + * @return deep copy of this method. */ public MethodGen copy(final String className, final ConstantPoolGen cp) { final Method m = ((MethodGen) clone()).getMethod(); @@ -640,9 +666,12 @@ public boolean equals(final Object obj) { // J5TODO: Should paramAnnotations be an array of arrays? Rather than an array of lists, this // is more likely to suggest to the caller it is readonly (which a List does not). + /** - * Return a list of AnnotationGen objects representing parameter annotations + * Return a list of AnnotationGen objects representing parameter annotations. * + * @param i The parameter index. + * @return list of AnnotationGen objects. * @since 6.0 */ public List getAnnotationsOnParameter(final int i) { @@ -653,30 +682,56 @@ public List getAnnotationsOnParameter(final int i) { return paramAnnotations[i]; } + /** + * Gets the argument name at the specified index. + * + * @param i The argument index. + * @return The argument name. + */ public String getArgumentName(final int i) { return argNames[i]; } + /** + * Gets all argument names. + * + * @return array of argument names. + */ public String[] getArgumentNames() { return argNames.clone(); } + /** + * Gets the argument type at the specified index. + * + * @param i The argument index. + * @return The argument type. + */ public Type getArgumentType(final int i) { return argTypes[i]; } + /** + * Gets all argument types. + * + * @return array of argument types. + */ public Type[] getArgumentTypes() { return argTypes.clone(); } /** - * @return class that contains this method + * Gets the class that contains this method. + * + * @return class that contains this method. */ public String getClassName() { return className; } /** + * Gets all attributes of this method. + * * @return all attributes of this method. */ public Attribute[] getCodeAttributes() { @@ -684,7 +739,7 @@ public Attribute[] getCodeAttributes() { } /** - * @return code exceptions for 'Code' attribute + * @return code exceptions for 'Code' attribute. */ private CodeException[] getCodeExceptions() { final int size = exceptionList.size(); @@ -693,15 +748,19 @@ private CodeException[] getCodeExceptions() { return cExc; } - /* - * @return array of declared exception handlers + /** + * Gets array of declared exception handlers. + * + * @return array of declared exception handlers. */ public CodeExceptionGen[] getExceptionHandlers() { return exceptionList.toArray(CodeExceptionGen.EMPTY_ARRAY); } - /* - * @return array of thrown exceptions + /** + * Gets array of thrown exceptions. + * + * @return array of thrown exceptions. */ public String[] getExceptions() { return throwsList.toArray(Const.EMPTY_STRING_ARRAY); @@ -717,18 +776,28 @@ private ExceptionTable getExceptionTable(final ConstantPoolGen cp) { return new ExceptionTable(cp.addUtf8("Exceptions"), 2 + 2 * size, ex, cp.getConstantPool()); } + /** + * Gets the instruction list. + * + * @return The instruction list. + */ public InstructionList getInstructionList() { return il; } - /* - * @return array of line numbers + /** + * Gets array of line numbers. + * + * @return array of line numbers. */ public LineNumberGen[] getLineNumbers() { return lineNumberList.toArray(LineNumberGen.EMPTY_ARRAY); } /** + * Gets the 'LineNumberTable' attribute of all the local variables of this method. + * + * @param cp The constant pool generator. * @return 'LineNumberTable' attribute of all the local variables of this method. */ public LineNumberTable getLineNumberTable(final ConstantPoolGen cp) { @@ -738,11 +807,13 @@ public LineNumberTable getLineNumberTable(final ConstantPoolGen cp) { return new LineNumberTable(cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp.getConstantPool()); } - /* + /** + * Gets array of declared local variables sorted by index. + * * If the range of the variable has not been set yet, it will be set to be valid from the start to the end of the * instruction list. * - * @return array of declared local variables sorted by index + * @return array of declared local variables sorted by index. */ public LocalVariableGen[] getLocalVariables() { final int size = variableList.size(); @@ -763,6 +834,9 @@ public LocalVariableGen[] getLocalVariables() { } /** + * Gets the 'LocalVariableTable' attribute of all the local variables of this method. + * + * @param cp The constant pool generator. * @return 'LocalVariableTable' attribute of all the local variables of this method. */ public LocalVariableTable getLocalVariableTable(final ConstantPoolGen cp) { @@ -774,16 +848,28 @@ public LocalVariableTable getLocalVariableTable(final ConstantPoolGen cp) { } /** + * Gets the 'LocalVariableTypeTable' attribute of this method. + * * @return 'LocalVariableTypeTable' attribute of this method. */ public LocalVariableTypeTable getLocalVariableTypeTable() { return localVariableTypeTable; } + /** + * Gets the maximum number of local variables. + * + * @return The maximum number of local variables. + */ public int getMaxLocals() { return maxLocals; } + /** + * Gets the maximum stack size. + * + * @return The maximum stack size. + */ public int getMaxStack() { return maxStack; } @@ -792,7 +878,7 @@ public int getMaxStack() { * Gets method object. Never forget to call setMaxStack() or setMaxStack(max), respectively, before calling this method * (the same applies for max locals). * - * @return method object + * @return method object. */ public Method getMethod() { final String signature = getSignature(); @@ -800,13 +886,13 @@ public Method getMethod() { final int nameIndex = cp.addUtf8(super.getName()); final int signatureIndex = cp.addUtf8(signature); /* - * Also updates positions of instructions, i.e., their indices + * Also updates positions of instructions, that is, their indices */ final byte[] byteCode = il != null ? il.getByteCode() : null; LineNumberTable lnt = null; LocalVariableTable lvt = null; /* - * Create LocalVariableTable and LineNumberTable attributes (for debuggers, e.g.) + * Create LocalVariableTable and LineNumberTable attributes (for debuggers, for example) */ if (!variableList.isEmpty() && !stripAttributes) { updateLocalVariableTable(getLocalVariableTable(cp)); @@ -877,6 +963,11 @@ public Method getMethod() { return m; } + /** + * Gets the return type. + * + * @return The return type. + */ public Type getReturnType() { return getType(); } @@ -903,6 +994,8 @@ private List makeMutableVersion(final AnnotationEntry[] muta /** * Remove a code attribute. + * + * @param a The attribute to remove. */ public void removeCodeAttribute(final Attribute a) { codeAttrsList.remove(a); @@ -918,6 +1011,8 @@ public void removeCodeAttributes() { /** * Remove an exception. + * + * @param c The exception to remove. */ public void removeException(final String c) { throwsList.remove(c); @@ -925,6 +1020,8 @@ public void removeException(final String c) { /** * Remove an exception handler. + * + * @param c The exception handler to remove. */ public void removeExceptionHandler(final CodeExceptionGen c) { exceptionList.remove(c); @@ -946,6 +1043,8 @@ public void removeExceptions() { /** * Remove a line number. + * + * @param l The line number to remove. */ public void removeLineNumber(final LineNumberGen l) { lineNumberList.remove(l); @@ -961,6 +1060,8 @@ public void removeLineNumbers() { /** * Remove a local variable, its slot will not be reused, if you do not use addLocalVariable with an explicit index * argument. + * + * @param l The local variable to remove. */ public void removeLocalVariable(final LocalVariableGen l) { variableList.remove(l); @@ -981,7 +1082,7 @@ public void removeLocalVariableTypeTable() { } /** - * Remove all NOPs from the instruction list (if possible) and update every object referring to them, i.e., branch + * Remove all NOPs from the instruction list (if possible) and update every object referring to them, that is, branch * instructions, local variables and exception handlers. */ public void removeNOPs() { @@ -1009,6 +1110,8 @@ public void removeNOPs() { /** * Remove observer for this object. + * + * @param o The observer to remove. */ public void removeObserver(final MethodObserver o) { if (observers != null) { @@ -1020,32 +1123,65 @@ public void removeObserver(final MethodObserver o) { * Would prefer to make this private, but need a way to test if client is using BCEL version 6.5.0 or later that * contains fix for BCEL-329. * + * @param attributes The attributes to remove. * @since 6.5.0 */ public void removeRuntimeAttributes(final Attribute[] attributes) { Utils.streamOfIfNonNull(attributes).forEach(this::removeAttribute); } + /** + * Sets the argument name at the specified index. + * + * @param i The argument index. + * @param name The argument name. + */ public void setArgumentName(final int i, final String name) { argNames[i] = name; } + /** + * Sets all argument names. + * + * @param argNames The argument names. + */ public void setArgumentNames(final String[] argNames) { this.argNames = Utils.createEmptyArrayIfNull(argNames, String[].class); } + /** + * Sets the argument type at the specified index. + * + * @param i The argument index. + * @param type The argument type. + */ public void setArgumentType(final int i, final Type type) { argTypes[i] = type; } + /** + * Sets all argument types. + * + * @param argTypes The argument types. + */ public void setArgumentTypes(final Type[] argTypes) { this.argTypes = argTypes != null ? argTypes : Type.NO_ARGS; } + /** + * Sets the class name. + * + * @param className The class name. + */ public void setClassName(final String className) { // TODO could be package-protected? this.className = className; } + /** + * Sets the instruction list. + * + * @param il The instruction list. + */ public void setInstructionList(final InstructionList il) { // TODO could be package-protected? this.il = il; } @@ -1056,10 +1192,8 @@ public void setInstructionList(final InstructionList il) { // TODO could be pack public void setMaxLocals() { // TODO could be package-protected? (some tests would need repackaging) if (il != null) { int max = isStatic() ? 0 : 1; - if (argTypes != null) { - for (final Type argType : argTypes) { - max += argType.getSize(); - } + for (final Type argType : argTypes) { + max += argType.getSize(); } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { final Instruction ins = ih.getInstruction(); @@ -1078,6 +1212,8 @@ public void setMaxLocals() { // TODO could be package-protected? (some tests wou /** * Sets maximum number of local variables. + * + * @param m The maximum number of local variables. */ public void setMaxLocals(final int m) { maxLocals = m; @@ -1096,17 +1232,26 @@ public void setMaxStack() { // TODO could be package-protected? (some tests woul /** * Sets maximum stack size for this method. + * + * @param m The maximum stack size. */ public void setMaxStack(final int m) { // TODO could be package-protected? maxStack = m; } + /** + * Sets the return type. + * + * @param returnType The return type. + */ public void setReturnType(final Type returnType) { setType(returnType); } /** - * Do not/Do produce attributes code attributesLineNumberTable and LocalVariableTable, like javac -O + * Do not/Do produce attributes code attributesLineNumberTable and LocalVariableTable, like javac -O. + * + * @param flag whether to strip attributes. */ public void stripAttributes(final boolean flag) { stripAttributes = flag; @@ -1114,7 +1259,7 @@ public void stripAttributes(final boolean flag) { /** * Return string representation close to declaration format, 'public static void main(String[]) throws IOException', - * e.g. + * for example. * * @return String representation of the method. */ @@ -1156,7 +1301,7 @@ private void updateLocalVariableTable(final LocalVariableTable a) { InstructionHandle start = il.findHandle(l.getStartPC()); final InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles - if (null == start) { + if (start == null) { start = il.getStart(); } // end == null => live to end of method diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodObserver.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodObserver.java index 22e773ea4b73..ba97193af4d7 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodObserver.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/MethodObserver.java @@ -27,5 +27,10 @@ */ public interface MethodObserver { + /** + * Notifies this observer of a change to the method. + * + * @param method The method that changed. + */ void notify(MethodGen method); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEW.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEW.java index 53b938581eee..0b6931e068b6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEW.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEW.java @@ -26,9 +26,9 @@ /** * NEW - Create new object * - *
+ * 
  * Stack: ... -> ..., objectref
- * 
+ *
*/ public class NEW extends CPInstruction implements LoadClass, AllocationInstruction, ExceptionThrower, StackProducer { @@ -38,15 +38,20 @@ public class NEW extends CPInstruction implements LoadClass, AllocationInstructi NEW() { } + /** + * Constructs a NEW instruction. + * + * @param index index into constant pool. + */ public NEW(final int index) { super(com.sun.org.apache.bcel.internal.Const.NEW, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEWARRAY.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEWARRAY.java index be2c64a0953d..78f0b854d4d2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEWARRAY.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEWARRAY.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -29,12 +29,12 @@ /** * NEWARRAY - Create new array of basic type (int, short, ...) * - *
+ * 
  * Stack: ..., count -> ..., arrayref
- * 
+ *
* * type must be one of T_INT, T_SHORT, ... - * @LastModified: Jan 2020 + * @LastModified: Nov 2026 */ public class NEWARRAY extends Instruction implements AllocationInstruction, ExceptionThrower, StackProducer { @@ -46,10 +46,20 @@ public class NEWARRAY extends Instruction implements AllocationInstruction, Exce NEWARRAY() { } + /** + * Constructs a NEWARRAY instruction. + * + * @param type element type of array. + */ public NEWARRAY(final BasicType type) { this(type.getType()); } + /** + * Constructs a NEWARRAY instruction. + * + * @param type element type code. + */ public NEWARRAY(final byte type) { super(com.sun.org.apache.bcel.internal.Const.NEWARRAY, (short) 2); this.type = type; @@ -57,9 +67,9 @@ public NEWARRAY(final byte type) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -70,9 +80,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -86,21 +96,25 @@ public Class[] getExceptions() { } /** - * @return type of constructed array + * Gets the type of the constructed array. + * + * @return type of constructed array. */ public final Type getType() { return new ArrayType(BasicType.getType(type), 1); } /** - * @return numeric code for basic element type + * Gets the type code. + * + * @return numeric code for basic element type. */ public final byte getTypecode() { return type; } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -109,7 +123,7 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NOP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NOP.java index 37f73953e0ab..b0eda741fd91 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NOP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NOP.java @@ -26,15 +26,18 @@ */ public class NOP extends Instruction { + /** + * Constructs a NOP instruction. + */ public NOP() { super(com.sun.org.apache.bcel.internal.Const.NOP, (short) 1); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NameSignatureInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NameSignatureInstruction.java index 3b79c821956b..b5eb99ee3b7b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NameSignatureInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NameSignatureInstruction.java @@ -33,14 +33,26 @@ */ public abstract class NameSignatureInstruction extends CPInstruction { + /** + * Constructs a NameSignatureInstruction. + */ public NameSignatureInstruction() { } + /** + * Constructs a NameSignatureInstruction. + * + * @param opcode The opcode. + * @param index index into constant pool. + */ public NameSignatureInstruction(final short opcode, final int index) { super(opcode, index); } /** + * Gets the name of the referenced method or field. + * + * @param cpg constant pool generator. * @return name of referenced method/field. */ public String getName(final ConstantPoolGen cpg) { @@ -49,6 +61,12 @@ public String getName(final ConstantPoolGen cpg) { return ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); } + /** + * Gets the name and type constant. + * + * @param cpg constant pool generator. + * @return The name and type constant. + */ public ConstantNameAndType getNameAndType(final ConstantPoolGen cpg) { final ConstantPool cp = cpg.getConstantPool(); final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); @@ -56,6 +74,9 @@ public ConstantNameAndType getNameAndType(final ConstantPoolGen cpg) { } /** + * Gets the signature of the referenced method or field. + * + * @param cpg constant pool generator. * @return signature of referenced method/field. */ public String getSignature(final ConstantPoolGen cpg) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NamedAndTyped.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NamedAndTyped.java index a46e7aa2dac1..055a4219eefc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NamedAndTyped.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NamedAndTyped.java @@ -26,11 +26,31 @@ */ public interface NamedAndTyped { + /** + * Gets the name. + * + * @return The name. + */ String getName(); + /** + * Gets the type. + * + * @return The type. + */ Type getType(); + /** + * Sets the name. + * + * @param name The name. + */ void setName(String name); + /** + * Sets the type. + * + * @param type The type. + */ void setType(Type type); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ObjectType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ObjectType.java index 622a3cdd9615..fc0b5191f481 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ObjectType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ObjectType.java @@ -34,8 +34,8 @@ public class ObjectType extends ReferenceType { /** * Constructs a new instance. * - * @param className fully qualified class name, e.g. java.lang.String - * @return a new instance. + * @param className fully qualified class name, for example {@link String}. + * @return A new instance. * @since 6.0 */ public static ObjectType getInstance(final String className) { @@ -47,7 +47,7 @@ public static ObjectType getInstance(final String className) { /** * Constructs a new instance. * - * @param className fully qualified class name, e.g. {@link String} + * @param className fully qualified class name, for example {@link String}. */ public ObjectType(final String className) { super(Const.T_REFERENCE, "L" + Utility.packageToPath(className) + ";"); @@ -55,9 +55,11 @@ public ObjectType(final String className) { } /** - * Java Virtual Machine Specification edition 2, 5.4.4 Access Control + * Java Virtual Machine Specification edition 2, 5.4.4 Access Control. * - * @throws ClassNotFoundException if the class referenced by this type can't be found + * @param accessor The accessing type. + * @return true if accessible. + * @throws ClassNotFoundException Thrown if the class referenced by this type can't be found. */ public boolean accessibleTo(final ObjectType accessor) throws ClassNotFoundException { final JavaClass jc = Repository.lookupClass(className); @@ -77,7 +79,7 @@ public boolean equals(final Object type) { } /** - * @return name of referenced class + * @return name of referenced class. */ @Override public String getClassName() { @@ -85,7 +87,9 @@ public String getClassName() { } /** - * @return a hash code value for the object. + * Gets the hash code. + * + * @return A hash code value for the object. */ @Override public int hashCode() { @@ -94,6 +98,8 @@ public int hashCode() { /** * If "this" doesn't reference a class, it references an interface or a non-existant entity. + * + * @return true if it references a class, false otherwise. * @deprecated (since 6.0) this method returns an inaccurate result if the class or interface referenced cannot be * found: use referencesClassExact() instead */ @@ -110,8 +116,8 @@ public boolean referencesClass() { /** * Return true if this type references a class, false if it references an interface. * - * @return true if the type references a class, false if it references an interface - * @throws ClassNotFoundException if the class or interface referenced by this type can't be found + * @return true if the type references a class, false if it references an interface. + * @throws ClassNotFoundException Thrown if the class or interface referenced by this type can't be found */ public boolean referencesClassExact() throws ClassNotFoundException { final JavaClass jc = Repository.lookupClass(className); @@ -121,6 +127,7 @@ public boolean referencesClassExact() throws ClassNotFoundException { /** * If "this" doesn't reference an interface, it references a class or a non-existant entity. * + * @return true if it references an interface, false otherwise. * @deprecated (since 6.0) this method returns an inaccurate result if the class or interface referenced cannot be * found: use referencesInterfaceExact() instead */ @@ -137,8 +144,8 @@ public boolean referencesInterface() { /** * Return true if this type references an interface, false if it references a class. * - * @return true if the type references an interface, false if it references a class - * @throws ClassNotFoundException if the class or interface referenced by this type can't be found + * @return true if the type references an interface, false if it references a class. + * @throws ClassNotFoundException Thrown if the class or interface referenced by this type can't be found */ public boolean referencesInterfaceExact() throws ClassNotFoundException { final JavaClass jc = Repository.lookupClass(className); @@ -148,7 +155,9 @@ public boolean referencesInterfaceExact() throws ClassNotFoundException { /** * Return true if this type is a subclass of given ObjectType. * - * @throws ClassNotFoundException if any of this class's superclasses can't be found + * @param superclass The superclass to check against. + * @return true if this is a subclass. + * @throws ClassNotFoundException Thrown if any of this class's superclasses can't be found. */ public boolean subclassOf(final ObjectType superclass) throws ClassNotFoundException { if (referencesInterfaceExact() || superclass.referencesInterfaceExact()) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP.java index e826dd78ce33..eb16a96638fa 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP.java @@ -24,21 +24,24 @@ /** * POP - Pop top operand stack word * - *
+ * 
  * Stack: ..., word -> ...
- * 
+ *
*/ public class POP extends StackInstruction implements PopInstruction { + /** + * Constructs a POP instruction. + */ public POP() { super(com.sun.org.apache.bcel.internal.Const.POP); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP2.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP2.java index 5124f4177fc6..fa5cb626a6f8 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP2.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/POP2.java @@ -24,21 +24,24 @@ /** * POP2 - Pop two top operand stack words * - *
+ * 
  * Stack: ..., word2, word1 -> ...
- * 
+ *
*/ public class POP2 extends StackInstruction implements PopInstruction { + /** + * Constructs a POP2 instruction. + */ public POP2() { super(com.sun.org.apache.bcel.internal.Const.POP2); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUSH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUSH.java index cac2027586fe..ddf55159541c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUSH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUSH.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -36,7 +36,7 @@ public final class PUSH implements CompoundInstruction, VariableLengthInstructio * Pushes an array type constant, for example {@code int[].class}, {@code String[].class}, and so on. * * @param cp generated constant pool. - * @param value to be pushed. + * @param value to push. * @since 6.7.0 */ public PUSH(final ConstantPoolGen cp, final ArrayType value) { @@ -48,8 +48,10 @@ public PUSH(final ConstantPoolGen cp, final ArrayType value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a boolean value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final boolean value) { Objects.requireNonNull(cp, "cp"); @@ -57,8 +59,10 @@ public PUSH(final ConstantPoolGen cp, final boolean value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a Boolean value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final Boolean value) { this(cp, value.booleanValue()); @@ -68,16 +72,18 @@ public PUSH(final ConstantPoolGen cp, final Boolean value) { * creates a push object from a Character value. Warning: Make sure not to attempt to allow autoboxing to create this * value parameter, as an alternative constructor will be called * - * @param cp Constant pool - * @param value to be pushed + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final Character value) { this(cp, value.charValue()); } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a double value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final double value) { if (value == 0.0) { @@ -90,8 +96,10 @@ public PUSH(final ConstantPoolGen cp, final double value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a float value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final float value) { if (value == 0.0) { @@ -108,8 +116,8 @@ public PUSH(final ConstantPoolGen cp, final float value) { /** * This constructor also applies for values of type short, char, byte * - * @param cp Constant pool - * @param value to be pushed + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final int value) { if (value >= -1 && value <= 5) { @@ -124,8 +132,10 @@ public PUSH(final ConstantPoolGen cp, final int value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a long value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final long value) { if (value == 0) { @@ -138,8 +148,10 @@ public PUSH(final ConstantPoolGen cp, final long value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a Number value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final Number value) { if (value instanceof Integer || value instanceof Short || value instanceof Byte) { @@ -156,9 +168,10 @@ public PUSH(final ConstantPoolGen cp, final Number value) { } /** + * Constructs a PUSH for an ObjectType value. * - * @param cp - * @param value + * @param cp The constant pool. + * @param value to push. * @since 6.0 */ public PUSH(final ConstantPoolGen cp, final ObjectType value) { @@ -170,8 +183,10 @@ public PUSH(final ConstantPoolGen cp, final ObjectType value) { } /** - * @param cp Constant pool - * @param value to be pushed + * Constructs a PUSH for a String value. + * + * @param cp Constant pool. + * @param value to push. */ public PUSH(final ConstantPoolGen cp, final String value) { if (value == null) { @@ -181,6 +196,11 @@ public PUSH(final ConstantPoolGen cp, final String value) { } } + /** + * Gets the instruction. + * + * @return The instruction. + */ public Instruction getInstruction() { return instruction; } @@ -191,7 +211,7 @@ public InstructionList getInstructionList() { } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTFIELD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTFIELD.java index 185a014774be..81f8d3fba12c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTFIELD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTFIELD.java @@ -27,15 +27,15 @@ /** * PUTFIELD - Put field in object * - *
+ * 
  * Stack: ..., objectref, value -> ...
- * 
+ *
* * OR * - *
+ * 
  * Stack: ..., objectref, value.word1, value.word2 -> ...
- * 
+ *
*/ public class PUTFIELD extends FieldInstruction implements PopInstruction, ExceptionThrower { @@ -45,15 +45,20 @@ public class PUTFIELD extends FieldInstruction implements PopInstruction, Except PUTFIELD() { } + /** + * Constructs a PUTFIELD instruction. + * + * @param index index into constant pool. + */ public PUTFIELD(final int index) { super(Const.PUTFIELD, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTSTATIC.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTSTATIC.java index f74ec347e9dd..da4b536c9ddc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTSTATIC.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/PUTSTATIC.java @@ -27,15 +27,15 @@ /** * PUTSTATIC - Put static field in class * - *
+ * 
  * Stack: ..., value -> ...
- * 
+ *
* * OR * - *
+ * 
  * Stack: ..., value.word1, value.word2 -> ...
- * 
+ *
*/ public class PUTSTATIC extends FieldInstruction implements ExceptionThrower, PopInstruction { @@ -45,15 +45,20 @@ public class PUTSTATIC extends FieldInstruction implements ExceptionThrower, Pop PUTSTATIC() { } + /** + * Constructs a PUTSTATIC instruction. + * + * @param index index into constant pool. + */ public PUTSTATIC(final int index) { super(Const.PUTSTATIC, index); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RET.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RET.java index 99a1efbed166..990778a8c226 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RET.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RET.java @@ -24,14 +24,15 @@ import java.io.DataOutputStream; import java.io.IOException; +import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.util.ByteSequence; /** * RET - Return from subroutine * - *
+ * 
  * Stack: ... -> ...
- * 
+ *
*/ public class RET extends Instruction implements IndexedInstruction, TypedInstruction { @@ -39,21 +40,26 @@ public class RET extends Instruction implements IndexedInstruction, TypedInstruc private int index; // index to local variable containg the return address /** - * Empty constructor needed for Instruction.readInstruction. Not to be used otherwise. + * Default constructor needed for Instruction.readInstruction. Not to be used otherwise. */ RET() { } + /** + * Constructs a RET instruction. + * + * @param index index of local variable containing the return address. + */ public RET(final int index) { - super(com.sun.org.apache.bcel.internal.Const.RET, (short) 2); + super(Const.RET, (short) 2); setIndex(index); // May set wide as side effect } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -61,14 +67,14 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { if (wide) { - out.writeByte(com.sun.org.apache.bcel.internal.Const.WIDE); + out.writeByte(Const.WIDE); } out.writeByte(super.getOpcode()); if (wide) { @@ -79,7 +85,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return index of local variable containg the return address + * @return index of local variable containg the return address. */ @Override public final int getIndex() { @@ -87,7 +93,7 @@ public final int getIndex() { } /** - * @return return address type + * @return return address type. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -95,7 +101,7 @@ public Type getType(final ConstantPoolGen cp) { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -111,18 +117,21 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws /** * Sets index of local variable containg the return address + * + * @param index index of local variable containg the return address. + * @throws ClassGenException Thrown if index is out of bounds. */ @Override - public final void setIndex(final int n) { - if (n < 0) { - throw new ClassGenException("Negative index value: " + n); + public final void setIndex(final int index) { + if (!isNonNegativeUShort(index)) { + throw new ClassGenException("Illegal value: " + index); } - index = n; + this.index = index; setWide(); } private void setWide() { - wide = index > com.sun.org.apache.bcel.internal.Const.MAX_BYTE; + wide = index > Const.MAX_BYTE; if (wide) { super.setLength(4); // Including the wide byte } else { @@ -131,7 +140,7 @@ private void setWide() { } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RETURN.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RETURN.java index 0e6b594fafa6..7598baf8d8e2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RETURN.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/RETURN.java @@ -24,21 +24,24 @@ /** * RETURN - Return from void method * - *
+ * 
  * Stack: ... -> <empty>
- * 
+ *
*/ public class RETURN extends ReturnInstruction { + /** + * Constructs a RETURN instruction. + */ public RETURN() { super(com.sun.org.apache.bcel.internal.Const.RETURN); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReferenceType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReferenceType.java index 881a3f2ebea7..09e1c3684e3e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReferenceType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReferenceType.java @@ -30,12 +30,18 @@ public abstract class ReferenceType extends Type { /** - * Class is non-abstract but not instantiable from the outside + * Class is non-abstract but not instantiable from the outside. */ ReferenceType() { super(Const.T_OBJECT, ""); } + /** + * Constructs a ReferenceType. + * + * @param t The type. + * @param s The signature. + */ protected ReferenceType(final byte t, final String s) { super(t, s); } @@ -48,8 +54,10 @@ protected ReferenceType(final byte t, final String s) { * interface, then {@link #OBJECT} is returned. If not all of the two classes' superclasses cannot be found, "null" is * returned. See the JVM specification edition 2, "4.9.2 The Bytecode Verifier". * - * @deprecated use getFirstCommonSuperclass(ReferenceType t) which has slightly changed semantics. - * @throws ClassNotFoundException on failure to find superclasses of this type, or the type passed as a parameter + * @param t The other type. + * @return The first common superclass. + * @throws ClassNotFoundException Thrown on failure to find superclasses of this type, or the type passed as a parameter. + * @deprecated Use getFirstCommonSuperclass(ReferenceType t) which has slightly changed semantics. */ @Deprecated public ReferenceType firstCommonSuperclass(final ReferenceType t) throws ClassNotFoundException { @@ -81,7 +89,9 @@ public ReferenceType firstCommonSuperclass(final ReferenceType t) throws ClassNo * the two classes' superclasses cannot be found, "null" is returned. See the JVM specification edition 2, "4.9.2 The * Bytecode Verifier". * - * @throws ClassNotFoundException on failure to find superclasses of this type, or the type passed as a parameter + * @param t The other type. + * @return The first common superclass. + * @throws ClassNotFoundException Thrown on failure to find superclasses of this type, or the type passed as a parameter. */ public ReferenceType getFirstCommonSuperclass(final ReferenceType t) throws ClassNotFoundException { if (equals(NULL)) { @@ -150,8 +160,10 @@ private ReferenceType getFirstCommonSuperclassInternal(final ReferenceType t) th * Return true iff this is assignment compatible with another type t as defined in the JVM specification; see the * AASTORE definition there. * - * @throws ClassNotFoundException if any classes or interfaces required to determine assignment compatibility can't be - * found + * @param t The other type. + * @return true iff this is assignment compatible with another type t. + * @throws ClassNotFoundException Thrown if any classes or interfaces required to determine assignment compatibility can't be + * found. */ public boolean isAssignmentCompatibleWith(final Type t) throws ClassNotFoundException { if (!(t instanceof ReferenceType)) { @@ -246,11 +258,13 @@ public boolean isAssignmentCompatibleWith(final Type t) throws ClassNotFoundExce /** * Return true iff this type is castable to another type t as defined in the JVM specification. The case where this is - * {@link #NULL} is not defined (see the CHECKCAST definition in the JVM specification). However, because e.g. CHECKCAST + * {@link #NULL} is not defined (see the CHECKCAST definition in the JVM specification). However, because for example CHECKCAST * doesn't throw a ClassCastException when casting a null reference to any Object, true is returned in this case. * - * @throws ClassNotFoundException if any classes or interfaces required to determine assignment compatibility can't be - * found + * @param t The other type. + * @return true iff this type is castable to another type t. + * @throws ClassNotFoundException Thrown if any classes or interfaces required to determine assignment compatibility can't be + * found. */ public boolean isCastableTo(final Type t) throws ClassNotFoundException { if (equals(NULL)) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnInstruction.java index 0e132f431c48..e36034d2ddea 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -26,7 +26,7 @@ /** * Super class for the xRETURN family of instructions. * - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public abstract class ReturnInstruction extends Instruction implements ExceptionThrower, TypedInstruction, StackConsumer { @@ -37,7 +37,9 @@ public abstract class ReturnInstruction extends Instruction implements Exception } /** - * @param opcode of instruction + * Constructs a ReturnInstruction. + * + * @param opcode of instruction. */ protected ReturnInstruction(final short opcode) { super(opcode, (short) 1); @@ -48,6 +50,11 @@ public Class[] getExceptions() { return new Class[] {ExceptionConst.ILLEGAL_MONITOR_STATE}; } + /** + * Gets the type of the returned value. + * + * @return The type. + */ public Type getType() { final short opcode = super.getOpcode(); switch (opcode) { @@ -69,7 +76,7 @@ public Type getType() { } /** - * @return type associated with the instruction + * @return type associated with the instruction. */ @Override public Type getType(final ConstantPoolGen cp) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnaddressType.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnaddressType.java index a35e83d26fd6..e18e95179778 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnaddressType.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/ReturnaddressType.java @@ -30,6 +30,7 @@ */ public class ReturnaddressType extends Type { + /** Predefined constant for a returnaddress with no target. */ public static final ReturnaddressType NO_TARGET = new ReturnaddressType(); private InstructionHandle returnTarget; @@ -42,6 +43,8 @@ private ReturnaddressType() { /** * Creates a ReturnaddressType object with a target. + * + * @param returnTarget The target instruction. */ public ReturnaddressType(final InstructionHandle returnTarget) { super(Const.T_ADDRESS, ""); @@ -50,6 +53,9 @@ public ReturnaddressType(final InstructionHandle returnTarget) { /** * Returns if the two Returnaddresses refer to the same target. + * + * @param rat The object to compare. + * @return true if equal. */ @Override public boolean equals(final Object rat) { @@ -64,14 +70,16 @@ public boolean equals(final Object rat) { } /** - * @return the target of this ReturnaddressType + * Gets the target of this ReturnaddressType. + * + * @return The target of this ReturnaddressType. */ public InstructionHandle getTarget() { return returnTarget; } /** - * @return a hash code value for the object. + * @return A hash code value for the object. */ @Override public int hashCode() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SALOAD.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SALOAD.java index 9499e5660f01..66860d92338f 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SALOAD.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SALOAD.java @@ -24,21 +24,24 @@ /** * SALOAD - Load short from array * - *
+ * 
  * Stack: ..., arrayref, index -> ..., value
- * 
+ *
*/ public class SALOAD extends ArrayInstruction implements StackProducer { + /** + * Constructs a SALOAD instruction. + */ public SALOAD() { super(com.sun.org.apache.bcel.internal.Const.SALOAD); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SASTORE.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SASTORE.java index c9c42d3d339f..ca47f8fd72b4 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SASTORE.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SASTORE.java @@ -24,21 +24,24 @@ /** * SASTORE - Store into short array * - *
+ * 
  * Stack: ..., arrayref, index, value -> ...
- * 
+ *
*/ public class SASTORE extends ArrayInstruction implements StackConsumer { + /** + * Constructs a SASTORE instruction. + */ public SASTORE() { super(com.sun.org.apache.bcel.internal.Const.SASTORE); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SIPUSH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SIPUSH.java index 513495e062f4..457e5b8f4b0b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SIPUSH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SIPUSH.java @@ -28,9 +28,9 @@ /** * SIPUSH - Push short * - *
+ * 
  * Stack: ... -> ..., value
- * 
+ *
*/ public class SIPUSH extends Instruction implements ConstantPushInstruction { @@ -42,6 +42,11 @@ public class SIPUSH extends Instruction implements ConstantPushInstruction { SIPUSH() { } + /** + * Constructs a SIPUSH. + * + * @param b The value. + */ public SIPUSH(final short b) { super(com.sun.org.apache.bcel.internal.Const.SIPUSH, (short) 3); this.b = b; @@ -49,9 +54,9 @@ public SIPUSH(final short b) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -63,7 +68,7 @@ public void accept(final Visitor v) { } /** - * Dump instruction as short code to stream out. + * Dumps instruction as short code to stream out. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -72,7 +77,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return Type.SHORT + * @return Type.SHORT. */ @Override public Type getType(final ConstantPoolGen cp) { @@ -85,7 +90,7 @@ public Number getValue() { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -94,7 +99,7 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWAP.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWAP.java index e3c0a46de731..a8bd755df5c9 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWAP.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWAP.java @@ -24,21 +24,24 @@ /** * SWAP - Swa top operand stack word * - *
+ * 
  * Stack: ..., word2, word1 -> ..., word1, word2
- * 
+ *
*/ public class SWAP extends StackInstruction implements StackConsumer, StackProducer { + /** + * Constructs a SWAP instruction. + */ public SWAP() { super(com.sun.org.apache.bcel.internal.Const.SWAP); } /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWITCH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWITCH.java index f929176c1749..56a96054bfe6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWITCH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SWITCH.java @@ -78,6 +78,13 @@ private static void sort(final int l, final int r, final int[] match, final Inst private final Select instruction; + /** + * Constructs a SWITCH with default maxGap of 1. + * + * @param match array of match values. + * @param targets The instructions to be branched to for each case. + * @param target The default target. + */ public SWITCH(final int[] match, final InstructionHandle[] targets, final InstructionHandle target) { this(match, targets, target, 1); } @@ -89,10 +96,10 @@ public SWITCH(final int[] match, final InstructionHandle[] targets, final Instru * * Note, that the key array always will be sorted, though we leave the original arrays unaltered. * - * @param match array of match values (case 2: ... case 7: ..., etc.) - * @param targets the instructions to be branched to for each case - * @param target the default target - * @param maxGap maximum gap that may between case branches + * @param match array of match values (case 2: ... case 7: ..., etc.). + * @param targets The instructions to be branched to for each case. + * @param target The default target. + * @param maxGap maximum gap that may between case branches. */ public SWITCH(final int[] match, final InstructionHandle[] targets, final InstructionHandle target, final int maxGap) { final int[] matchClone = match.clone(); @@ -107,18 +114,18 @@ public SWITCH(final int[] match, final InstructionHandle[] targets, final Instru final int[] mVec = new int[maxSize]; final InstructionHandle[] tVec = new InstructionHandle[maxSize]; int count = 1; - mVec[0] = match[0]; - tVec[0] = targets[0]; + mVec[0] = matchClone[0]; + tVec[0] = targetsClone[0]; for (int i = 1; i < matchLength; i++) { - final int prev = match[i - 1]; - final int gap = match[i] - prev; + final int prev = matchClone[i - 1]; + final int gap = matchClone[i] - prev; for (int j = 1; j < gap; j++) { mVec[count] = prev + j; tVec[count] = target; count++; } - mVec[count] = match[i]; - tVec[count] = targets[i]; + mVec[count] = matchClone[i]; + tVec[count] = targetsClone[i]; count++; } instruction = new TABLESWITCH(Arrays.copyOf(mVec, count), Arrays.copyOf(tVec, count), target); @@ -128,6 +135,11 @@ public SWITCH(final int[] match, final InstructionHandle[] targets, final Instru } } + /** + * Gets the instruction. + * + * @return The instruction. + */ public Instruction getInstruction() { return instruction; } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Select.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Select.java index a3086ac16642..c77e7113ae3a 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Select.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Select.java @@ -33,7 +33,6 @@ * @see LOOKUPSWITCH * @see TABLESWITCH * @see InstructionList - * @LastModified: Sept 2025 */ public abstract class Select extends BranchInstruction implements VariableLengthInstruction, StackConsumer /* @since 6.0 */, StackProducer { @@ -41,7 +40,7 @@ public abstract class Select extends BranchInstruction implements VariableLength * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter */ @Deprecated - protected int[] match; // matches, i.e., case 1: ... TODO could be package-protected? + protected int[] match; // matches, that is, case 1: ... TODO could be package-protected? /** * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter @@ -82,9 +81,9 @@ public abstract class Select extends BranchInstruction implements VariableLength /** * (Match, target) pairs for switch. 'Match' and 'targets' must have the same length of course. * - * @param match array of matching values - * @param targets instruction targets - * @param defaultTarget default instruction target + * @param match array of matching values. + * @param targets instruction targets. + * @param defaultTarget default instruction target. */ Select(final short opcode, final int[] match, final InstructionHandle[] targets, final InstructionHandle defaultTarget) { // don't set default target before instruction is built @@ -112,7 +111,7 @@ protected Object clone() throws CloneNotSupportedException { } /** - * @return true, if ih is target of this instruction + * @return true, if ih is target of this instruction. */ @Override public boolean containsTarget(final InstructionHandle ih) { @@ -139,9 +138,9 @@ void dispose() { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -154,7 +153,7 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * @return the fixed_length + * @return The fixed_length. * @since 6.0 */ final int getFixedLength() { @@ -162,14 +161,16 @@ final int getFixedLength() { } /** - * @return array of match target offsets + * Gets the match target offsets. + * + * @return array of match target offsets. */ public int[] getIndices() { return indices; } /** - * @return index entry from indices + * @return index entry from indices. * @since 6.0 */ final int getIndices(final int index) { @@ -177,7 +178,7 @@ final int getIndices(final int index) { } /** - * @return match entry + * @return match entry. * @since 6.0 */ final int getMatch(final int index) { @@ -185,7 +186,7 @@ final int getMatch(final int index) { } /** - * @return the match_length + * @return The match_length. * @since 6.0 */ final int getMatchLength() { @@ -193,7 +194,9 @@ final int getMatchLength() { } /** - * @return array of match indices + * Gets the match indices. + * + * @return array of match indices. */ public int[] getMatchs() { return match; @@ -201,7 +204,7 @@ public int[] getMatchs() { /** * - * @return the padding + * @return The padding. * @since 6.0 */ final int getPadding() { @@ -209,7 +212,7 @@ final int getPadding() { } /** - * @return target entry + * @return target entry. * @since 6.0 */ final InstructionHandle getTarget(final int index) { @@ -217,14 +220,16 @@ final InstructionHandle getTarget(final int index) { } /** - * @return array of match targets + * Gets the match targets. + * + * @return array of match targets. */ public InstructionHandle[] getTargets() { return targets; } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { @@ -237,7 +242,7 @@ protected void initFromFile(final ByteSequence bytes, final boolean wide) throws } /** - * @param fixedLength the fixed_length to set + * @param fixedLength The fixed_length to set. * @since 6.0 */ final void setFixedLength(final int fixedLength) { @@ -252,7 +257,7 @@ final int setIndices(final int i, final int value) { /** * - * @param array + * @param array. * @since 6.0 */ final void setIndices(final int[] array) { @@ -261,8 +266,8 @@ final void setIndices(final int[] array) { /** * - * @param index - * @param value + * @param index. + * @param value. * @since 6.0 */ final void setMatch(final int index, final int value) { @@ -271,7 +276,7 @@ final void setMatch(final int index, final int value) { /** * - * @param array + * @param array. * @since 6.0 */ final void setMatches(final int[] array) { @@ -279,7 +284,7 @@ final void setMatches(final int[] array) { } /** - * @param matchLength the match_length to set + * @param matchLength The match_length to set. * @since 6.0 */ final int setMatchLength(final int matchLength) { @@ -288,7 +293,10 @@ final int setMatchLength(final int matchLength) { } /** - * Sets branch target for 'i'th case + * Sets branch target for 'i'th case. + * + * @param i The case index. + * @param target The branch target. */ public void setTarget(final int i, final InstructionHandle target) { // TODO could be package-protected? notifyTarget(targets[i], target, this); @@ -297,7 +305,7 @@ public void setTarget(final int i, final InstructionHandle target) { // TODO cou /** * - * @param array + * @param array. * @since 6.0 */ final void setTargets(final InstructionHandle[] array) { @@ -305,7 +313,7 @@ final void setTargets(final InstructionHandle[] array) { } /** - * @return mnemonic for instruction + * @return mnemonic for instruction. */ @Override public String toString(final boolean verbose) { @@ -336,9 +344,9 @@ public String toString(final boolean verbose) { * length instructions 'setPositions' performs multiple passes over the instruction list to calculate the correct (byte) * positions and offsets by calling this function. * - * @param offset additional offset caused by preceding (variable length) instructions - * @param maxOffset the maximum offset that may be caused by these instructions - * @return additional offset caused by possible change of this instruction's length + * @param offset additional offset caused by preceding (variable length) instructions. + * @param maxOffset The maximum offset that may be caused by these instructions. + * @return additional offset caused by possible change of this instruction's length. */ @Override protected int updatePosition(final int offset, final int maxOffset) { @@ -353,8 +361,8 @@ protected int updatePosition(final int offset, final int maxOffset) { } /** - * @param oldIh old target - * @param newIh new target + * @param oldIh old target. + * @param newIh new target. */ @Override public void updateTarget(final InstructionHandle oldIh, final InstructionHandle newIh) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SimpleElementValueGen.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SimpleElementValueGen.java index 363b3237632c..6cb33eb3848c 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SimpleElementValueGen.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/SimpleElementValueGen.java @@ -33,6 +33,8 @@ import com.sun.org.apache.bcel.internal.classfile.SimpleElementValue; /** + * Generates simple element values in annotations. + * * @since 6.0 */ public class SimpleElementValueGen extends ElementValueGen { @@ -41,6 +43,13 @@ public class SimpleElementValueGen extends ElementValueGen { // For 'class' this points to the class entry in the cpGen private final int idx; + /** + * Constructs a SimpleElementValueGen for a boolean value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The boolean value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final boolean value) { super(type, cpGen); if (value) { @@ -50,41 +59,97 @@ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final } } + /** + * Constructs a SimpleElementValueGen for a byte value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The byte value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final byte value) { super(type, cpGen); idx = getConstantPool().addInteger(value); } + /** + * Constructs a SimpleElementValueGen for a char value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The char value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final char value) { super(type, cpGen); idx = getConstantPool().addInteger(value); } + /** + * Constructs a SimpleElementValueGen for a double value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The double value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final double value) { super(type, cpGen); idx = getConstantPool().addDouble(value); } + /** + * Constructs a SimpleElementValueGen for a float value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The float value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final float value) { super(type, cpGen); idx = getConstantPool().addFloat(value); } + /** + * Constructs a SimpleElementValueGen for an int value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The int value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final int value) { super(type, cpGen); idx = getConstantPool().addInteger(value); } + /** + * Constructs a SimpleElementValueGen for a long value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The long value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final long value) { super(type, cpGen); idx = getConstantPool().addLong(value); } + /** + * Constructs a SimpleElementValueGen for a short value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The short value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final short value) { super(type, cpGen); idx = getConstantPool().addInteger(value); } + /** + * Constructs a SimpleElementValueGen for a String value. + * + * @param type The element value type. + * @param cpGen The constant pool generator. + * @param value The string value. + */ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final String value) { super(type, cpGen); idx = getConstantPool().addUtf8(value); @@ -92,9 +157,14 @@ public SimpleElementValueGen(final int type, final ConstantPoolGen cpGen, final // ctors for each supported type... type could be inferred but for now lets // force it to be passed + /** * Protected ctor used for deserialization, doesn't *put* an entry in the constant pool, assumes the one at the supplied * index is correct. + * + * @param type The element value type. + * @param idx The constant pool index. + * @param cpGen The constant pool generator. */ protected SimpleElementValueGen(final int type, final int idx, final ConstantPoolGen cpGen) { super(type, cpGen); @@ -104,6 +174,10 @@ protected SimpleElementValueGen(final int type, final int idx, final ConstantPoo /** * The boolean controls whether we copy info from the 'old' constant pool to the 'new'. You need to use this ctor if the * annotation is being copied from one file to another. + * + * @param value The simple element value to copy. + * @param cpool The constant pool generator. + * @param copyPoolEntries whether to copy pool entries. */ public SimpleElementValueGen(final SimpleElementValue value, final ConstantPoolGen cpool, final boolean copyPoolEntries) { super(value.getElementValueType(), cpool); @@ -171,17 +245,29 @@ public void dump(final DataOutputStream dos) throws IOException { } /** - * Return immutable variant + * Gets the immutable variant. + * + * @return The immutable variant. */ @Override public ElementValue getElementValue() { return new SimpleElementValue(super.getElementValueType(), idx, getConstantPool().getConstantPool()); } + /** + * Gets the constant pool index. + * + * @return The index. + */ public int getIndex() { return idx; } + /** + * Gets the int value. + * + * @return The int value. + */ public int getValueInt() { if (super.getElementValueType() != PRIMITIVE_INT) { throw new IllegalStateException("Don't call getValueString() on a non STRING ElementValue"); @@ -190,6 +276,11 @@ public int getValueInt() { return c.getBytes(); } + /** + * Gets the string value. + * + * @return The string value. + */ public String getValueString() { if (super.getElementValueType() != STRING) { throw new IllegalStateException("Don't call getValueString() on a non STRING ElementValue"); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackConsumer.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackConsumer.java index c0709a46b285..2ce40aa8833b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackConsumer.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackConsumer.java @@ -27,7 +27,10 @@ public interface StackConsumer { /** - * @return how many words are consumed from stack + * Gets how many words are consumed from stack. + * + * @param cpg The constant pool generator. + * @return how many words are consumed from stack. */ int consumeStack(ConstantPoolGen cpg); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackInstruction.java index 313215122955..9169fc824921 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackInstruction.java @@ -33,14 +33,19 @@ public abstract class StackInstruction extends Instruction { } /** - * @param opcode instruction opcode + * Constructs a StackInstruction. + * + * @param opcode instruction opcode. */ protected StackInstruction(final short opcode) { super(opcode, (short) 1); } /** - * @return Type.UNKNOWN + * Gets the type. + * + * @param cp The constant pool. + * @return Type.UNKNOWN. */ public Type getType(final ConstantPoolGen cp) { return Type.UNKNOWN; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackProducer.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackProducer.java index f660e3b329fa..05c743781dbb 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackProducer.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StackProducer.java @@ -22,12 +22,15 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Denotes an instruction that may produce a value on top of the stack (this excludes DUP_X1, e.g.) + * Denotes an instruction that may produce a value on top of the stack (this excludes DUP_X1, for example) */ public interface StackProducer { /** - * @return how many words are produced on stack + * Gets how many words are produced on stack. + * + * @param cpg The constant pool generator. + * @return how many words are produced on stack. */ int produceStack(ConstantPoolGen cpg); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StoreInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StoreInstruction.java index ceef3a8b794e..78ea370fb77b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StoreInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/StoreInstruction.java @@ -22,7 +22,7 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Denotes an unparameterized instruction to store a value into a local variable, e.g. ISTORE. + * Denotes an unparameterized instruction to store a value into a local variable, for example ISTORE. */ public abstract class StoreInstruction extends LocalVariableInstruction implements PopInstruction { @@ -35,9 +35,11 @@ public abstract class StoreInstruction extends LocalVariableInstruction implemen } /** - * @param opcode Instruction opcode - * @param cTag Instruction number for compact version, ASTORE_0, e.g. - * @param n local variable index (unsigned short) + * Constructs a StoreInstruction. + * + * @param opcode Instruction opcode. + * @param cTag Instruction number for compact version, ASTORE_0, for example. + * @param n local variable index (unsigned short). */ protected StoreInstruction(final short opcode, final short cTag, final int n) { super(opcode, cTag, n); @@ -45,9 +47,9 @@ protected StoreInstruction(final short opcode, final short cTag, final int n) { /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TABLESWITCH.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TABLESWITCH.java index e38da5eec771..eaa82c25f631 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TABLESWITCH.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TABLESWITCH.java @@ -24,10 +24,11 @@ import java.io.DataOutputStream; import java.io.IOException; +import com.sun.org.apache.bcel.internal.classfile.ClassFormatException; import com.sun.org.apache.bcel.internal.util.ByteSequence; /** - * TABLESWITCH - Switch within given range of values, i.e., low..high + * TABLESWITCH - Switch within given range of values, that is, low..high * * @see SWITCH */ @@ -40,9 +41,11 @@ public class TABLESWITCH extends Select { } /** - * @param match sorted array of match values, match[0] must be low value, match[match_length - 1] high value - * @param targets where to branch for matched values - * @param defaultTarget default branch + * Constructs a TABLESWITCH instruction. + * + * @param match sorted array of match values, match[0] must be low value, match[match_length - 1] high value. + * @param targets where to branch for matched values. + * @param defaultTarget default branch. */ public TABLESWITCH(final int[] match, final InstructionHandle[] targets, final InstructionHandle defaultTarget) { super(com.sun.org.apache.bcel.internal.Const.TABLESWITCH, match, targets, defaultTarget); @@ -54,9 +57,9 @@ public TABLESWITCH(final int[] match, final InstructionHandle[] targets, final I /** * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call - * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last. + * methods according to the class hierarchy in descending order, that is, the most specific visitXXX() call comes last. * - * @param v Visitor object + * @param v Visitor object. */ @Override public void accept(final Visitor v) { @@ -68,9 +71,9 @@ public void accept(final Visitor v) { } /** - * Dump instruction as byte code to stream out. + * Dumps instruction as byte code to stream out. * - * @param out Output stream + * @param out Output stream. */ @Override public void dump(final DataOutputStream out) throws IOException { @@ -86,14 +89,22 @@ public void dump(final DataOutputStream out) throws IOException { } /** - * Read needed data (e.g. index) from file. + * Reads needed data (for example index) from file. */ @Override protected void initFromFile(final ByteSequence bytes, final boolean wide) throws IOException { super.initFromFile(bytes, wide); final int low = bytes.readInt(); final int high = bytes.readInt(); - final int matchLength = high - low + 1; + // Compute in long arithmetic to guard against integer overflow, and require the match table to actually fit into the remaining code bytes (4 bytes + // per jump offset). The low and high fields are attacker-controlled in a malicious class file and could otherwise request a multi-gigabyte + // allocation, or a negative array size, before a single table entry is read. + final long matchLengthLong = (long) high - low + 1; + if (matchLengthLong < 0 || matchLengthLong > bytes.available() / 4) { + throw new ClassFormatException( + "Invalid tableswitch: low=" + low + ", high=" + high + ", but only " + bytes.available() + " bytes of code remain."); + } + final int matchLength = (int) matchLengthLong; setMatchLength(matchLength); final short fixedLength = (short) (13 + matchLength * 4); setFixedLength(fixedLength); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TargetLostException.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TargetLostException.java index 038bbe631481..a827c9b2cdb6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TargetLostException.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TargetLostException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -46,7 +46,7 @@ * @see InstructionHandle * @see InstructionList * @see InstructionTargeter - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public final class TargetLostException extends Exception { @@ -54,6 +54,12 @@ public final class TargetLostException extends Exception { @SuppressWarnings("serial") // Array component type is not Serializable private final InstructionHandle[] targets; + /** + * Constructs a TargetLostException. + * + * @param targets The instruction handles. + * @param message The exception message. + */ TargetLostException(final InstructionHandle[] targets, final String message) { super(message); this.targets = targets; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Type.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Type.java index b58645b402e9..246f75a23882 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Type.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Type.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -32,8 +32,8 @@ /** * Abstract super class for all possible Java types, namely basic types such as int, object types like String and array - * types, e.g. int[] - * @LastModified: Sept 2025 + * types, for example int[] + * @LastModified: Nov 2026 */ public abstract class Type { @@ -42,27 +42,54 @@ public abstract class Type { */ public static final BasicType VOID = new BasicType(Const.T_VOID); + /** Predefined constant for boolean type. */ public static final BasicType BOOLEAN = new BasicType(Const.T_BOOLEAN); + + /** Predefined constant for int type. */ public static final BasicType INT = new BasicType(Const.T_INT); + + /** Predefined constant for short type. */ public static final BasicType SHORT = new BasicType(Const.T_SHORT); + + /** Predefined constant for byte type. */ public static final BasicType BYTE = new BasicType(Const.T_BYTE); + + /** Predefined constant for long type. */ public static final BasicType LONG = new BasicType(Const.T_LONG); + + /** Predefined constant for double type. */ public static final BasicType DOUBLE = new BasicType(Const.T_DOUBLE); + + /** Predefined constant for float type. */ public static final BasicType FLOAT = new BasicType(Const.T_FLOAT); + + /** Predefined constant for char type. */ public static final BasicType CHAR = new BasicType(Const.T_CHAR); + + /** Predefined constant for Object type. */ public static final ObjectType OBJECT = new ObjectType("java.lang.Object"); + + /** Predefined constant for Class type. */ public static final ObjectType CLASS = new ObjectType("java.lang.Class"); + + /** Predefined constant for String type. */ public static final ObjectType STRING = new ObjectType("java.lang.String"); + + /** Predefined constant for StringBuffer type. */ public static final ObjectType STRINGBUFFER = new ObjectType("java.lang.StringBuffer"); + + /** Predefined constant for Throwable type. */ public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable"); /** * Empty array. */ public static final Type[] NO_ARGS = {}; + /** Predefined constant for null type. */ public static final ReferenceType NULL = new ReferenceType() { }; + /** Predefined constant for unknown type. */ public static final Type UNKNOWN = new Type(Const.T_UNKNOWN, "") { }; @@ -80,8 +107,8 @@ static int encode(final int size, final int consumed) { /** * Convert arguments of a method (signature) to an array of Type objects. * - * @param signature signature string such as (Ljava/lang/String;)V - * @return array of argument types + * @param signature signature string such as (Ljava/lang/String;)V. + * @return array of argument types. */ public static Type[] getArgumentTypes(final String signature) { final List vec = new ArrayList<>(); @@ -126,10 +153,10 @@ static int getArgumentTypesSize(final String signature) { } /** - * Convert type to Java method signature, e.g. int[] f(java.lang.String x) becomes (Ljava/lang/String;)[I + * Convert type to Java method signature, for example int[] f(java.lang.String x) becomes (Ljava/lang/String;)[I * - * @param returnType what the method returns - * @param argTypes what are the argument types + * @param returnType what the method returns. + * @param argTypes what are the argument types. * @return method signature for given type(s). */ public static String getMethodSignature(final Type returnType, final Type[] argTypes) { @@ -147,8 +174,8 @@ public static String getMethodSignature(final Type returnType, final Type[] argT /** * Convert return value of a method (signature) to a Type object. * - * @param signature signature string such as (Ljava/lang/String;)V - * @return return type + * @param signature signature string such as (Ljava/lang/String;)V. + * @return return type. */ public static Type getReturnType(final String signature) { try { @@ -165,6 +192,12 @@ static int getReturnTypeSize(final String signature) { return size(getTypeSize(signature.substring(index))); } + /** + * Gets the signature for a method. + * + * @param meth The method. + * @return The method signature. + */ public static String getSignature(final java.lang.reflect.Method meth) { final StringBuilder sb = new StringBuilder("("); final Class[] params = meth.getParameterTypes(); // avoid clone @@ -179,8 +212,8 @@ public static String getSignature(final java.lang.reflect.Method meth) { /** * Convert runtime {@link Class} to BCEL Type object. * - * @param cls Java class - * @return corresponding Type object + * @param cls Java class. + * @return corresponding Type object. */ public static Type getType(final Class cls) { Objects.requireNonNull(cls, "cls"); @@ -226,8 +259,8 @@ public static Type getType(final Class cls) { /** * Convert signature to a Type object. * - * @param signature signature string such as Ljava/lang/String; - * @return type object + * @param signature signature string such as Ljava/lang/String;. + * @return type object. */ public static Type getType(final String signature) throws StringIndexOutOfBoundsException { final byte type = Utility.typeOfSignature(signature); @@ -258,8 +291,8 @@ public static Type getType(final String signature) throws StringIndexOutOfBounds /** * Convert runtime {@code java.lang.Class[]} to BCEL Type objects. * - * @param classes an array of runtime class objects - * @return array of corresponding Type objects + * @param classes An array of runtime class objects. + * @return array of corresponding Type objects. */ public static Type[] getTypes(final Class[] classes) { final Type[] ret = new Type[classes.length]; @@ -330,13 +363,19 @@ private static void wrap(final ThreadLocal tl, final int value) { @Deprecated protected String signature; // signature for the type TODO should be private + /** + * Constructs a Type. + * + * @param type The type constant. + * @param signature The type signature. + */ protected Type(final byte type, final String signature) { this.type = type; this.signature = signature; } /** - * @return whether the Types are equal + * @return whether the Types are equal. */ @Override public boolean equals(final Object o) { @@ -347,11 +386,18 @@ public boolean equals(final Object o) { return false; } + /** + * Gets the class name. + * + * @return The class name. + */ public String getClassName() { return toString(); } /** + * Gets the signature for this type. + * * @return signature for given type. */ public String getSignature() { @@ -359,7 +405,9 @@ public String getSignature() { } /** - * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise) + * Gets the stack size of this type. + * + * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise). */ public int getSize() { switch (type) { @@ -374,14 +422,18 @@ public int getSize() { } /** - * @return type as defined in Constants + * Gets the type as defined in Constants. + * + * @return type as defined in Constants. */ public byte getType() { return type; } /** - * @return hash code of Type + * Gets the hash code of this Type. + * + * @return hash code of Type. */ @Override public int hashCode() { @@ -392,6 +444,7 @@ public int hashCode() { * boolean, short and char variable are considered as int in the stack or local variable area. Returns {@link #INT} * for {@link #BOOLEAN}, {@link #SHORT} or {@link #CHAR}, otherwise returns the given type. * + * @return The normalized type. * @since 6.0 */ public Type normalizeForStackOrLocal() { @@ -402,7 +455,7 @@ public Type normalizeForStackOrLocal() { } /** - * @return Type string, e.g. 'int[]' + * @return Type string, for example 'int[]'. */ @Override public String toString() { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TypedInstruction.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TypedInstruction.java index 27b952f3996e..dcd0cdb37853 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TypedInstruction.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/TypedInstruction.java @@ -22,9 +22,15 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Gets the type associated with an instruction, int for ILOAD, or the type of the field of a PUTFIELD instruction, e.g.. + * Gets the type associated with an instruction, int for ILOAD, or the type of the field of a PUTFIELD instruction. */ public interface TypedInstruction { + /** + * Gets the type associated with this instruction. + * + * @param cpg The constant pool generator. + * @return The type associated with this instruction. + */ Type getType(ConstantPoolGen cpg); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/UnconditionalBranch.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/UnconditionalBranch.java index 8ccd7313e119..e4a18fd2c748 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/UnconditionalBranch.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/UnconditionalBranch.java @@ -22,7 +22,7 @@ package com.sun.org.apache.bcel.internal.generic; /** - * Denotes an instruction to perform an unconditional branch, i.e., GOTO, JSR. + * Denotes an instruction to perform an unconditional branch, that is, GOTO, JSR. * * @see GOTO * @see JSR diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Visitor.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Visitor.java index fd70e8cd5542..67e825d49a66 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Visitor.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/Visitor.java @@ -27,368 +27,1271 @@ */ public interface Visitor { + /** + * Visits an AALOAD instruction. + * + * @param obj The instruction. + */ void visitAALOAD(AALOAD obj); + /** + * Visits an AASTORE instruction. + * + * @param obj The instruction. + */ void visitAASTORE(AASTORE obj); + /** + * Visits an ACONST_NULL instruction. + * + * @param obj The instruction. + */ void visitACONST_NULL(ACONST_NULL obj); + /** + * Visits an AllocationInstruction. + * + * @param obj The instruction. + */ void visitAllocationInstruction(AllocationInstruction obj); + /** + * Visits an ALOAD instruction. + * + * @param obj The instruction. + */ void visitALOAD(ALOAD obj); + /** + * Visits an ANEWARRAY instruction. + * + * @param obj The instruction. + */ void visitANEWARRAY(ANEWARRAY obj); + /** + * Visits an ARETURN instruction. + * + * @param obj The instruction. + */ void visitARETURN(ARETURN obj); + /** + * Visits an ArithmeticInstruction. + * + * @param obj The instruction. + */ void visitArithmeticInstruction(ArithmeticInstruction obj); + /** + * Visits an ArrayInstruction. + * + * @param obj The instruction. + */ void visitArrayInstruction(ArrayInstruction obj); + /** + * Visits an ARRAYLENGTH instruction. + * + * @param obj The instruction. + */ void visitARRAYLENGTH(ARRAYLENGTH obj); + /** + * Visits an ASTORE instruction. + * + * @param obj The instruction. + */ void visitASTORE(ASTORE obj); + /** + * Visits an ATHROW instruction. + * + * @param obj The instruction. + */ void visitATHROW(ATHROW obj); + /** + * Visits a BALOAD instruction. + * + * @param obj The instruction. + */ void visitBALOAD(BALOAD obj); + /** + * Visits a BASTORE instruction. + * + * @param obj The instruction. + */ void visitBASTORE(BASTORE obj); + /** + * Visits a BIPUSH instruction. + * + * @param obj The instruction. + */ void visitBIPUSH(BIPUSH obj); + /** + * Visits a BranchInstruction. + * + * @param obj The instruction. + */ void visitBranchInstruction(BranchInstruction obj); + /** + * Visits a BREAKPOINT instruction. + * + * @param obj The instruction. + */ void visitBREAKPOINT(BREAKPOINT obj); + /** + * Visits a CALOAD instruction. + * + * @param obj The instruction. + */ void visitCALOAD(CALOAD obj); + /** + * Visits a CASTORE instruction. + * + * @param obj The instruction. + */ void visitCASTORE(CASTORE obj); + /** + * Visits a CHECKCAST instruction. + * + * @param obj The instruction. + */ void visitCHECKCAST(CHECKCAST obj); + /** + * Visits a ConstantPushInstruction. + * + * @param obj The instruction. + */ void visitConstantPushInstruction(ConstantPushInstruction obj); + /** + * Visits a ConversionInstruction. + * + * @param obj The instruction. + */ void visitConversionInstruction(ConversionInstruction obj); + /** + * Visits a CPInstruction. + * + * @param obj The instruction. + */ void visitCPInstruction(CPInstruction obj); + /** + * Visits a D2F instruction. + * + * @param obj The instruction. + */ void visitD2F(D2F obj); + /** + * Visits a D2I instruction. + * + * @param obj The instruction. + */ void visitD2I(D2I obj); + /** + * Visits a D2L instruction. + * + * @param obj The instruction. + */ void visitD2L(D2L obj); + /** + * Visits a DADD instruction. + * + * @param obj The instruction. + */ void visitDADD(DADD obj); + /** + * Visits a DALOAD instruction. + * + * @param obj The instruction. + */ void visitDALOAD(DALOAD obj); + /** + * Visits a DASTORE instruction. + * + * @param obj The instruction. + */ void visitDASTORE(DASTORE obj); + /** + * Visits a DCMPG instruction. + * + * @param obj The instruction. + */ void visitDCMPG(DCMPG obj); + /** + * Visits a DCMPL instruction. + * + * @param obj The instruction. + */ void visitDCMPL(DCMPL obj); + /** + * Visits a DCONST instruction. + * + * @param obj The instruction. + */ void visitDCONST(DCONST obj); + /** + * Visits a DDIV instruction. + * + * @param obj The instruction. + */ void visitDDIV(DDIV obj); + /** + * Visits a DLOAD instruction. + * + * @param obj The instruction. + */ void visitDLOAD(DLOAD obj); + /** + * Visits a DMUL instruction. + * + * @param obj The instruction. + */ void visitDMUL(DMUL obj); + /** + * Visits a DNEG instruction. + * + * @param obj The instruction. + */ void visitDNEG(DNEG obj); + /** + * Visits a DREM instruction. + * + * @param obj The instruction. + */ void visitDREM(DREM obj); + /** + * Visits a DRETURN instruction. + * + * @param obj The instruction. + */ void visitDRETURN(DRETURN obj); + /** + * Visits a DSTORE instruction. + * + * @param obj The instruction. + */ void visitDSTORE(DSTORE obj); + /** + * Visits a DSUB instruction. + * + * @param obj The instruction. + */ void visitDSUB(DSUB obj); + /** + * Visits a DUP instruction. + * + * @param obj The instruction. + */ void visitDUP(DUP obj); + /** + * Visits a DUP_X1 instruction. + * + * @param obj The instruction. + */ void visitDUP_X1(DUP_X1 obj); + /** + * Visits a DUP_X2 instruction. + * + * @param obj The instruction. + */ void visitDUP_X2(DUP_X2 obj); + /** + * Visits a DUP2 instruction. + * + * @param obj The instruction. + */ void visitDUP2(DUP2 obj); + /** + * Visits a DUP2_X1 instruction. + * + * @param obj The instruction. + */ void visitDUP2_X1(DUP2_X1 obj); + /** + * Visits a DUP2_X2 instruction. + * + * @param obj The instruction. + */ void visitDUP2_X2(DUP2_X2 obj); + /** + * Visits an ExceptionThrower. + * + * @param obj The instruction. + */ void visitExceptionThrower(ExceptionThrower obj); + /** + * Visits an F2D instruction. + * + * @param obj The instruction. + */ void visitF2D(F2D obj); + /** + * Visits an F2I instruction. + * + * @param obj The instruction. + */ void visitF2I(F2I obj); + /** + * Visits an F2L instruction. + * + * @param obj The instruction. + */ void visitF2L(F2L obj); + /** + * Visits an FADD instruction. + * + * @param obj The instruction. + */ void visitFADD(FADD obj); + /** + * Visits an FALOAD instruction. + * + * @param obj The instruction. + */ void visitFALOAD(FALOAD obj); + /** + * Visits an FASTORE instruction. + * + * @param obj The instruction. + */ void visitFASTORE(FASTORE obj); + /** + * Visits an FCMPG instruction. + * + * @param obj The instruction. + */ void visitFCMPG(FCMPG obj); + /** + * Visits an FCMPL instruction. + * + * @param obj The instruction. + */ void visitFCMPL(FCMPL obj); + /** + * Visits an FCONST instruction. + * + * @param obj The instruction. + */ void visitFCONST(FCONST obj); + /** + * Visits an FDIV instruction. + * + * @param obj The instruction. + */ void visitFDIV(FDIV obj); + /** + * Visits a FieldInstruction. + * + * @param obj The instruction. + */ void visitFieldInstruction(FieldInstruction obj); + /** + * Visits a FieldOrMethod. + * + * @param obj The instruction. + */ void visitFieldOrMethod(FieldOrMethod obj); + /** + * Visits an FLOAD instruction. + * + * @param obj The instruction. + */ void visitFLOAD(FLOAD obj); + /** + * Visits an FMUL instruction. + * + * @param obj The instruction. + */ void visitFMUL(FMUL obj); + /** + * Visits an FNEG instruction. + * + * @param obj The instruction. + */ void visitFNEG(FNEG obj); + /** + * Visits an FREM instruction. + * + * @param obj The instruction. + */ void visitFREM(FREM obj); + /** + * Visits an FRETURN instruction. + * + * @param obj The instruction. + */ void visitFRETURN(FRETURN obj); + /** + * Visits an FSTORE instruction. + * + * @param obj The instruction. + */ void visitFSTORE(FSTORE obj); + /** + * Visits an FSUB instruction. + * + * @param obj The instruction. + */ void visitFSUB(FSUB obj); + /** + * Visits a GETFIELD instruction. + * + * @param obj The instruction. + */ void visitGETFIELD(GETFIELD obj); + /** + * Visits a GETSTATIC instruction. + * + * @param obj The instruction. + */ void visitGETSTATIC(GETSTATIC obj); + /** + * Visits a GOTO instruction. + * + * @param obj The instruction. + */ void visitGOTO(GOTO obj); + /** + * Visits a GOTO_W instruction. + * + * @param obj The instruction. + */ void visitGOTO_W(GOTO_W obj); + /** + * Visits a GotoInstruction. + * + * @param obj The instruction. + */ void visitGotoInstruction(GotoInstruction obj); + /** + * Visits an I2B instruction. + * + * @param obj The instruction. + */ void visitI2B(I2B obj); + /** + * Visits an I2C instruction. + * + * @param obj The instruction. + */ void visitI2C(I2C obj); + /** + * Visits an I2D instruction. + * + * @param obj The instruction. + */ void visitI2D(I2D obj); + /** + * Visits an I2F instruction. + * + * @param obj The instruction. + */ void visitI2F(I2F obj); + /** + * Visits an I2L instruction. + * + * @param obj The instruction. + */ void visitI2L(I2L obj); + /** + * Visits an I2S instruction. + * + * @param obj The instruction. + */ void visitI2S(I2S obj); + /** + * Visits an IADD instruction. + * + * @param obj The instruction. + */ void visitIADD(IADD obj); + /** + * Visits an IALOAD instruction. + * + * @param obj The instruction. + */ void visitIALOAD(IALOAD obj); + /** + * Visits an IAND instruction. + * + * @param obj The instruction. + */ void visitIAND(IAND obj); + /** + * Visits an IASTORE instruction. + * + * @param obj The instruction. + */ void visitIASTORE(IASTORE obj); + /** + * Visits an ICONST instruction. + * + * @param obj The instruction. + */ void visitICONST(ICONST obj); + /** + * Visits an IDIV instruction. + * + * @param obj The instruction. + */ void visitIDIV(IDIV obj); + /** + * Visits an IF_ACMPEQ instruction. + * + * @param obj The instruction. + */ void visitIF_ACMPEQ(IF_ACMPEQ obj); + /** + * Visits an IF_ACMPNE instruction. + * + * @param obj The instruction. + */ void visitIF_ACMPNE(IF_ACMPNE obj); + /** + * Visits an IF_ICMPEQ instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPEQ(IF_ICMPEQ obj); + /** + * Visits an IF_ICMPGE instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPGE(IF_ICMPGE obj); + /** + * Visits an IF_ICMPGT instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPGT(IF_ICMPGT obj); + /** + * Visits an IF_ICMPLE instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPLE(IF_ICMPLE obj); + /** + * Visits an IF_ICMPLT instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPLT(IF_ICMPLT obj); + /** + * Visits an IF_ICMPNE instruction. + * + * @param obj The instruction. + */ void visitIF_ICMPNE(IF_ICMPNE obj); + /** + * Visits an IFEQ instruction. + * + * @param obj The instruction. + */ void visitIFEQ(IFEQ obj); + /** + * Visits an IFGE instruction. + * + * @param obj The instruction. + */ void visitIFGE(IFGE obj); + /** + * Visits an IFGT instruction. + * + * @param obj The instruction. + */ void visitIFGT(IFGT obj); + /** + * Visits an IfInstruction. + * + * @param obj The instruction. + */ void visitIfInstruction(IfInstruction obj); + /** + * Visits an IFLE instruction. + * + * @param obj The instruction. + */ void visitIFLE(IFLE obj); + /** + * Visits an IFLT instruction. + * + * @param obj The instruction. + */ void visitIFLT(IFLT obj); + /** + * Visits an IFNE instruction. + * + * @param obj The instruction. + */ void visitIFNE(IFNE obj); + /** + * Visits an IFNONNULL instruction. + * + * @param obj The instruction. + */ void visitIFNONNULL(IFNONNULL obj); + /** + * Visits an IFNULL instruction. + * + * @param obj The instruction. + */ void visitIFNULL(IFNULL obj); + /** + * Visits an IINC instruction. + * + * @param obj The instruction. + */ void visitIINC(IINC obj); + /** + * Visits an ILOAD instruction. + * + * @param obj The instruction. + */ void visitILOAD(ILOAD obj); + /** + * Visits an IMPDEP1 instruction. + * + * @param obj The instruction. + */ void visitIMPDEP1(IMPDEP1 obj); + /** + * Visits an IMPDEP2 instruction. + * + * @param obj The instruction. + */ void visitIMPDEP2(IMPDEP2 obj); + /** + * Visits an IMUL instruction. + * + * @param obj The instruction. + */ void visitIMUL(IMUL obj); + /** + * Visits an INEG instruction. + * + * @param obj The instruction. + */ void visitINEG(INEG obj); + /** + * Visits an INSTANCEOF instruction. + * + * @param obj The instruction. + */ void visitINSTANCEOF(INSTANCEOF obj); /** + * Visits an INVOKEDYNAMIC instruction. + * + * @param obj The instruction. * @since 6.0 */ void visitINVOKEDYNAMIC(INVOKEDYNAMIC obj); + /** + * Visits an InvokeInstruction. + * + * @param obj The instruction. + */ void visitInvokeInstruction(InvokeInstruction obj); + /** + * Visits an INVOKEINTERFACE instruction. + * + * @param obj The instruction. + */ void visitINVOKEINTERFACE(INVOKEINTERFACE obj); + /** + * Visits an INVOKESPECIAL instruction. + * + * @param obj The instruction. + */ void visitINVOKESPECIAL(INVOKESPECIAL obj); + /** + * Visits an INVOKESTATIC instruction. + * + * @param obj The instruction. + */ void visitINVOKESTATIC(INVOKESTATIC obj); + /** + * Visits an INVOKEVIRTUAL instruction. + * + * @param obj The instruction. + */ void visitINVOKEVIRTUAL(INVOKEVIRTUAL obj); + /** + * Visits an IOR instruction. + * + * @param obj The instruction. + */ void visitIOR(IOR obj); + /** + * Visits an IREM instruction. + * + * @param obj The instruction. + */ void visitIREM(IREM obj); + /** + * Visits an IRETURN instruction. + * + * @param obj The instruction. + */ void visitIRETURN(IRETURN obj); + /** + * Visits an ISHL instruction. + * + * @param obj The instruction. + */ void visitISHL(ISHL obj); + /** + * Visits an ISHR instruction. + * + * @param obj The instruction. + */ void visitISHR(ISHR obj); + /** + * Visits an ISTORE instruction. + * + * @param obj The instruction. + */ void visitISTORE(ISTORE obj); + /** + * Visits an ISUB instruction. + * + * @param obj The instruction. + */ void visitISUB(ISUB obj); + /** + * Visits an IUSHR instruction. + * + * @param obj The instruction. + */ void visitIUSHR(IUSHR obj); + /** + * Visits an IXOR instruction. + * + * @param obj The instruction. + */ void visitIXOR(IXOR obj); + /** + * Visits a JSR instruction. + * + * @param obj The instruction. + */ void visitJSR(JSR obj); + /** + * Visits a JSR_W instruction. + * + * @param obj The instruction. + */ void visitJSR_W(JSR_W obj); + /** + * Visits a JsrInstruction. + * + * @param obj The instruction. + */ void visitJsrInstruction(JsrInstruction obj); + /** + * Visits an L2D instruction. + * + * @param obj The instruction. + */ void visitL2D(L2D obj); + /** + * Visits an L2F instruction. + * + * @param obj The instruction. + */ void visitL2F(L2F obj); + /** + * Visits an L2I instruction. + * + * @param obj The instruction. + */ void visitL2I(L2I obj); + /** + * Visits an LADD instruction. + * + * @param obj The instruction. + */ void visitLADD(LADD obj); + /** + * Visits an LALOAD instruction. + * + * @param obj The instruction. + */ void visitLALOAD(LALOAD obj); + /** + * Visits an LAND instruction. + * + * @param obj The instruction. + */ void visitLAND(LAND obj); + /** + * Visits an LASTORE instruction. + * + * @param obj The instruction. + */ void visitLASTORE(LASTORE obj); + /** + * Visits an LCMP instruction. + * + * @param obj The instruction. + */ void visitLCMP(LCMP obj); + /** + * Visits an LCONST instruction. + * + * @param obj The instruction. + */ void visitLCONST(LCONST obj); + /** + * Visits an LDC instruction. + * + * @param obj The instruction. + */ void visitLDC(LDC obj); + /** + * Visits an LDC2_W instruction. + * + * @param obj The instruction. + */ void visitLDC2_W(LDC2_W obj); + /** + * Visits an LDIV instruction. + * + * @param obj The instruction. + */ void visitLDIV(LDIV obj); + /** + * Visits an LLOAD instruction. + * + * @param obj The instruction. + */ void visitLLOAD(LLOAD obj); + /** + * Visits an LMUL instruction. + * + * @param obj The instruction. + */ void visitLMUL(LMUL obj); + /** + * Visits an LNEG instruction. + * + * @param obj The instruction. + */ void visitLNEG(LNEG obj); + /** + * Visits a LoadClass. + * + * @param obj The load class. + */ void visitLoadClass(LoadClass obj); + /** + * Visits a LoadInstruction. + * + * @param obj The instruction. + */ void visitLoadInstruction(LoadInstruction obj); + /** + * Visits a LocalVariableInstruction. + * + * @param obj The instruction. + */ void visitLocalVariableInstruction(LocalVariableInstruction obj); + /** + * Visits a LOOKUPSWITCH instruction. + * + * @param obj The instruction. + */ void visitLOOKUPSWITCH(LOOKUPSWITCH obj); + /** + * Visits an LOR instruction. + * + * @param obj The instruction. + */ void visitLOR(LOR obj); + /** + * Visits an LREM instruction. + * + * @param obj The instruction. + */ void visitLREM(LREM obj); + /** + * Visits an LRETURN instruction. + * + * @param obj The instruction. + */ void visitLRETURN(LRETURN obj); + /** + * Visits an LSHL instruction. + * + * @param obj The instruction. + */ void visitLSHL(LSHL obj); + /** + * Visits an LSHR instruction. + * + * @param obj The instruction. + */ void visitLSHR(LSHR obj); + /** + * Visits an LSTORE instruction. + * + * @param obj The instruction. + */ void visitLSTORE(LSTORE obj); + /** + * Visits an LSUB instruction. + * + * @param obj The instruction. + */ void visitLSUB(LSUB obj); + /** + * Visits an LUSHR instruction. + * + * @param obj The instruction. + */ void visitLUSHR(LUSHR obj); + /** + * Visits an LXOR instruction. + * + * @param obj The instruction. + */ void visitLXOR(LXOR obj); + /** + * Visits a MONITORENTER instruction. + * + * @param obj The instruction. + */ void visitMONITORENTER(MONITORENTER obj); + /** + * Visits a MONITOREXIT instruction. + * + * @param obj The instruction. + */ void visitMONITOREXIT(MONITOREXIT obj); + /** + * Visits a MULTIANEWARRAY instruction. + * + * @param obj The instruction. + */ void visitMULTIANEWARRAY(MULTIANEWARRAY obj); + /** + * Visits a NEW instruction. + * + * @param obj The instruction. + */ void visitNEW(NEW obj); + /** + * Visits a NEWARRAY instruction. + * + * @param obj The instruction. + */ void visitNEWARRAY(NEWARRAY obj); + /** + * Visits a NOP instruction. + * + * @param obj The instruction. + */ void visitNOP(NOP obj); + /** + * Visits a POP instruction. + * + * @param obj The instruction. + */ void visitPOP(POP obj); + /** + * Visits a POP2 instruction. + * + * @param obj The instruction. + */ void visitPOP2(POP2 obj); + /** + * Visits a PopInstruction. + * + * @param obj The instruction. + */ void visitPopInstruction(PopInstruction obj); + /** + * Visits a PushInstruction. + * + * @param obj The instruction. + */ void visitPushInstruction(PushInstruction obj); + /** + * Visits a PUTFIELD instruction. + * + * @param obj The instruction. + */ void visitPUTFIELD(PUTFIELD obj); + /** + * Visits a PUTSTATIC instruction. + * + * @param obj The instruction. + */ void visitPUTSTATIC(PUTSTATIC obj); + /** + * Visits a RET instruction. + * + * @param obj The instruction. + */ void visitRET(RET obj); + /** + * Visits a RETURN instruction. + * + * @param obj The instruction. + */ void visitRETURN(RETURN obj); + /** + * Visits a ReturnInstruction. + * + * @param obj The instruction. + */ void visitReturnInstruction(ReturnInstruction obj); + /** + * Visits a SALOAD instruction. + * + * @param obj The instruction. + */ void visitSALOAD(SALOAD obj); + /** + * Visits a SASTORE instruction. + * + * @param obj The instruction. + */ void visitSASTORE(SASTORE obj); + /** + * Visits a Select instruction. + * + * @param obj The instruction. + */ void visitSelect(Select obj); + /** + * Visits a SIPUSH instruction. + * + * @param obj The instruction. + */ void visitSIPUSH(SIPUSH obj); + /** + * Visits a StackConsumer. + * + * @param obj The instruction. + */ void visitStackConsumer(StackConsumer obj); + /** + * Visits a StackInstruction. + * + * @param obj The instruction. + */ void visitStackInstruction(StackInstruction obj); + /** + * Visits a StackProducer. + * + * @param obj The instruction. + */ void visitStackProducer(StackProducer obj); + /** + * Visits a StoreInstruction. + * + * @param obj The instruction. + */ void visitStoreInstruction(StoreInstruction obj); + /** + * Visits a SWAP instruction. + * + * @param obj The instruction. + */ void visitSWAP(SWAP obj); + /** + * Visits a TABLESWITCH instruction. + * + * @param obj The instruction. + */ void visitTABLESWITCH(TABLESWITCH obj); + /** + * Visits a TypedInstruction. + * + * @param obj The instruction. + */ void visitTypedInstruction(TypedInstruction obj); + /** + * Visits an UnconditionalBranch. + * + * @param obj The instruction. + */ void visitUnconditionalBranch(UnconditionalBranch obj); + /** + * Visits a VariableLengthInstruction. + * + * @param obj The instruction. + */ void visitVariableLengthInstruction(VariableLengthInstruction obj); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Args.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Args.java index a61d9d35d2aa..dbde429fade1 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Args.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Args.java @@ -36,7 +36,7 @@ public class Args { * * @param value The value to test. * @param required The required value. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int require(final int value, final int required, final String message) { @@ -50,7 +50,7 @@ public static int require(final int value, final int required, final String mess * Requires a 0 value. * * @param value The value to test. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int require0(final int value, final String message) { @@ -61,7 +61,7 @@ public static int require0(final int value, final String message) { * Requires a u1 value. * * @param value The value to test. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int requireU1(final int value, final String message) { @@ -77,7 +77,7 @@ public static int requireU1(final int value, final String message) { * @param value The value to test. * @param min The minimum required u2 value. * @param max The maximum required u2 value. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int requireU2(final int value, final int min, final int max, final String message) { @@ -88,7 +88,7 @@ public static int requireU2(final int value, final int min, final int max, final throw new IllegalArgumentException(String.format("%s programming error: min %,d < 0", message, min)); } if (value < min || value > max) { - throw new ClassFormatException(String.format("%s [Value out of range (%,d - %,d) for type u2: %,d]", message, min, Const.MAX_SHORT, value)); + throw new ClassFormatException(String.format("%s [Value out of range (%,d - %,d) for type u2: %,d]", message, min, max, value)); } return value; } @@ -98,7 +98,7 @@ public static int requireU2(final int value, final int min, final int max, final * * @param value The value to test. * @param min The minimum required value. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int requireU2(final int value, final int min, final String message) { @@ -109,7 +109,7 @@ public static int requireU2(final int value, final int min, final String message * Requires a u2 value. * * @param value The value to test. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int requireU2(final int value, final String message) { @@ -117,32 +117,56 @@ public static int requireU2(final int value, final String message) { } /** - * Requires a u4 value of at least {@code min}. + * Requires a u4 value of at least {@code min} and not above {@code max}. * * @param value The value to test. - * @param min The minimum required value. - * @param message The message prefix + * @param min The minimum required u4 value. + * @param max The maximum required u4 value. + * @param message The message prefix. * @return The value to test. + * @throws IllegalArgumentException Thrown if {@code min < 0} or {@code max > Integer.MAX_VALUE}. + * @throws ClassFormatException Thrown if {@code value < min} or {@code value > max}. + * @since 6.12.0 */ - public static int requireU4(final int value, final int min, final String message) { + public static int requireU4(final int value, final int min, final int max, final String message) { if (min < 0) { throw new IllegalArgumentException(String.format("%s programming error: min %,d < 0", message, min)); } - if (value < min) { + if (value < min || value > max) { throw new ClassFormatException( - String.format("%s [Value out of range (%,d - %,d) for type u2: %,d]", message, min, Integer.MAX_VALUE, value & 0xFFFFFFFFL)); + String.format("%s [Value out of range (%,d - %,d) for type u4: %,d]", message, min, Integer.MAX_VALUE, value & 0xFFFFFFFFL)); } return value; } + /** + * Requires a u4 value of at least {@code min}. + * + * @param value The value to test. + * @param min The minimum required value. + * @param message The message prefix. + * @return The value to test. + */ + public static int requireU4(final int value, final int min, final String message) { + // Should really be 2^32-1, instead 2^21-1. + return requireU4(value, min, Integer.MAX_VALUE, message); + } + /** * Requires a u4 value. * * @param value The value to test. - * @param message The message prefix + * @param message The message prefix. * @return The value to test. */ public static int requireU4(final int value, final String message) { return requireU4(value, 0, message); } + + /** + * Private constructor to prevent instantiation of this utility class. + */ + public Args() { + // Utility class + } } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/AttributeHTML.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/AttributeHTML.java index 4a84901fc564..5e003d9b5f7e 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/AttributeHTML.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/AttributeHTML.java @@ -91,7 +91,7 @@ void writeAttribute(final Attribute attribute, final String anchor, final int me } else { printWriter.print(""); } - printWriter.println("

" + attrCount + " " + Const.getAttributeName(tag) + "

"); + printWriter.println("

" + attrCount + " " + Const.getAttributeName(tag) + "

"); /* * Handle different attributes */ @@ -162,9 +162,9 @@ void writeAttribute(final Attribute attribute, final String anchor, final int me signature = Utility.signatureToString(signature, false); final int start = var.getStartPC(); final int end = start + var.getLength(); - printWriter.println("
  • " + Class2HTML.referenceType(signature) + " " + var.getName() + " in slot %" + var.getIndex() - + "
    Valid from lines " + "" + start - + " to " + "" + end + "
  • "); + printWriter.println("
  • " + Class2HTML.referenceType(signature) + " " + Class2HTML.toHTML(var.getName()) + " in slot %" + var.getIndex() + + "
    Valid from lines " + start + + " to " + end + "
  • "); }); printWriter.print("\n"); break; @@ -176,7 +176,7 @@ void writeAttribute(final Attribute attribute, final String anchor, final int me final String access; index = clazz.getInnerNameIndex(); if (index > 0) { - name = constantPool.getConstantUtf8(index).getBytes(); + name = Class2HTML.toHTML(constantPool.getConstantUtf8(index).getBytes()); } else { name = "<anonymous>"; } @@ -187,7 +187,7 @@ void writeAttribute(final Attribute attribute, final String anchor, final int me printWriter.print("\n"); break; default: // Such as Unknown attribute or Deprecated - printWriter.print("

    " + attribute); + printWriter.print("

    " + Class2HTML.toHTML(String.valueOf(attribute))); } printWriter.println(""); printWriter.flush(); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELComparator.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELComparator.java index fb32dc35e0b0..cf2d76144a1b 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELComparator.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELComparator.java @@ -32,17 +32,17 @@ public interface BCELComparator { /** * Compares two objects and return what a.equals(b) should return. * - * @param a an object. - * @param b an object to be compared with {@code a} for equality. + * @param a An object. + * @param b An object to be compared with {@code a} for equality. * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. */ boolean equals(T a, T b); /** - * Gets the hash code for o.hashCode() + * Gets the hash code for o.hashCode(). * - * @param o - * @return hash code for o.hashCode() + * @param o The object. + * @return hash code for o.hashCode(). */ int hashCode(T o); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELFactory.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELFactory.java index 93f22e7d0add..ced935ea39e5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELFactory.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import com.sun.org.apache.bcel.internal.Const; @@ -58,12 +57,13 @@ import com.sun.org.apache.bcel.internal.generic.ReturnInstruction; import com.sun.org.apache.bcel.internal.generic.Select; import com.sun.org.apache.bcel.internal.generic.Type; +import jdk.xml.internal.Utils; /** * Factory creates il.append() statements, and sets instruction targets. A helper class for BCELifier. * * @see BCELifier - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ final class BCELFactory extends EmptyVisitor { @@ -115,7 +115,7 @@ private void createConstant(final Object value) { embed += "L"; } else if (value instanceof ObjectType) { final ObjectType ot = (ObjectType) value; - embed = "new ObjectType(\"" + ot.getClassName() + "\")"; + embed = "new ObjectType(\"" + Utility.convertString(ot.getClassName()) + "\")"; } else if (value instanceof ArrayType) { final ArrayType at = (ArrayType) value; embed = "new ArrayType(" + BCELifier.printType(at.getBasicType()) + ", " + at.getDimensions() + ")"; @@ -170,8 +170,8 @@ private void updateExceptionHandlers() { final CodeExceptionGen[] handlers = methodGen.getExceptionHandlers(); for (final CodeExceptionGen h : handlers) { final String type = h.getCatchType() == null ? "null" : BCELifier.printType(h.getCatchType()); - printWriter.println(" method.addExceptionHandler(" + "ih_" + h.getStartPC().getPosition() + ", " + "ih_" + h.getEndPC().getPosition() + ", " - + "ih_" + h.getHandlerPC().getPosition() + ", " + type + ");"); + printWriter.println(" method.addExceptionHandler(ih_" + h.getStartPC().getPosition() + ", ih_" + h.getEndPC().getPosition() + ", ih_" + + h.getHandlerPC().getPosition() + ", " + type + ");"); } } @@ -188,16 +188,16 @@ public void visitAllocationInstruction(final AllocationInstruction i) { int dim = 1; switch (opcode) { case Const.NEW: - printWriter.println("il.append(_factory.createNew(\"" + ((ObjectType) type).getClassName() + "\"));"); + printWriter.println("il.append(_factory.createNew(\"" + Utility.convertString(((ObjectType) type).getClassName()) + "\"));"); break; case Const.MULTIANEWARRAY: dim = ((MULTIANEWARRAY) i).getDimensions(); - //$FALL-THROUGH$ + // falls-through case Const.NEWARRAY: if (type instanceof ArrayType) { type = ((ArrayType) type).getBasicType(); } - //$FALL-THROUGH$ + // falls-through case Const.ANEWARRAY: printWriter.println("il.append(_factory.createNewArray(" + BCELifier.printType(type) + ", (short) " + dim + "));"); break; @@ -231,7 +231,7 @@ public void visitBranchInstruction(final BranchInstruction bi) { } } args.append(" }"); - printWriter.print("Select " + name + " = new " + bi.getName().toUpperCase(Locale.ENGLISH) + "(" + args + ", new InstructionHandle[] { "); + printWriter.print("Select " + name + " = new " + Utils.toUpperCase(bi.getName()) + "(" + args + ", new InstructionHandle[] { "); for (int i = 0; i < matchs.length; i++) { printWriter.print("null"); if (i < matchs.length - 1) { @@ -241,7 +241,7 @@ public void visitBranchInstruction(final BranchInstruction bi) { printWriter.println(" }, null);"); } else { final int tPos = bh.getTarget().getPosition(); - String target; + final String target; if (pos > tPos) { target = "ih_" + tPos; } else { @@ -249,7 +249,7 @@ public void visitBranchInstruction(final BranchInstruction bi) { target = "null"; } printWriter.println(" BranchInstruction " + name + " = _factory.createBranchInstruction(" + CONSTANT_PREFIX - + bi.getName().toUpperCase(Locale.ENGLISH) + ", " + target + ");"); + + Utils.toUpperCase(bi.getName()) + ", " + target + ");"); } if (bh.hasTargeters()) { printWriter.println(" ih_" + pos + " = il.append(" + name + ");"); @@ -275,8 +275,9 @@ public void visitFieldInstruction(final FieldInstruction i) { final String className = i.getReferenceType(constantPoolGen).getClassName(); final String fieldName = i.getFieldName(constantPoolGen); final Type type = i.getFieldType(constantPoolGen); - printWriter.println("il.append(_factory.createFieldAccess(\"" + className + "\", \"" + fieldName + "\", " + BCELifier.printType(type) + ", " - + CONSTANT_PREFIX + Const.getOpcodeName(opcode).toUpperCase(Locale.ENGLISH) + "));"); + printWriter.println("il.append(_factory.createFieldAccess(\"" + Utility.convertString(className) + "\", \"" + Utility.convertString(fieldName) + "\", " + + BCELifier.printType(type) + ", " + + CONSTANT_PREFIX + Utils.toUpperCase(Const.getOpcodeName(opcode)) + "));"); } @Override @@ -288,7 +289,7 @@ public void visitINSTANCEOF(final INSTANCEOF i) { private boolean visitInstruction(final Instruction i) { final short opcode = i.getOpcode(); if (InstructionConst.getInstruction(opcode) != null && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below - printWriter.println("il.append(InstructionConst." + i.getName().toUpperCase(Locale.ENGLISH) + ");"); + printWriter.println("il.append(InstructionConst." + Utils.toUpperCase(i.getName()) + ");"); return true; } return false; @@ -301,8 +302,9 @@ public void visitInvokeInstruction(final InvokeInstruction i) { final String methodName = i.getMethodName(constantPoolGen); final Type type = i.getReturnType(constantPoolGen); final Type[] argTypes = i.getArgumentTypes(constantPoolGen); - printWriter.println("il.append(_factory.createInvoke(\"" + className + "\", \"" + methodName + "\", " + BCELifier.printType(type) + ", " - + BCELifier.printArgumentTypes(argTypes) + ", " + CONSTANT_PREFIX + Const.getOpcodeName(opcode).toUpperCase(Locale.ENGLISH) + "));"); + printWriter.println("il.append(_factory.createInvoke(\"" + Utility.convertString(className) + "\", \"" + Utility.convertString(methodName) + "\", " + + BCELifier.printType(type) + ", " + BCELifier.printArgumentTypes(argTypes) + ", " + CONSTANT_PREFIX + + Utils.toUpperCase(Const.getOpcodeName(opcode)) + "));"); } @Override diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELifier.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELifier.java index 0eb9bfb4ee1a..d8a8e9280030 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELifier.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/BCELifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,7 +25,6 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; -import java.util.Locale; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.Repository; @@ -44,13 +43,14 @@ import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen; import com.sun.org.apache.bcel.internal.generic.MethodGen; import com.sun.org.apache.bcel.internal.generic.Type; +import jdk.xml.internal.Utils; /** * This class takes a given JavaClass object and converts it to a Java program that creates that very class using BCEL. * This gives new users of BCEL a useful example showing how things are done with BCEL. It does not cover all features * of BCEL, but tries to mimic hand-written code as close as possible. * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class BCELifier extends com.sun.org.apache.bcel.internal.classfile.EmptyVisitor { @@ -58,7 +58,15 @@ public class BCELifier extends com.sun.org.apache.bcel.internal.classfile.EmptyV * Enum corresponding to flag source. */ public enum FLAGS { - UNKNOWN, CLASS, METHOD, + + /** Unknown flag source. */ + UNKNOWN, + + /** Class flag source. */ + CLASS, + + /** Method flag source. */ + METHOD, } // The base package name for imports; assumes Const is at the top level @@ -66,6 +74,48 @@ public enum FLAGS { private static final String BASE_PACKAGE = Const.class.getPackage().getName(); private static final String CONSTANT_PREFIX = Const.class.getSimpleName() + "."; + /** + * Checks that a name from the parsed class file is a dotted sequence of valid Java identifiers before it is + * emitted in identifier position of the generated source. The class file format allows characters in names (for + * example braces, parentheses or newlines) that the Java language does not, so an unchecked name from a crafted + * class file could inject arbitrary code into the generated program. + * + * @param name the class or package name to check. + * @return {@code name} if it is safe to emit as a Java identifier. + * @throws IllegalArgumentException Thrown if the name is not a dotted sequence of valid Java identifiers. + */ + private static String checkJavaName(final String name) { + boolean expectStart = true; + for (int i = 0; i < name.length(); i++) { + final char ch = name.charAt(i); + if (expectStart) { + if (!Character.isJavaIdentifierStart(ch)) { + throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name)); + } + expectStart = false; + } else if (ch == '.') { + expectStart = true; + } else if (!Character.isJavaIdentifierPart(ch)) { + throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name)); + } + } + if (expectStart) { + throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name)); + } + return name; + } + + private static String[] escape(final String[] names) { + if (names == null) { + return null; + } + final String[] escaped = new String[names.length]; + for (int i = 0; i < names.length; i++) { + escaped[i] = names[i] == null ? null : Utility.convertString(names[i]); + } + return escaped; + } + // Needs to be accessible from unit test code static JavaClass getJavaClass(final String name) throws ClassNotFoundException, IOException { JavaClass javaClass; @@ -76,9 +126,12 @@ static JavaClass getJavaClass(final String name) throws ClassNotFoundException, } /** - * Default main method + * Default main method. + * + * @param argv command line arguments. + * @throws Exception Thrown if an error occurs. */ - public static void main(final String[] argv) throws Exception { + public static void _main(final String[] argv) throws Exception { if (argv.length != 1) { System.out.println("Usage: BCELifier className"); System.out.println("\tThe class must exist on the classpath"); @@ -109,9 +162,9 @@ static String printFlags(final int flags) { /** * Return a string with the flag settings * - * @param flags the flags field to interpret - * @param location the item type - * @return the formatted string + * @param flags The flags field to interpret. + * @param location The item type. + * @return The formatted string. * @since 6.0 made public */ public static String printFlags(final int flags, final FLAGS location) { @@ -128,7 +181,7 @@ public static String printFlags(final int flags, final FLAGS location) { } else if (pow == Const.ACC_TRANSIENT && location == FLAGS.METHOD) { buf.append(CONSTANT_PREFIX).append("ACC_VARARGS | "); } else if (i < Const.ACCESS_NAMES_LENGTH) { - buf.append(CONSTANT_PREFIX).append("ACC_").append(Const.getAccessName(i).toUpperCase(Locale.ENGLISH)).append(" | "); + buf.append(CONSTANT_PREFIX).append("ACC_").append(Utils.toUpperCase(Const.getAccessName(i))).append(" | "); } else { buf.append(String.format(CONSTANT_PREFIX + "ACC_BIT %x | ", pow)); } @@ -143,7 +196,7 @@ static String printType(final String signature) { final Type type = Type.getType(signature); final byte t = type.getType(); if (t <= Const.T_VOID) { - return "Type." + Const.getTypeName(t).toUpperCase(Locale.ENGLISH); + return "Type." + Utils.toUpperCase(Const.getTypeName(t)); } if (type.toString().equals("java.lang.String")) { return "Type.STRING"; @@ -199,10 +252,10 @@ private void printCreate() { } private void printMain() { - final String className = clazz.getClassName(); + final String className = checkJavaName(clazz.getClassName()); printWriter.println(" public static void main(String[] args) throws Exception {"); printWriter.println(" " + className + "Creator creator = new " + className + "Creator();"); - printWriter.println(" creator.create(new FileOutputStream(\"" + className + ".class\"));"); + printWriter.println(" creator.create(new FileOutputStream(\"" + Utility.convertString(className) + ".class\"));"); printWriter.println(" }"); } @@ -217,8 +270,8 @@ public void start() { @Override public void visitField(final Field field) { printWriter.println(); - printWriter.println( - " field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", " + printType(field.getSignature()) + ", \"" + field.getName() + "\", _cp);"); + printWriter.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", " + printType(field.getSignature()) + ", \"" + + Utility.convertString(field.getName()) + "\", _cp);"); final ConstantValue cv = field.getConstantValue(); if (cv != null) { printWriter.print(" field.setInitValue("); @@ -248,11 +301,11 @@ public void visitField(final Field field) { @Override public void visitJavaClass(final JavaClass clazz) { - String className = clazz.getClassName(); + String className = checkJavaName(clazz.getClassName()); final String superName = clazz.getSuperclassName(); final String packageName = clazz.getPackageName(); - final String inter = Utility.printArray(clazz.getInterfaceNames(), false, true); - if (packageName != null && !packageName.trim().isEmpty()) { + final String inter = Utility.printArray(escape(clazz.getInterfaceNames()), false, true); + if (Utils.isNotEmpty(packageName)) { className = className.substring(packageName.length() + 1); printWriter.println("package " + packageName + ";"); printWriter.println(); @@ -268,8 +321,9 @@ public void visitJavaClass(final JavaClass clazz) { printWriter.println(" private ClassGen _cg;"); printWriter.println(); printWriter.println(" public " + className + "Creator() {"); - printWriter.println(" _cg = new ClassGen(\"" + (packageName.isEmpty() ? className : packageName + "." + className) + "\", \"" + superName - + "\", " + "\"" + clazz.getSourceFileName() + "\", " + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " });"); + printWriter.println(" _cg = new ClassGen(\"" + Utility.convertString(packageName.isEmpty() ? className : packageName + "." + className) + "\", \"" + + Utility.convertString(superName) + "\", \"" + Utility.convertString(clazz.getSourceFileName()) + "\", " + + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " });"); printWriter.println(" _cg.setMajor(" + clazz.getMajor() + ");"); printWriter.println(" _cg.setMinor(" + clazz.getMinor() + ");"); printWriter.println(); @@ -304,14 +358,14 @@ public void visitMethod(final Method method) { final MethodGen mg = new MethodGen(method, clazz.getClassName(), constantPoolGen); printWriter.println(" InstructionList il = new InstructionList();"); printWriter.println(" MethodGen method = new MethodGen(" + printFlags(method.getAccessFlags(), FLAGS.METHOD) + ", " + printType(mg.getReturnType()) - + ", " + printArgumentTypes(mg.getArgumentTypes()) + ", " + "new String[] { " + Utility.printArray(mg.getArgumentNames(), false, true) + " }, \"" - + method.getName() + "\", \"" + clazz.getClassName() + "\", il, _cp);"); + + ", " + printArgumentTypes(mg.getArgumentTypes()) + ", new String[] { " + Utility.printArray(escape(mg.getArgumentNames()), false, true) + " }, \"" + + Utility.convertString(method.getName()) + "\", \"" + Utility.convertString(clazz.getClassName()) + "\", il, _cp);"); final ExceptionTable exceptionTable = method.getExceptionTable(); if (exceptionTable != null) { final String[] exceptionNames = exceptionTable.getExceptionNames(); for (final String exceptionName : exceptionNames) { printWriter.print(" method.addException(\""); - printWriter.print(exceptionName); + printWriter.print(Utility.convertString(exceptionName)); printWriter.println("\");"); } } @@ -336,7 +390,7 @@ public void visitStackMap(final StackMap stackMap) { super.visitStackMap(stackMap); printWriter.print(" method.addCodeAttribute("); printWriter.print("new StackMap(_cp.addUtf8(\""); - printWriter.print(stackMap.getName()); + printWriter.print(Utility.convertString(stackMap.getName())); printWriter.print("\"), "); printWriter.print(stackMap.getLength()); printWriter.print(", "); @@ -370,7 +424,8 @@ public void visitStackMapEntry(final StackMapEntry stackMapEntry) { /** * Visits a {@link StackMapType} object. - * @param stackMapType object to visit + * + * @param stackMapType object to visit. * @since 6.7.1 */ @Override @@ -381,7 +436,7 @@ public void visitStackMapType(final StackMapType stackMapType) { printWriter.print(", "); if (stackMapType.hasIndex()) { printWriter.print("_cp.addClass(\""); - printWriter.print(stackMapType.getClassName()); + printWriter.print(Utility.convertString(stackMapType.getClassName())); printWriter.print("\")"); } else { printWriter.print("-1"); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ByteSequence.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ByteSequence.java index 65dfd3f3eafe..820e612f9124 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ByteSequence.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ByteSequence.java @@ -50,15 +50,28 @@ void unreadByte() { private final ByteArrayStream byteStream; + /** + * Constructs a ByteSequence. + * + * @param bytes The byte array. + */ public ByteSequence(final byte[] bytes) { super(new ByteArrayStream(bytes)); byteStream = (ByteArrayStream) in; } + /** + * Gets the current index. + * + * @return The current index. + */ public int getIndex() { return byteStream.getPosition(); } + /** + * Unreads the last byte. + */ void unreadByte() { byteStream.unreadByte(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Class2HTML.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Class2HTML.java index 10d31974d47a..70d1cc1354ef 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Class2HTML.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Class2HTML.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -50,10 +50,10 @@ *

  • "package"."class"_methods.html contains references to all methods and fields of the class * * - * All subfiles reference each other appropriately, e.g. clicking on a method in the Method's frame will jump to the + * All subfiles reference each other appropriately, for example clicking on a method in the Method's frame will jump to the * appropriate method in the Code frame. * - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class Class2HTML { @@ -73,7 +73,36 @@ public class Class2HTML { basicTypes.add("float"); } - public static void main(final String[] argv) throws IOException { + /** + * The class name comes from the attacker-controlled this_class constant of the parsed class file and is + * concatenated into the five output file paths ("dir + className + suffix"). Class file parsing only folds + * '/' into '.', so Windows separators ('\\'), drive designators (':') and ".." segments survive and would + * let a crafted class file write its HTML output outside the target directory (CWE-22). + * + * @param name the class name about to be used as part of a file name. + * @throws IOException Thrown if the name contains a path separator, a Windows-reserved file name character, a + * control character, or a ".." sequence. + */ + private static void checkFileNameSafe(final String name) throws IOException { + for (int i = 0; i < name.length(); i++) { + final char c = name.charAt(i); + if (c < ' ' || "\\/:*?\"<>|".indexOf(c) >= 0) { + throw new IOException("Refusing to write HTML for a class whose name contains the unsafe character (0x" + + Integer.toHexString(c) + "): " + name); + } + } + if (name.contains("..")) { + throw new IOException("Refusing to write HTML for a class whose name contains \"..\": " + name); + } + } + + /** + * Main program to convert class files to HTML. + * + * @param argv command line arguments. + * @throws IOException Thrown if an I/O error occurs. + */ + public static void _main(final String[] argv) throws IOException { final String[] fileName = new String[argv.length]; int files = 0; ClassParser parser = null; @@ -125,13 +154,13 @@ public static void main(final String[] argv) throws IOException { } /** - * Utility method that converts a class reference in the constant pool, i.e., an index to a string. + * Utility method that converts a class reference in the constant pool, that is, an index to a string. */ static String referenceClass(final int index) { String str = constantPool.getConstantString(index, Const.CONSTANT_Class); str = Utility.compactClassName(str); str = Utility.compactClassName(str, classPackage + ".", true); - return "" + str + ""; + return "" + toHTML(str) + ""; } static String referenceType(final String type) { @@ -146,20 +175,29 @@ static String referenceType(final String type) { if (basicTypes.contains(baseType)) { return "" + type + ""; } - return "" + shortType + ""; + return "" + toHTML(shortType) + ""; } static String toHTML(final String str) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < str.length(); i++) { - char ch; + final char ch; switch (ch = str.charAt(i)) { + case '&': + buf.append("&"); + break; case '<': buf.append("<"); break; case '>': buf.append(">"); break; + case '"': + buf.append("""); + break; + case '\'': + buf.append("'"); + break; case '\n': buf.append("\\n"); break; @@ -173,15 +211,24 @@ static String toHTML(final String str) { return buf.toString(); } + /** + * Escapes a class or type name taken from the constant pool for use as a relative link target inside an HREF + * attribute value. On top of the text escaping done by {@code toHTML(String)}, any ':' is replaced so an + * attacker-chosen name cannot smuggle a URL scheme such as "javascript:" into the generated link. + */ + static String toHTMLRef(final String str) { + return toHTML(str.replace(':', '_')); + } + private final JavaClass javaClass; // current class object private final String dir; /** - * Write contents of the given JavaClass into HTML files. + * Writes contents of the given JavaClass into HTML files. * - * @param javaClass The class to write - * @param dir The directory to put the files in + * @param javaClass The class to write. + * @param dir The directory to put the files in. * @throws IOException Thrown when an I/O exception of some sort has occurred. */ public Class2HTML(final JavaClass javaClass, final String dir) throws IOException { @@ -193,6 +240,7 @@ private Class2HTML(final JavaClass javaClass, final String dir, final Charset ch this.javaClass = javaClass; this.dir = dir; className = javaClass.getClassName(); // Remember full name + checkFileNameSafe(className); constantPool = javaClass.getConstantPool(); // Get package name by tacking off everything after the last '.' final int index = className.lastIndexOf('.'); @@ -215,13 +263,26 @@ private Class2HTML(final JavaClass javaClass, final String dir, final Charset ch private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws FileNotFoundException, UnsupportedEncodingException { try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) { - file.println("\n" + "Documentation for " + className + "" + "\n" + "\n" - + "\n" + "\n" + "\n" + "\n" - + "\n" + "\n" + "\n" + ""); + // @formatter:off + file.println("\n" + + "Documentation for " + toHTML(className) + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + ""); + // @formatter:on } final Attribute[] attributes = javaClass.getAttributes(); for (int i = 0; i < attributes.length; i++) { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassQueue.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassQueue.java index 82c4e52168c5..fa0483bb98a5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassQueue.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassQueue.java @@ -25,7 +25,6 @@ /** * Utility class implementing a (typesafe) queue of JavaClass objects. - * @LastModified: Jan 2020 */ public class ClassQueue { @@ -35,14 +34,35 @@ public class ClassQueue { @Deprecated protected LinkedList vec = new LinkedList<>(); // TODO not used externally + /** + * Constructs a new ClassQueue. + */ + public ClassQueue() { + } + + /** + * Removes and returns the first JavaClass from the queue. + * + * @return The first JavaClass from the queue. + */ public JavaClass dequeue() { return vec.removeFirst(); } + /** + * Checks if the queue is empty. + * + * @return true if the queue is empty. + */ public boolean empty() { return vec.isEmpty(); } + /** + * Adds a JavaClass to the end of the queue. + * + * @param clazz The JavaClass to add. + */ public void enqueue(final JavaClass clazz) { vec.addLast(clazz); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassSet.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassSet.java index e95e8fbd0a0e..36844c1958c5 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassSet.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -30,28 +30,60 @@ * Utility class implementing a (type-safe) set of JavaClass objects. Since JavaClass has no equals() method, the name of the class is used for comparison. * * @see ClassStack - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class ClassSet { private final Map map = new HashMap<>(); + /** + * Constructs a new ClassSet. + */ + public ClassSet() { + } + + /** + * Adds a JavaClass to the set. + * + * @param clazz The JavaClass to add. + * @return true if the class was added. + */ public boolean add(final JavaClass clazz) { return map.putIfAbsent(clazz.getClassName(), clazz) != null; } + /** + * Checks if the set is empty. + * + * @return true if the set is empty. + */ public boolean empty() { return map.isEmpty(); } + /** + * Gets the class names in the set. + * + * @return The class names in the set. + */ public String[] getClassNames() { return map.keySet().toArray(Const.EMPTY_STRING_ARRAY); } + /** + * Removes a JavaClass from the set. + * + * @param clazz The JavaClass to remove. + */ public void remove(final JavaClass clazz) { map.remove(clazz.getClassName()); } + /** + * Converts the set to an array. + * + * @return An array of JavaClass objects. + */ public JavaClass[] toArray() { return map.values().toArray(JavaClass.EMPTY_ARRAY); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassStack.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassStack.java index cc07acf7dbce..369094d631ba 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassStack.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ClassStack.java @@ -34,18 +34,44 @@ public class ClassStack { private final Stack stack = new Stack<>(); + /** + * Constructs a new ClassStack. + */ + public ClassStack() { + } + + /** + * Checks if the stack is empty. + * + * @return true if the stack is empty. + */ public boolean empty() { return stack.empty(); } + /** + * Pops a JavaClass from the stack. + * + * @return The JavaClass from the top of the stack. + */ public JavaClass pop() { return stack.pop(); } + /** + * Pushes a JavaClass onto the stack. + * + * @param clazz The JavaClass to push. + */ public void push(final JavaClass clazz) { stack.push(clazz); } + /** + * Gets the top JavaClass from the stack without removing it. + * + * @return The JavaClass at the top of the stack. + */ public JavaClass top() { return stack.peek(); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/CodeHTML.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/CodeHTML.java index 1935d724b3b9..f553766cdba0 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/CodeHTML.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/CodeHTML.java @@ -28,6 +28,7 @@ import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.classfile.Attribute; +import com.sun.org.apache.bcel.internal.classfile.ClassFormatException; import com.sun.org.apache.bcel.internal.classfile.Code; import com.sun.org.apache.bcel.internal.classfile.CodeException; import com.sun.org.apache.bcel.internal.classfile.ConstantFieldref; @@ -75,27 +76,27 @@ final class CodeHTML { /** * Disassemble a stream of byte codes and return the string representation. * - * @param stream data input stream - * @return String representation of byte code + * @param stream data input stream. + * @return String representation of byte code. */ private String codeToHTML(final ByteSequence bytes, final int methodNumber) throws IOException { final short opcode = (short) bytes.readUnsignedByte(); String name; - String signature; + final String signature; int defaultOffset = 0; - int low; - int high; + final int low; + final int high; int index; - int classIndex; - int vindex; - int constant; - int[] jumpTable; + final int classIndex; + final int vindex; + final int constant; + final int[] jumpTable; int noPadBytes = 0; - int offset; + final int offset; final StringBuilder buf = new StringBuilder(256); // CHECKSTYLE IGNORE MagicNumber buf.append("").append(Const.getOpcodeName(opcode)).append(""); /* - * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned + * Special case: Skip (0-3) padding bytes, that is, the following bytes are 4-byte-aligned */ if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) { final int remainder = bytes.getIndex() % 4; @@ -112,9 +113,16 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro high = bytes.readInt(); offset = bytes.getIndex() - 12 - noPadBytes - 1; defaultOffset += offset; + // Each jump table entry is a 4 byte offset, so a well-formed table cannot declare more entries than fit + // into the remaining byte code; checking before allocating keeps a crafted low/high pair from forcing a + // huge allocation. + final long jumpTableLength = (long) high - low + 1; + if (jumpTableLength < 0 || jumpTableLength * 4 > bytes.available()) { + throw new ClassFormatException("Invalid TABLESWITCH: low = " + low + ", high = " + high + " but only " + bytes.available() + " bytes remain"); + } buf.append(""); // Print switch indices in first row (and default) - jumpTable = new int[high - low + 1]; + jumpTable = new int[(int) jumpTableLength]; for (int i = 0; i < jumpTable.length; i++) { jumpTable[i] = offset + bytes.readInt(); buf.append(""); @@ -133,6 +141,10 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro case Const.LOOKUPSWITCH: final int npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - noPadBytes - 1; + // Each match-offset pair is 8 bytes, see the TABLESWITCH check above. + if (npairs < 0 || (long) npairs * 8 > bytes.available()) { + throw new ClassFormatException("Invalid LOOKUPSWITCH: npairs = " + npairs + " but only " + bytes.available() + " bytes remain"); + } jumpTable = new int[npairs]; defaultOffset += offset; buf.append("
    ").append(low + i).append("
    "); @@ -198,7 +210,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro case Const.LSTORE: case Const.RET: if (wide) { - vindex = bytes.readShort(); + vindex = bytes.readUnsignedShort(); wide = false; // Clear flag } else { vindex = bytes.readUnsignedByte(); @@ -226,7 +238,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro case Const.GETSTATIC: case Const.PUTFIELD: case Const.PUTSTATIC: - index = bytes.readShort(); + index = bytes.readUnsignedShort(); final ConstantFieldref c1 = constantPool.getConstant(index, Const.CONSTANT_Fieldref, ConstantFieldref.class); classIndex = c1.getClassIndex(); name = constantPool.getConstantString(classIndex, Const.CONSTANT_Class); @@ -234,10 +246,10 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro index = c1.getNameAndTypeIndex(); final String fieldName = constantPool.constantToString(index, Const.CONSTANT_NameAndType); if (name.equals(className)) { // Local field - buf.append("").append(fieldName) - .append("\n"); + buf.append("") + .append(Class2HTML.toHTML(fieldName)).append("\n"); } else { - buf.append(constantHtml.referenceConstant(classIndex)).append(".").append(fieldName); + buf.append(constantHtml.referenceConstant(classIndex)).append(".").append(Class2HTML.toHTML(fieldName)); } break; /* @@ -246,7 +258,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro case Const.CHECKCAST: case Const.INSTANCEOF: case Const.NEW: - index = bytes.readShort(); + index = bytes.readUnsignedShort(); buf.append(constantHtml.referenceConstant(index)); break; /* @@ -257,8 +269,8 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro case Const.INVOKEVIRTUAL: case Const.INVOKEINTERFACE: case Const.INVOKEDYNAMIC: - final int mIndex = bytes.readShort(); - String str; + final int mIndex = bytes.readUnsignedShort(); + final String str; if (opcode == Const.INVOKEINTERFACE) { // Special treatment needed bytes.readUnsignedByte(); // Redundant bytes.readUnsignedByte(); // Reserved @@ -284,7 +296,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro name = Class2HTML.referenceClass(classIndex); } str = Class2HTML.toHTML(constantPool.constantToString(constantPool.getConstant(index, Const.CONSTANT_NameAndType))); - // Get signature, i.e., types + // Get signature, that is, types final ConstantNameAndType c2 = constantPool.getConstant(index, Const.CONSTANT_NameAndType, ConstantNameAndType.class); signature = constantPool.constantToString(c2.getSignatureIndex(), Const.CONSTANT_Utf8); final String[] args = Utility.methodSignatureArgumentTypes(signature, false); @@ -306,7 +318,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro */ case Const.LDC_W: case Const.LDC2_W: - index = bytes.readShort(); + index = bytes.readUnsignedShort(); buf.append("") .append(Class2HTML.toHTML(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))).append(""); break; @@ -319,15 +331,15 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro * Array of references. */ case Const.ANEWARRAY: - index = bytes.readShort(); + index = bytes.readUnsignedShort(); buf.append(constantHtml.referenceConstant(index)); break; /* * Multidimensional array of references. */ case Const.MULTIANEWARRAY: - index = bytes.readShort(); - final int dimensions = bytes.readByte(); + index = bytes.readUnsignedShort(); + final int dimensions = bytes.readUnsignedByte(); buf.append(constantHtml.referenceConstant(index)).append(":").append(dimensions).append("-dimensional"); break; /* @@ -335,7 +347,7 @@ private String codeToHTML(final ByteSequence bytes, final int methodNumber) thro */ case Const.IINC: if (wide) { - vindex = bytes.readShort(); + vindex = bytes.readUnsignedShort(); constant = bytes.readShort(); wide = false; } else { @@ -377,7 +389,7 @@ private void findGotos(final ByteSequence bytes, final Code code) throws IOExcep gotoSet = new BitSet(bytes.available()); int opcode; /* - * First get Code attribute from method and the exceptions handled (try .. catch) in this method. We only need the line + * First get Code attribute from method and the exceptions handled (try-catch) in this method. We only need the line * number here. */ if (code != null) { @@ -411,7 +423,7 @@ private void findGotos(final ByteSequence bytes, final Code code) throws IOExcep final int remainder = bytes.getIndex() % 4; final int noPadBytes = remainder == 0 ? 0 : 4 - remainder; int defaultOffset; - int offset; + final int offset; for (int j = 0; j < noPadBytes; j++) { bytes.readByte(); } @@ -476,7 +488,7 @@ private void findGotos(final ByteSequence bytes, final Code code) throws IOExcep } /** - * Write a single method with the byte code associated with it. + * Writes a single method with the byte code associated with it. */ private void writeMethod(final Method method, final int methodNumber) throws IOException { // Get raw signature @@ -493,7 +505,7 @@ private void writeMethod(final Method method, final int methodNumber) throws IOE access = Utility.replace(access, " ", " "); // Get the method's attributes, the Code Attribute in particular final Attribute[] attributes = method.getAttributes(); - printWriter.print("

    " + access + " " + "" + Class2HTML.referenceType(type) + printWriter.print("

    " + access + " " + Class2HTML.referenceType(type) + " " + htmlName + "("); for (int i = 0; i < args.length; i++) { printWriter.print(Class2HTML.referenceType(args[i])); @@ -521,7 +533,7 @@ private void writeMethod(final Method method, final int methodNumber) throws IOE printWriter.print("

    "); @@ -529,14 +541,14 @@ private void writeMethod(final Method method, final int methodNumber) throws IOE } printWriter.println(""); } - if (code != null) { // No code, an abstract method, e.g. + if (code != null) { // No code, an abstract method, for example // System.out.println(name + "\n" + Utility.codeToString(code, constantPool, 0, -1)); // Print the byte code try (ByteSequence stream = new ByteSequence(code)) { stream.mark(stream.available()); findGotos(stream, c); stream.reset(); - printWriter.println("
    " + ""); + printWriter.println("
    Byte
    offset
    InstructionArgument
    "); while (stream.available() > 0) { final int offset = stream.getIndex(); final String str = codeToHTML(stream, methodNumber); @@ -548,7 +560,7 @@ private void writeMethod(final Method method, final int methodNumber) throws IOE if (gotoSet.get(offset)) { anchor = ""; } - String anchor2; + final String anchor2; if (stream.getIndex() == code.length) { anchor2 = "" + offset + ""; } else { diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ConstantHTML.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ConstantHTML.java index b3197f6d45a3..8b04a25452e6 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ConstantHTML.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ConstantHTML.java @@ -98,9 +98,9 @@ String referenceConstant(final int index) { private void writeConstant(final int index) { final byte tag = constants[index].getTag(); - int classIndex; - int nameIndex; - String ref; + final int classIndex; + final int nameIndex; + final String ref; // The header is always the same printWriter.println("

    " + index + " " + Const.getConstantName(tag) + "

    "); /* @@ -122,10 +122,11 @@ private void writeConstant(final int index) { // Get method name and its class final String methodName = constantPool.constantToString(nameIndex, Const.CONSTANT_NameAndType); final String htmlMethodName = Class2HTML.toHTML(methodName); - // Partially compacted class name, i.e., / -> . + // Partially compacted class name, that is, / -> . final String methodClass = constantPool.constantToString(classIndex, Const.CONSTANT_Class); String shortMethodClass = Utility.compactClassName(methodClass); // I.e., remove java.lang. shortMethodClass = Utility.compactClassName(shortMethodClass, classPackage + ".", true); // Remove class package prefix + shortMethodClass = Class2HTML.toHTML(shortMethodClass); // Get method signature final ConstantNameAndType c2 = constantPool.getConstant(nameIndex, Const.CONSTANT_NameAndType, ConstantNameAndType.class); final String signature = constantPool.constantToString(c2.getSignatureIndex(), Const.CONSTANT_Utf8); @@ -146,11 +147,11 @@ private void writeConstant(final int index) { if (methodClass.equals(className)) { ref = "" + htmlMethodName + ""; } else { - ref = "" + shortMethodClass + "." + htmlMethodName; + ref = "" + shortMethodClass + "." + htmlMethodName; } constantRef[index] = retType + " " + shortMethodClass + "." + htmlMethodName + " " + argTypes; - printWriter.println("

    " + retType + " " + ref + argTypes + " \n

      " + "
    • Class index(" + printWriter.println("

      " + retType + " " + ref + argTypes + " \n

      "); break; case Const.CONSTANT_Fieldref: @@ -162,14 +163,16 @@ private void writeConstant(final int index) { final String fieldClass = constantPool.constantToString(classIndex, Const.CONSTANT_Class); String shortFieldClass = Utility.compactClassName(fieldClass); // I.e., remove java.lang. shortFieldClass = Utility.compactClassName(shortFieldClass, classPackage + ".", true); // Remove class package prefix + shortFieldClass = Class2HTML.toHTML(shortFieldClass); final String fieldName = constantPool.constantToString(nameIndex, Const.CONSTANT_NameAndType); + final String htmlFieldName = Class2HTML.toHTML(fieldName); if (fieldClass.equals(className)) { - ref = "" + fieldName + ""; + ref = "" + htmlFieldName + ""; } else { - ref = "" + shortFieldClass + "." + fieldName + "\n"; + ref = "" + shortFieldClass + "." + htmlFieldName + "\n"; } constantRef[index] = "" + shortFieldClass + "." + fieldName + ""; + + className + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + htmlFieldName + ""; printWriter.println("

      " + ref + "
      \n" + "

      "); break; @@ -179,7 +182,8 @@ private void writeConstant(final int index) { final String className2 = constantPool.constantToString(index, tag); // / -> . String shortClassName = Utility.compactClassName(className2); // I.e., remove java.lang. shortClassName = Utility.compactClassName(shortClassName, classPackage + ".", true); // Remove class package prefix - ref = "" + shortClassName + ""; + shortClassName = Class2HTML.toHTML(shortClassName); + ref = "" + shortClassName + ""; constantRef[index] = "" + shortClassName + ""; printWriter.println("

      " + ref + "

      \n"); break; diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/InstructionFinder.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/InstructionFinder.java index 510fe4a03a66..bfb8982dc821 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/InstructionFinder.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/InstructionFinder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -25,7 +25,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -34,48 +33,49 @@ import com.sun.org.apache.bcel.internal.generic.ClassGenException; import com.sun.org.apache.bcel.internal.generic.InstructionHandle; import com.sun.org.apache.bcel.internal.generic.InstructionList; +import jdk.xml.internal.Utils; /** - * InstructionFinder is a tool to search for given instructions patterns, i.e., match sequences of instructions in an - * instruction list via regular expressions. This can be used, e.g., in order to implement a peep hole optimizer that + * InstructionFinder is a tool to search for given instructions patterns, that is, match sequences of instructions in an + * instruction list via regular expressions. This can be used, for example, in order to implement a peep hole optimizer that * looks for code patterns and replaces them with faster equivalents. * *

      * This class internally uses the java.util.regex package to search for regular expressions. - * + *

      + *

      * A typical application would look like this: - * + *

      *
      - *
      - *
      - *   InstructionFinder f   = new InstructionFinder(il);
      - *   String            pat = "IfInstruction ICONST_0 GOTO ICONST_1 NOP (IFEQ|IFNE)";
      + *   InstructionFinder f = new InstructionFinder(il);
      + *   String pat = "IfInstruction ICONST_0 GOTO ICONST_1 NOP (IFEQ|IFNE)";
        *
        *   for (Iterator i = f.search(pat, constraint); i.hasNext(); ) {
      - *   InstructionHandle[] match = (InstructionHandle[])i.next();
      - *   ...
      - *   il.delete(match[1], match[5]);
      - *   ...
      + *       InstructionHandle[] match = (InstructionHandle[])i.next();
      + *       ...
      + *       il.delete(match[1], match[5]);
      + *       ...
        *   }
      - *
      - *
      +
        * 
      * * @see com.sun.org.apache.bcel.internal.generic.Instruction * @see InstructionList - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public class InstructionFinder { /** * Code patterns found may be checked using an additional user-defined constraint object whether they really match the - * needed criterion. I.e., check constraints that can not expressed with regular expressions. + * needed criterion. I.e., check constraints that cannot expressed with regular expressions. */ public interface CodeConstraint { /** - * @param match array of instructions matching the requested pattern - * @return true if the matched area is really useful + * Checks if the matched code area is really useful. + * + * @param match array of instructions matching the requested pattern. + * @return true if the matched area is really useful. */ boolean checkCode(InstructionHandle[] match); } @@ -171,12 +171,12 @@ public interface CodeConstraint { * Replace symbolic names of instructions with the appropriate character and remove all white space from string. Meta * characters such as +, * are ignored. * - * @param pattern The pattern to compile - * @return translated regular expression string + * @param pattern The pattern to compile. + * @return translated regular expression string. */ private static String compilePattern(final String pattern) { // Bug: BCEL-77 - Instructions are assumed to be english, to avoid odd Locale issues - final String lower = pattern.toLowerCase(Locale.ENGLISH); + final String lower = Utils.toLowerCase(pattern); final StringBuilder buf = new StringBuilder(); final int size = pattern.length(); for (int i = 0; i < size; i++) { @@ -209,7 +209,7 @@ private static char makeChar(final short opcode) { /** * Map symbolic instruction names like "getfield" to a single character. * - * @param pattern instruction pattern in lower case + * @param pattern instruction pattern in lower case. * @return encoded string for a pattern such as "BranchInstruction". */ private static String mapName(final String pattern) { @@ -243,8 +243,11 @@ private static String precompile(final short from, final short to, final short e private InstructionHandle[] handles; // map instruction // list to array + /** - * @param il instruction list to search for given patterns + * Constructs an InstructionFinder. + * + * @param il instruction list to search for given patterns. */ public InstructionFinder(final InstructionList il) { this.il = il; @@ -252,21 +255,23 @@ public InstructionFinder(final InstructionList il) { } /** - * @return the inquired instruction list + * Gets the inquired instruction list. + * + * @return The inquired instruction list. */ public final InstructionList getInstructionList() { return il; } /** - * @return the matched piece of code as an array of instruction (handles) + * @return The matched piece of code as an array of instruction (handles). */ private InstructionHandle[] getMatch(final int matchedFrom, final int matchLength) { return Arrays.copyOfRange(handles, matchedFrom, matchedFrom + matchLength); } /** - * Reread the instruction list, e.g., after you've altered the list upon a match. + * Reread the instruction list, for example, after you've altered the list upon a match. */ public final void reread() { final int size = il.getLength(); @@ -282,8 +287,8 @@ public final void reread() { /** * Start search beginning from the start of the given instruction list. * - * @param pattern the instruction pattern to search for, where case is ignored - * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area + * @param pattern The instruction pattern to search for, where case is ignored. + * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area. */ public final Iterator search(final String pattern) { return search(pattern, il.getStart(), null); @@ -292,9 +297,9 @@ public final Iterator search(final String pattern) { /** * Start search beginning from the start of the given instruction list. Check found matches with the constraint object. * - * @param pattern the instruction pattern to search for, case is ignored - * @param constraint constraints to be checked on matching code - * @return instruction handle or 'null' if the match failed + * @param pattern The instruction pattern to search for, case is ignored. + * @param constraint constraints to be checked on matching code. + * @return instruction handle or 'null' if the match failed. */ public final Iterator search(final String pattern, final CodeConstraint constraint) { return search(pattern, il.getStart(), constraint); @@ -303,17 +308,17 @@ public final Iterator search(final String pattern, final Co /** * Start search beginning from 'from'. * - * @param pattern the instruction pattern to search for, where case is ignored - * @param from where to start the search in the instruction list - * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area + * @param pattern The instruction pattern to search for, where case is ignored. + * @param from where to start the search in the instruction list. + * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area. */ public final Iterator search(final String pattern, final InstructionHandle from) { return search(pattern, from, null); } /** - * Search for the given pattern in the instruction list. You can search for any valid opcode via its symbolic name, e.g. - * "istore". You can also use a super class or an interface name to match a whole set of instructions, e.g. + * Search for the given pattern in the instruction list. You can search for any valid opcode via its symbolic name, for example + * "istore". You can also use a super class or an interface name to match a whole set of instructions, for example * "BranchInstruction" or "LoadInstruction". "istore" is also an alias for all "istore_x" instructions. Additional * aliases are "if" for "ifxx", "if_icmp" for "if_icmpxx", "if_acmp" for "if_acmpxx". * @@ -321,9 +326,9 @@ public final Iterator search(final String pattern, final In * pattern. * * For the rest the usual pattern matching rules for regular expressions apply. - *

      + *

      * Example pattern: - * + *

      *
            * search("BranchInstruction NOP ((IfInstruction|GOTO)+ ISTORE Instruction)*");
            * 
      @@ -331,11 +336,12 @@ public final Iterator search(final String pattern, final In *

      * If you alter the instruction list upon a match such that other matching areas are affected, you should call reread() * to update the finder and call search() again, because the matches are cached. + *

      * - * @param pattern the instruction pattern to search for, where case is ignored - * @param from where to start the search in the instruction list - * @param constraint optional CodeConstraint to check the found code pattern for user-defined constraints - * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area + * @param pattern The instruction pattern to search for, where case is ignored. + * @param from where to start the search in the instruction list. + * @param constraint optional CodeConstraint to check the found code pattern for user-defined constraints. + * @return iterator of matches where e.nextElement() returns an array of instruction handles describing the matched area. */ public final Iterator search(final String pattern, final InstructionHandle from, final CodeConstraint constraint) { final String search = compilePattern(pattern); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/MethodHTML.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/MethodHTML.java index a75a58bedbf4..0b0c74a7ba90 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/MethodHTML.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/MethodHTML.java @@ -55,13 +55,13 @@ final class MethodHTML { printWriter.print(charset.name()); printWriter.println("\">"); printWriter.println("
    Byte
    offset
    InstructionArgument
    "); - printWriter.println("" + ""); + printWriter.println(""); for (final Field field : fields) { writeField(field); } printWriter.println("
    Access flagsTypeField name
    Access flagsTypeField name
    "); printWriter.println("" - + "" + ""); + + ""); for (int i = 0; i < methods.length; i++) { writeMethod(methods[i], i); } @@ -72,16 +72,16 @@ final class MethodHTML { /** * Print field of class. * - * @param field field to print + * @param field field to print. */ private void writeField(final Field field) { final String type = Utility.signatureToString(field.getSignature()); final String name = field.getName(); String access = Utility.accessToString(field.getAccessFlags()); - Attribute[] attributes; + final Attribute[] attributes; access = Utility.replace(access, " ", " "); printWriter.print("\n"); + + Class2HTML.toHTML(name) + "\">" + Class2HTML.toHTML(name) + ""); attributes = field.getAttributes(); // Write them to the Attributes.html file with anchor "[]" for (int i = 0; i < attributes.length; i++) { @@ -91,7 +91,8 @@ private void writeField(final Field field) { if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // Default value final String str = attributes[i].toString(); // Reference attribute in _attributes.html - printWriter.print("\n"); + printWriter.print("\n"); break; } } @@ -107,7 +108,6 @@ private void writeMethod(final Method method, final int methodNumber) { final String type = Utility.methodSignatureReturnType(signature, false); // Get method name final String name = method.getName(); - String htmlName; // Get method's access flags String access = Utility.accessToString(method.getAccessFlags()); // Get the method's attributes, the Code Attribute in particular @@ -116,9 +116,9 @@ private void writeMethod(final Method method, final int methodNumber) { * HTML doesn't like names like and spaces are places to break lines. Both we don't want... */ access = Utility.replace(access, " ", " "); - htmlName = Class2HTML.toHTML(name); + final String htmlName = Class2HTML.toHTML(name); printWriter.print(""); - printWriter.print("\n
    Access flagsReturn typeMethod nameArguments
    Return typeMethod nameArguments
    " + access + "" + Class2HTML.referenceType(type) + "" + name + "= " + str + "= " + + Class2HTML.toHTML(str) + "
    " + access + "" + Class2HTML.referenceType(type) + "" + "" + printWriter.print("" + Class2HTML.referenceType(type) + "" + htmlName + "("); for (int i = 0; i < args.length; i++) { printWriter.print(Class2HTML.referenceType(args[i])); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ModularRuntimeImage.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ModularRuntimeImage.java index fd7cd0d2dc36..4d9ed07e8214 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ModularRuntimeImage.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/ModularRuntimeImage.java @@ -1,6 +1,5 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -42,6 +41,7 @@ * Wraps a Java 9 JEP 220 modular runtime image. Requires the JRT NIO file system. * * @since 6.3 + * @LastModified: Nov 2026 */ public class ModularRuntimeImage implements Closeable { @@ -63,8 +63,7 @@ public ModularRuntimeImage() { * Constructs an instance using the JRT file system implementation from a specific Java Home. * * @param javaHome Path to a Java 9 or greater home. - * - * @throws IOException an I/O error occurs accessing the file system + * @throws IOException Thrown if I/O error occurs accessing the file system. */ public ModularRuntimeImage(final String javaHome) throws IOException { final Map emptyMap = Collections.emptyMap(); @@ -85,10 +84,19 @@ public void close() throws IOException { classLoader.close(); } if (fileSystem != null) { - fileSystem.close(); + try { + fileSystem.close(); + } catch (final UnsupportedOperationException e) { + // do nothing + } } } + /** + * Gets the file system. + * + * @return The file system. + */ public FileSystem getFileSystem() { return fileSystem; } @@ -97,8 +105,8 @@ public FileSystem getFileSystem() { * Lists all entries in the given directory. * * @param dirPath directory path. - * @return a list of dir entries if an I/O error occurs - * @throws IOException an I/O error occurs accessing the file system + * @return A list of dir entries if an I/O error occurs. + * @throws IOException Thrown if I/O error occurs accessing the file system. */ public List list(final Path dirPath) throws IOException { final List list = new ArrayList<>(); @@ -112,8 +120,8 @@ public List list(final Path dirPath) throws IOException { * Lists all entries in the given directory. * * @param dirName directory path. - * @return a list of dir entries if an I/O error occurs - * @throws IOException an I/O error occurs accessing the file system + * @return A list of dir entries if an I/O error occurs. + * @throws IOException Thrown if I/O error occurs accessing the file system. */ public List list(final String dirName) throws IOException { return list(fileSystem.getPath(dirName)); @@ -122,8 +130,8 @@ public List list(final String dirName) throws IOException { /** * Lists all modules. * - * @return a list of modules - * @throws IOException an I/O error occurs accessing the file system + * @return A list of modules. + * @throws IOException Thrown if I/O error occurs accessing the file system. */ public List modules() throws IOException { return list(MODULES_PATH); @@ -132,8 +140,8 @@ public List modules() throws IOException { /** * Lists all packages. * - * @return a list of modules - * @throws IOException an I/O error occurs accessing the file system + * @return A list of modules. + * @throws IOException Thrown if I/O error occurs accessing the file system. */ public List packages() throws IOException { return list(PACKAGES_PATH); diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Repository.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Repository.java index c44e36d0a81f..4cfff10cc2ed 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Repository.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/Repository.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -26,7 +26,7 @@ * used in the Repository.setRepository method. * * @see com.sun.org.apache.bcel.internal.Repository - * @LastModified: Sept 2025 + * @LastModified: Nov 2026 */ public interface Repository { @@ -37,30 +37,41 @@ public interface Repository { /** * Finds the class with the name provided, if the class isn't there, return NULL. + * + * @param className The class name. + * @return The JavaClass instance, or null. */ JavaClass findClass(String className); /** * Finds the JavaClass instance for the given run-time class object. * - * @throws ClassNotFoundException if the class can't be found. + * @param clazz The class. + * @return The JavaClass instance. + * @throws ClassNotFoundException Thrown if the class can't be found. */ JavaClass loadClass(Class clazz) throws ClassNotFoundException; /** * Finds the class with the name provided, if the class isn't there, make an attempt to load it. * - * @throws ClassNotFoundException if the class can't be found. + * @param className The class name. + * @return The JavaClass instance. + * @throws ClassNotFoundException Thrown if the class can't be found. */ JavaClass loadClass(String className) throws ClassNotFoundException; /** - * Removes class from repository + * Removes class from repository. + * + * @param clazz The class to remove. */ void removeClass(JavaClass clazz); /** - * Stores the provided class under "clazz.getClassName()" + * Stores the provided class under "clazz.getClassName()". + * + * @param clazz The class to store. */ void storeClass(JavaClass clazz); } diff --git a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/SyntheticRepository.java b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/SyntheticRepository.java index 470c6ea17b6b..907cdce0dff2 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/SyntheticRepository.java +++ b/src/java.xml/share/classes/com/sun/org/apache/bcel/internal/util/SyntheticRepository.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -40,7 +40,7 @@ * * @see com.sun.org.apache.bcel.internal.Repository * - * @LastModified: Feb 2023 + * @LastModified: Nov 2026 */ public class SyntheticRepository implements Repository { diff --git a/src/java.xml/share/classes/jdk/xml/internal/Utils.java b/src/java.xml/share/classes/jdk/xml/internal/Utils.java index f7f5c49387b1..59d59265766a 100644 --- a/src/java.xml/share/classes/jdk/xml/internal/Utils.java +++ b/src/java.xml/share/classes/jdk/xml/internal/Utils.java @@ -29,6 +29,7 @@ import java.net.URI; import java.nio.file.Path; import java.util.Arrays; +import java.util.Locale; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; @@ -182,4 +183,24 @@ public static URI createURI(String systemId) { return Path.of(systemId).toUri(); } } + + // converts the input to upper case using the ROOT locale + public static String toUpperCase(CharSequence input) { + return input == null ? null : input.toString().toUpperCase(Locale.ROOT); + } + + // converts the input to lower case using the ROOT locale + public static String toLowerCase(CharSequence input) { + return input == null ? null : input.toString().toLowerCase(Locale.ROOT); + } + + // converts the input to upper case using the specified locale + public static String toUpperCase(CharSequence input, Locale locale) { + return input == null ? null : input.toString().toUpperCase(locale); + } + + // converts the input to lower case using the specified locale + public static String toLowerCase(CharSequence input, Locale locale) { + return input == null ? null : input.toString().toLowerCase(locale); + } } diff --git a/src/java.xml/share/legal/bcel.md b/src/java.xml/share/legal/bcel.md index b64fc3640d4a..52a913982c92 100644 --- a/src/java.xml/share/legal/bcel.md +++ b/src/java.xml/share/legal/bcel.md @@ -1,10 +1,10 @@ -## Apache Commons Byte Code Engineering Library (BCEL) Version 6.10.0 +## Apache Commons Byte Code Engineering Library (BCEL) Version 6.13.0 ### Apache Commons BCEL Notice
     
         Apache Commons BCEL
    -    Copyright 2004-2022 The Apache Software Foundation
    +    Copyright 2004-2026 The Apache Software Foundation
     
         This product includes software developed at
         The Apache Software Foundation (https://www.apache.org/).
    diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
    index 8597b30b11f2..f8152aa3c46c 100644
    --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
    +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java
    @@ -720,10 +720,6 @@ VarSymbol addParametersReturnReceiver() {
                         rcvr = new VarSymbol(SYNTHETIC, names.fromString("rec$"), tree.getQualifierExpression().type, owner);
                         rcvr.pos = tree.pos;
                         receiverExpression = attr.makeNullCheck(tree.getQualifierExpression());
    -                    if (receiverExpression.hasTag(Tag.NULLCHK)) {
    -                        Type t = types.skipTypeVars(tree.getQualifierExpression().type, false);
    -                        receiverExpression.type = t.isCompound() ? erasure(tree.sym.owner.type) : erasure(t);
    -                    }
                         break;
                     case UNBOUND:
                         // The receiver is the first parameter, extract it and
    @@ -966,11 +962,7 @@ public void visitNewClass(JCNewClass tree) {
                 if (tree.def == null) {
                     tree.encl = translate(tree.encl, erasure(tree.encl.type));
                 } else {
    -                JCExpression expr = attr.makeNullCheck(tree.encl);
    -                if (expr.hasTag(Tag.NULLCHK)) {
    -                    expr.type = erasure(tree.encl.type);
    -                }
    -                tree.args = tree.args.prepend(expr);
    +                tree.args = tree.args.prepend(attr.makeNullCheck(tree.encl));
                     tree.encl = null;
                 }
             }
    @@ -1030,7 +1022,7 @@ public void visitAssignop(JCAssignOp tree) {
     
         public void visitUnary(JCUnary tree) {
             tree.arg = translate(tree.arg, (tree.getTag() == Tag.NULLCHK)
    -            ? tree.type
    +            ? erasure(tree.type)
                 : tree.operator.type.getParameterTypes().head);
             result = tree;
         }
    diff --git a/src/jdk.hotspot.agent/macosx/native/libsaproc/MacosxDebuggerLocal.m b/src/jdk.hotspot.agent/macosx/native/libsaproc/MacosxDebuggerLocal.m
    index 5ee6dd995639..42a7434502db 100644
    --- a/src/jdk.hotspot.agent/macosx/native/libsaproc/MacosxDebuggerLocal.m
    +++ b/src/jdk.hotspot.agent/macosx/native/libsaproc/MacosxDebuggerLocal.m
    @@ -161,18 +161,12 @@ static void throw_new_debugger_exception(JNIEnv* env, const char* errMsg) {
     
     #if defined(amd64)
         #define hsdb_thread_state_t     x86_thread_state64_t
    -    #define hsdb_float_state_t      x86_float_state64_t
         #define HSDB_THREAD_STATE       x86_THREAD_STATE64
    -    #define HSDB_FLOAT_STATE        x86_FLOAT_STATE64
         #define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT
    -    #define HSDB_FLOAT_STATE_COUNT  x86_FLOAT_STATE64_COUNT
     #elif defined(aarch64)
         #define hsdb_thread_state_t     arm_thread_state64_t
    -    #define hsdb_float_state_t      arm_neon_state64_t
         #define HSDB_THREAD_STATE       ARM_THREAD_STATE64
    -    #define HSDB_FLOAT_STATE        ARM_NEON_STATE64
         #define HSDB_THREAD_STATE_COUNT ARM_THREAD_STATE64_COUNT
    -    #define HSDB_FLOAT_STATE_COUNT  ARM_NEON_STATE64_COUNT
     #else
         #error UNSUPPORTED_ARCH
     #endif
    diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
    index 6339e41a3f45..910cd931ac98 100644
    --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
    +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java
    @@ -59,10 +59,11 @@
     import java.util.HashSet;
     import java.util.List;
     import java.util.Set;
    -import java.util.Timer;
    -import java.util.TimerTask;
     import java.util.concurrent.CountDownLatch;
     import java.util.concurrent.Executor;
    +import java.util.concurrent.RejectedExecutionHandler;
    +import java.util.concurrent.ScheduledExecutorService;
    +import java.util.concurrent.ScheduledThreadPoolExecutor;
     import java.util.concurrent.TimeUnit;
     
     import static java.nio.charset.StandardCharsets.ISO_8859_1;
    @@ -111,7 +112,6 @@ class ServerImpl {
         static final long MAX_REQ_TIME = getTimeMillis(ServerConfig.getMaxReqTime());
         static final long MAX_RSP_TIME = getTimeMillis(ServerConfig.getMaxRspTime());
         static final boolean HOST_VALIDATION_DISABLED = ServerConfig.isHostValidationDisabled();;
    -    static final boolean reqRspTimeoutEnabled = MAX_REQ_TIME != -1 || MAX_RSP_TIME != -1;
         // the maximum idle duration for a connection which is currently idle but has served
         // some request in the past
         static final long IDLE_INTERVAL = ServerConfig.getIdleIntervalMillis();
    @@ -126,7 +126,7 @@ class ServerImpl {
                     : IDLE_INTERVAL;
         }
     
    -    private Timer timer, timer1;
    +    private final ScheduledExecutorService scheduler;
         private final Logger logger;
         private Thread dispatcherThread;
     
    @@ -156,11 +156,15 @@ class ServerImpl {
             reqConnections = Collections.synchronizedSet(new HashSet());
             rspConnections = Collections.synchronizedSet(new HashSet());
             newlyAcceptedConnections = Collections.synchronizedSet(new HashSet<>());
    -        timer = new Timer("idle-timeout-task", true);
    -        timer.schedule(new IdleTimeoutTask(), IDLE_TIMER_TASK_SCHEDULE, IDLE_TIMER_TASK_SCHEDULE);
    +        var reqRspTimeoutEnabled = MAX_REQ_TIME != -1 || MAX_RSP_TIME != -1;
    +        scheduler = createScheduler(reqRspTimeoutEnabled ? 2 : 1, logger);
    +        scheduler.scheduleWithFixedDelay(
    +                new IdleTimeoutTask(),
    +                IDLE_TIMER_TASK_SCHEDULE, IDLE_TIMER_TASK_SCHEDULE, TimeUnit.MILLISECONDS);
             if (reqRspTimeoutEnabled) {
    -            timer1 = new Timer("req-rsp-timeout-task", true);
    -            timer1.schedule(new ReqRspTimeoutTask(), REQ_RSP_TIMER_SCHEDULE, REQ_RSP_TIMER_SCHEDULE);
    +            scheduler.scheduleWithFixedDelay(
    +                    new ReqRspTimeoutTask(),
    +                    REQ_RSP_TIMER_SCHEDULE, REQ_RSP_TIMER_SCHEDULE, TimeUnit.MILLISECONDS);
                 logger.log(Level.DEBUG, "HttpServer request/response timeout task schedule ms: ",
                         REQ_RSP_TIMER_SCHEDULE);
                 logger.log(Level.DEBUG, "MAX_REQ_TIME:  "+MAX_REQ_TIME);
    @@ -170,6 +174,19 @@ class ServerImpl {
             logger.log(Level.DEBUG, "HttpServer created "+protocol+" "+ addr);
         }
     
    +    private static ScheduledExecutorService createScheduler(int threadCount, Logger logger) {
    +        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (ignored, exception) ->
    +                logger.log(Level.ERROR, "Scheduled task execution has failed", exception);
    +        var threadFactory = Thread.ofPlatform()
    +                .daemon()
    +                .uncaughtExceptionHandler(uncaughtExceptionHandler)
    +                .factory();
    +        RejectedExecutionHandler rejectedExecutionHandler = (runnable, ignored) ->
    +                logger.log(Level.ERROR, "Failed executing task: " + runnable);
    +        return new ScheduledThreadPoolExecutor(
    +                threadCount, threadFactory, rejectedExecutionHandler);
    +    }
    +
         public void bind(InetSocketAddress addr, int backlog) throws IOException {
             if (bound) {
                 throw new BindException("HttpServer already bound");
    @@ -279,10 +296,7 @@ public void stop(int delay) {
                 allConnections.clear();
                 idleConnections.clear();
                 newlyAcceptedConnections.clear();
    -            timer.cancel();
    -            if (reqRspTimeoutEnabled) {
    -                timer1.cancel();
    -            }
    +            scheduler.shutdownNow();
                 logger.log(Level.TRACE, "connections closed");
     
                 if (dispatcherThread != null && dispatcherThread != Thread.currentThread()) {
    @@ -1057,7 +1071,7 @@ HttpServer getWrapper() {
         }
     
         void requestStarted(HttpConnection c) {
    -        c.reqStartedTime = System.currentTimeMillis();
    +        c.reqStartedTime = monotonicMilliTicks();
             c.setState(State.REQUEST);
             reqConnections.add(c);
         }
    @@ -1071,7 +1085,7 @@ void markIdle(HttpConnection c) {
                     // instead set boolean and close outside the synchronized block
                     close = true;
                 } else {
    -                c.idleStartTime = System.currentTimeMillis();
    +                c.idleStartTime = monotonicMilliTicks();
                     c.setState(State.IDLE);
                     idleConnections.add(c);
                 }
    @@ -1084,7 +1098,7 @@ void markIdle(HttpConnection c) {
         }
     
         void markNewlyAccepted(HttpConnection c) {
    -        c.idleStartTime = System.currentTimeMillis();
    +        c.idleStartTime = monotonicMilliTicks();
             c.setState(State.NEWLY_ACCEPTED);
             newlyAcceptedConnections.add(c);
         }
    @@ -1100,7 +1114,7 @@ void requestCompleted(HttpConnection c) {
             State s = c.getState();
             assert s == State.REQUEST : "State is not REQUEST ("+s+")";
             reqConnections.remove(c);
    -        c.rspStartedTime = System.currentTimeMillis();
    +        c.rspStartedTime = monotonicMilliTicks();
             rspConnections.add(c);
             c.setState(State.RESPONSE);
         }
    @@ -1115,10 +1129,22 @@ void responseCompleted(HttpConnection c) {
     
         /**
          * Responsible for closing connections that have been idle.
    -     * TimerTask run every CLOCK_TICK ms
          */
    -    class IdleTimeoutTask extends TimerTask {
    +    class IdleTimeoutTask implements Runnable {
    +
    +        @Override
             public void run() {
    +            try {
    +                run0();
    +            } catch (Throwable throwable) {
    +                var message = IdleTimeoutTask.class.getSimpleName() + " has failed";
    +                logger.log(Level.ERROR, message, throwable);
    +                // Rethrow to cancel the execution of the task
    +                throw new RuntimeException(message, throwable);
    +            }
    +        }
    +
    +        private void run0() {
                 closeConnections(idleConnections, IDLE_INTERVAL);
                 // if any newly accepted connection has been idle (i.e. no byte has been sent on that
                 // connection during the configured idle timeout period) then close it as well
    @@ -1126,7 +1152,7 @@ public void run() {
             }
     
             private void closeConnections(Set connections, long idleInterval) {
    -            long currentTime = System.currentTimeMillis();
    +            long currentTime = monotonicMilliTicks();
                 ArrayList toClose = new ArrayList<>();
     
                 connections.forEach(c -> {
    @@ -1151,12 +1177,23 @@ private void closeConnections(Set connections, long idleInterval
         /**
          * Responsible for closing connections which have timed out while in REQUEST or RESPONSE state
          */
    -    class ReqRspTimeoutTask extends TimerTask {
    +    class ReqRspTimeoutTask implements Runnable {
     
    -        // runs every TIMER_MILLIS
    +        @Override
             public void run() {
    +            try {
    +                run0();
    +            } catch (Throwable throwable) {
    +                var message = ReqRspTimeoutTask.class.getSimpleName() + " has failed";
    +                logger.log(Level.ERROR, message, throwable);
    +                // Rethrow to cancel the execution of the task
    +                throw new RuntimeException(message, throwable);
    +            }
    +        }
    +
    +        private void run0() {
                 ArrayList toClose = new ArrayList<>();
    -            final long currentTime = System.currentTimeMillis();
    +            final long currentTime = monotonicMilliTicks();
                 synchronized (reqConnections) {
                     if (MAX_REQ_TIME != -1) {
                         for (HttpConnection c : reqConnections) {
    @@ -1204,4 +1241,15 @@ private static long getTimeMillis(long secs) {
             // this handles potential numeric overflow that may have happened during conversion
             return milli > 0 ? milli : -1;
         }
    +
    +    /**
    +     * A monotonic clock substitute of {@link System#currentTimeMillis()}, which
    +     * uses wall clock, and hence, is unsuitable for elapsed time measurements.
    +     */
    +    private static long monotonicMilliTicks() {
    +        return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - START_INSTANT_NANOS);
    +    }
    +
    +    private static final long START_INSTANT_NANOS = System.nanoTime();
    +
     }
    diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java
    index d6a42d366c83..5af683e7be6f 100644
    --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java
    +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -34,9 +34,6 @@ public class JWebServer {
     
         private static final String SYS_PROP_MAX_CONNECTIONS = "jdk.httpserver.maxConnections";
         private static final String DEFAULT_JWEBSERVER_MAX_CONNECTIONS = "200";
    -
    -    private static final String SYS_PROP_ENHANCED_EXCEP = "jdk.includeInExceptions";
    -    private static final String DEFAULT_ENHANCED_EXCEP = "net";
         /**
          * This constructor should never be called.
          */
    @@ -63,7 +60,6 @@ public class JWebServer {
          */
         public static void main(String... args) {
             setMaxReqTime();
    -        setEnhancedExceptions();
             setMaxConnectionsIfNotSet();
     
             int ec = SimpleFileServerImpl.start(new PrintWriter(System.out, true), "jwebserver", args);
    @@ -83,14 +79,6 @@ private static void setMaxReqTime() {
             }
         }
     
    -    static void setEnhancedExceptions() {
    -        if (System.getProperty(SYS_PROP_ENHANCED_EXCEP) != null) {
    -            // an explicit value has already been set, so we don't override it
    -            return;
    -        }
    -        System.setProperty(SYS_PROP_ENHANCED_EXCEP, DEFAULT_ENHANCED_EXCEP);
    -    }
    -
         static void setMaxConnectionsIfNotSet() {
             if (System.getProperty(SYS_PROP_MAX_CONNECTIONS) == null) {
                 System.setProperty(SYS_PROP_MAX_CONNECTIONS, DEFAULT_JWEBSERVER_MAX_CONNECTIONS);
    diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/AbstractMask.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/AbstractMask.java
    index 256c06681784..4b5fc492a976 100644
    --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/AbstractMask.java
    +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/AbstractMask.java
    @@ -256,78 +256,6 @@ public VectorMask indexInRange(long offset, long limit) {
             return (AbstractVector) zero.blend(mone, this);
         }
     
    -    /**
    -     * Test if a masked memory access at a given offset into an array
    -     * of the given length will stay within the array.
    -     * The per-lane offsets are iota*esize.
    -     */
    -    /*package-private*/
    -    @ForceInline
    -    void checkIndexByLane(int offset, int length,
    -                          Vector iota,
    -                          int esize) {
    -        if (VectorIntrinsics.VECTOR_ACCESS_OOB_CHECK == 0) {
    -            return;
    -        }
    -        // Although the specification is simple, the implementation is
    -        // tricky, because the value iota*esize might possibly
    -        // overflow.  So we calculate our test values as scalars,
    -        // clipping to the range [-1..VLENGTH], and test them against
    -        // the unscaled iota vector, whose values are in [0..VLENGTH-1].
    -        int vlength = length();
    -        VectorMask badMask;
    -        if (esize == 1) {
    -            badMask = checkIndex0(offset, length, iota, vlength);
    -        } else if (offset >= 0) {
    -            // Masked access to multi-byte lanes in byte array.
    -            // It could be aligned anywhere.
    -            int elemCount = Math.min(vlength, (length - offset) / esize);
    -            badMask = checkIndex0(0, elemCount, iota, vlength);
    -        } else {
    -            int clipOffset = Math.max(offset, -(vlength * esize));
    -            badMask = checkIndex0(clipOffset, length,
    -                                  iota.lanewise(VectorOperators.MUL, esize),
    -                                  vlength * esize);
    -        }
    -        badMask = badMask.and(this);
    -        if (badMask.anyTrue()) {
    -            int badLane = badMask.firstTrue();
    -            throw ((AbstractMask)badMask)
    -                   .checkIndexFailed(offset, badLane, length, esize);
    -        }
    -    }
    -
    -    private
    -    @ForceInline
    -    VectorMask checkIndex0(int offset, int length,
    -                              Vector iota, int vlength) {
    -        // An active lane is bad if its number is greater than
    -        // length-offset, since when added to offset it will step off
    -        // of the end of the array.  To avoid overflow when
    -        // converting, clip the comparison value to [0..vlength]
    -        // inclusive.
    -        int indexLimit = Math.max(0, Math.min(length - offset, vlength));
    -        VectorMask badMask =
    -            iota.compare(GE, iota.broadcast(indexLimit));
    -        if (offset < 0) {
    -            // An active lane is bad if its number is less than
    -            // -offset, because when added to offset it will then
    -            // address an array element at a negative index.  To avoid
    -            // overflow when converting, clip the comparison value at
    -            // vlength.  This specific expression works correctly even
    -            // when offset is Integer.MIN_VALUE.
    -            int firstGoodIndex = -Math.max(offset, -vlength);
    -            VectorMask badMask2 =
    -                iota.compare(LT, iota.broadcast(firstGoodIndex));
    -            if (indexLimit >= vlength) {
    -                badMask = badMask2;  // 1st badMask is all true
    -            } else {
    -                badMask = badMask.or(badMask2);
    -            }
    -        }
    -        return badMask;
    -    }
    -
         /**
          * Test if a masked memory access at a given offset into an array
          * of the given length will stay within the array.
    @@ -341,29 +269,17 @@ void checkIndexByLane(long offset, long length,
             if (VectorIntrinsics.VECTOR_ACCESS_OOB_CHECK == 0) {
                 return;
             }
    -        // Although the specification is simple, the implementation is
    -        // tricky, because the value iota*esize might possibly
    -        // overflow.  So we calculate our test values as scalars,
    -        // clipping to the range [-1..VLENGTH], and test them against
    -        // the unscaled iota vector, whose values are in [0..VLENGTH-1].
    +        assert length >= 0;
             int vlength = length();
    -        VectorMask badMask;
    -        if (esize == 1) {
    -            badMask = checkIndex0(offset, length, iota, vlength);
    -        } else if (offset >= 0) {
    -            // Masked access to multi-byte lanes in byte array.
    -            // It could be aligned anywhere.
    -            // 0 <= elemCount <= vlength
    -            int elemCount = (int) Math.min(vlength, (length - offset) / esize);
    -            badMask = checkIndex0(0, elemCount, iota, vlength);
    -        } else {
    -            // -vlength * esize <= clipOffset <= 0
    -            int clipOffset = (int) Math.max(offset, -(vlength * esize));
    -            badMask = checkIndex0(clipOffset, length,
    -                    iota.lanewise(VectorOperators.MUL, esize),
    -                    vlength * esize);
    -        }
    +        // badMask marks lanes that are not valid, i.e. fall outside
    +        // the segment.
    +
    +        // The implementation assumes that iota*esize will not overflow.
    +        VectorMask badMask = checkIndex0(offset, length - esize + 1,
    +                iota.lanewise(VectorOperators.MUL, esize),
    +                vlength * esize);
             badMask = badMask.and(this);
    +        // if any active lanes fall outside, throw.
             if (badMask.anyTrue()) {
                 int badLane = badMask.firstTrue();
                 throw ((AbstractMask)badMask)
    @@ -374,34 +290,67 @@ void checkIndexByLane(long offset, long length,
         private
         @ForceInline
         VectorMask checkIndex0(long offset, long length,
    -                              Vector iota, int vlength) {
    -        // An active lane is bad if its number is greater than
    -        // length-offset, since when added to offset it will step off
    -        // of the end of the array.  To avoid overflow when
    -        // converting, clip the comparison value to [0..vlength]
    -        // inclusive.
    -        // 0 <= indexLimit <= vlength
    -        int indexLimit = (int) Math.max(0, Math.min(length - offset, vlength));
    -        VectorMask badMask =
    -                iota.compare(GE, iota.broadcast(indexLimit));
    +                              Vector iotaScaled, int vlengthScaled) {
    +        // This method takes:
    +        // - vector length scaled by esize (vlengthScaled)
    +        // - vector of lane offsets for the given vector type
    +        //   with values (0, esize, 2 * esize, ..., vlengthScaled - esize) (iotaScaled)
    +        // - an offset into the segment at which the access
    +        //   will take place (offset)
    +        // - the length of the segment, reduced by esize - 1 (length)
    +        // Returns a mask where bad lanes are set to true
    +        // and good lanes are set to false.
    +        // Bad lanes are defined as lanes whose offset falls below 0
    +        // or above length.
    +        // Technically, the algorithm is equivalent to:
    +        // offsets = iotaScaled + offset
    +        // mask = !(0 <= offsets < length)
    +        // except it's trying hard to avoid overflows.
    +
    +        // iotaScaled is scaled by esize, it is the caller's responsibility
    +        // to adjust the length down by esize - 1 to ensure that the lanes
    +        // completely fit in bounds. If esize = 1 no adjustment is required.
    +
    +        // The algorithm assumes that:
    +        // - values in iotaScaled are between [0, vlengthScaled)
    +        // - vector type can represent values in [0, vlengthScaled) range with full precision
    +        //   (this will not work for float8)
    +        assert vlengthScaled > 0;
    +        if (length < offset || length < 0 || offset <= -vlengthScaled) {
    +            return vectorSpecies().maskAll(true);
    +        }
    +
    +        // For each index i, the access at i is in-bounds if and only if
    +        // 0 <= offset + i < length
             if (offset < 0) {
    -            // An active lane is bad if its number is less than
    -            // -offset, because when added to offset it will then
    -            // address an array element at a negative index.  To avoid
    -            // overflow when converting, clip the comparison value at
    -            // vlength.  This specific expression works correctly even
    -            // when offset is Integer.MIN_VALUE.
    -            // 0 <= firstGoodIndex <= vlength
    -            int firstGoodIndex = (int) -Math.max(offset, -vlength);
    -            VectorMask badMask2 =
    -                    iota.compare(LT, iota.broadcast(firstGoodIndex));
    -            if (indexLimit >= vlength) {
    -                badMask = badMask2;  // 1st badMask is all true
    +            // 0 <= offset + i is equivalent to E(-offset) < i;
    +            // E(-offset) will be precise because -vlengthScaled < offset < 0
    +            VectorMask lowMask =
    +                    iotaScaled.compare(LT, iotaScaled.broadcast(-offset));
    +            // check if we need to mask lanes above length.
    +            // offset < 0 and vlengthScaled > 0, so offset + vlengthScaled will not overflow
    +            if (offset + vlengthScaled > length) {
    +                // offset + i < length is equivalent to i < E(length - offset)
    +                // E(length - offset) will be precise because 0 <= length - offset < vlengthScaled
    +                VectorMask highMask =
    +                        iotaScaled.compare(GE, iotaScaled.broadcast(length - offset));
    +                return highMask.or(lowMask);
    +
                 } else {
    -                badMask = badMask.or(badMask2);
    +                return lowMask;
                 }
    +        } else {
    +            // 0 <= offset + i is guaranteed here because offset >= 0 and i >= 0
    +            // offset + i < length is equivalent to i < E(min(vlengthScaled, length - offset))
    +            // length - offset will not underflow because 0 <= offset <= length,
    +            // length - offset can be clamped to vlengthScaled because i < vlengthScaled.
    +
    +            // Alternatively, we could directly return an all-false mask if length - offset >= vlengthScaled.
    +            int indexLimit = Math.clamp(length - offset, 0, vlengthScaled);
    +            VectorMask highMask =
    +                    iotaScaled.compare(GE, iotaScaled.broadcast(indexLimit));
    +            return highMask;
             }
    -        return badMask;
         }
     
         private IndexOutOfBoundsException checkIndexFailed(long offset, int lane,
    diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java
    index dfdd2a304c66..6129d3beae50 100644
    --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java
    +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java
    @@ -490,7 +490,8 @@ public static Float16 valueOf(String s) throws NumberFormatException {
                 || Math.abs(trialResult) > (65504.0 + 32.0) || // MAX_VALUE + ulp(MAX_VALUE),
                                                                // handles infinities too
                 Double.isNaN(trialResult) ||
    -            noDoubleRoundingToFloat16(trialResult)) {
    +            (Math.abs(trialResult) > 0x1.0p-14 && // Float16.MIN_NORMAL, avoid subnormal range
    +             noDoubleRoundingToFloat16(trialResult))) {
                 return valueOf(trialResult);
             } else {
                 // If double rounding is not ruled out, re-parse, create a
    diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/event/EventWriter.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/event/EventWriter.java
    index f35e297c39d8..bcafdb229c2e 100644
    --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/event/EventWriter.java
    +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/event/EventWriter.java
    @@ -152,7 +152,12 @@ public void putString(String s) {
     
         private void putStringValue(String s) {
             int length = s.length();
    -        if (isValidForSize(1 + 5 + 3 * length)) {
    +        long size = 1L + 5L + 3L * length;
    +        if (size > Integer.MAX_VALUE) {
    +            valid = false;
    +            return;
    +        }
    +        if (isValidForSize((int)size)) {
                 putUncheckedByte(StringParser.Encoding.CHAR_ARRAY.byteValue()); // 1 byte
                 putUncheckedInt(length); // max 5 bytes
                 for (int i = 0; i < length; i++) {
    diff --git a/src/jdk.jpackage/windows/native/libjpackage/IconSwap.cpp b/src/jdk.jpackage/windows/native/libjpackage/IconSwap.cpp
    index b7d604fc6594..84336cc03c6a 100644
    --- a/src/jdk.jpackage/windows/native/libjpackage/IconSwap.cpp
    +++ b/src/jdk.jpackage/windows/native/libjpackage/IconSwap.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -131,7 +131,7 @@ bool ChangeIcon(HANDLE update, const wstring& iconTarget) {
     
         LPGRPICONDIR lpgid = (LPGRPICONDIR) malloc(
                 sizeof (GRPICONDIR) + (sizeof (GRPICONDIRENTRY) * (idCount - 1)));
    -    if (lpid == NULL) {
    +    if (lpgid == NULL) {
             CloseHandle(icon);
             free(lpid);
             printf("Error: Failed to allocate memory\n");
    @@ -156,6 +156,13 @@ bool ChangeIcon(HANDLE update, const wstring& iconTarget) {
         // Store images in .EXE
         for (int i = 0; i < lpid->idCount; i++) {
             LPBYTE lpBuffer = (LPBYTE) malloc(lpid->idEntries[i].dwBytesInRes);
    +        if (lpBuffer == NULL) {
    +            free(lpid);
    +            free(lpgid);
    +            CloseHandle(icon);
    +            printf("Error: Failed to allocate memory\n");
    +            return false;
    +        }
             SetFilePointer(icon, lpid->idEntries[i].dwImageOffset,
                     NULL, FILE_BEGIN);
             ReadFile(icon, lpBuffer, lpid->idEntries[i].dwBytesInRes,
    diff --git a/test/hotspot/gtest/gc/g1/test_g1IHOPControl.cpp b/test/hotspot/gtest/gc/g1/test_g1IHOPControl.cpp
    index c908cb021b3f..d31d9867aa7c 100644
    --- a/test/hotspot/gtest/gc/g1/test_g1IHOPControl.cpp
    +++ b/test/hotspot/gtest/gc/g1/test_g1IHOPControl.cpp
    @@ -187,7 +187,7 @@ TEST_VM(G1IHOPControl, allocation_tracker_incr) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       G1IHOPTestController ctrl(false /* adaptive */, initial_ihop, 100 /* target_occupancy */);
       double const time_step_s = 1.0;
       double gc_start_time_s = time_step_s;
    @@ -237,7 +237,7 @@ TEST_VM(G1IHOPControl, non_adaptive_ihop) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
     
       G1IHOPTestController ctrl(false /* adaptive */, initial_ihop, 100 /* target_occupancy */);
     
    @@ -258,7 +258,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_not_enough_samples) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
     
       G1IHOPTestController ctrl(true /* adaptive */, initial_ihop, 100 /* target_occupancy */);
     
    @@ -279,7 +279,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_non_humongous_only) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -311,7 +311,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_peak_humongous_only) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -342,7 +342,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_combined) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -373,7 +373,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_high_alloc_pressure) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -399,7 +399,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_young_reserve) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -449,7 +449,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_recovers_after_spike) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
     
    @@ -495,7 +495,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_reuse_eagerly_reclaimed) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
     
       size_t target_occupancy = 100;
       size_t young_reserve    = 10;
    @@ -556,7 +556,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_eager_reclaim_reduces_extra_humongous_occup
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -626,7 +626,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_cycle_duration) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -660,7 +660,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_cycle_duration_scales) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -715,7 +715,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_gc_humongous_allocation) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
       // G1Predictions require 5 or more samples to skip special considerations for
       // small samples.
       size_t num_samples = 5;
    @@ -786,7 +786,7 @@ TEST_VM(G1IHOPControl, adaptive_ihop_humongous_allocation_causes_conc_start) {
         return;
       }
     
    -  size_t initial_ihop = InitiatingHeapOccupancyPercent;
    +  size_t initial_ihop = G1IHOP;
     
       size_t target_occupancy = 100;
     
    diff --git a/test/hotspot/gtest/opto/test_typejavaptr.cpp b/test/hotspot/gtest/opto/test_typejavaptr.cpp
    index 6bf42c251fd3..969ab0a155ca 100644
    --- a/test/hotspot/gtest/opto/test_typejavaptr.cpp
    +++ b/test/hotspot/gtest/opto/test_typejavaptr.cpp
    @@ -506,10 +506,10 @@ class TypePtrMirror {
     
       const TypePtrMirror* meet(const TypePtrMirror* o) const { ShouldNotReachHere(); }
       const TypePtrMirror* join(const TypePtrMirror* o) const { ShouldNotReachHere(); }
    -  const TypePtrMirror* is_ptr()                     const { ShouldNotReachHere(); }
    +  const TypePtrMirror* as_ptr()                     const { ShouldNotReachHere(); }
     
    -  virtual const TypeOopPtrMirror*   is_oopptr()   const { ShouldNotReachHere(); }
    -  virtual const TypeKlassPtrMirror* is_klassptr() const { ShouldNotReachHere(); }
    +  virtual const TypeOopPtrMirror*   as_oopptr()   const { ShouldNotReachHere(); }
    +  virtual const TypeKlassPtrMirror* as_klassptr() const { ShouldNotReachHere(); }
     
       virtual void dump_on(outputStream& st) const {
         st.print("AnyPtr:");
    @@ -568,11 +568,11 @@ class TypeOopPtrMirror : public TypePtrMirror {
       constexpr const TypePtrMirror* speculative()    const { return nullptr; }
       constexpr int                  inline_depth()   const { return 0; }
     
    -  virtual const TypeOopPtrMirror*  is_oopptr()  const override { return this; }
    -  virtual const TypeInstPtrMirror* is_instptr() const = 0;
    -  virtual const TypeAryPtrMirror*  is_aryptr()  const = 0;
    +  const TypeOopPtrMirror* as_oopptr() const override { return this; }
    +  virtual const TypeInstPtrMirror* as_instptr() const = 0;
    +  virtual const TypeAryPtrMirror*  as_aryptr()  const = 0;
     
    -  virtual void dump_on(outputStream& st) const override = 0;
    +  void dump_on(outputStream& st) const override = 0;
     };
     
     static constexpr size_t TypeInstPtr_samples_size() {
    @@ -638,8 +638,8 @@ class TypeInstPtrMirror : public TypeOopPtrMirror {
     
       constexpr const ciInstanceKlassMirror* instance_klass() const { return _klass; }
     
    -  virtual const TypeInstPtrMirror* is_instptr() const override { return this; }
    -  virtual const TypeAryPtrMirror*  is_aryptr()  const override { ShouldNotReachHere(); }
    +  const TypeInstPtrMirror* as_instptr() const override { return this; }
    +  const TypeAryPtrMirror*  as_aryptr()  const override { ShouldNotReachHere(); }
     
       virtual void dump_on(outputStream& st) const override {
         st.print("InstPtr:");
    @@ -737,7 +737,7 @@ class ArySizeType {
       }
     
       const ArySizeType* operator->() const { return this; }
    -  const ArySizeType& is_int()     const { assert(!_empty, "must not be empty"); return *this; }
    +  const ArySizeType& as_int()     const { assert(!_empty, "must not be empty"); return *this; }
       const ArySizeType& isa_int()    const { return *this; }
     
       constexpr bool contains(int len) const {
    @@ -914,10 +914,10 @@ class TypeAryPtrMirror : public TypeOopPtrMirror {
       bool is_atomic()        const { return true; }
       Type::Offset field_offset() const { return Type::Offset::bottom; }
     
    -  virtual const TypeInstPtrMirror* is_instptr() const override { ShouldNotReachHere(); }
    -  virtual const TypeAryPtrMirror*  is_aryptr()  const override { return this; }
    +  const TypeInstPtrMirror* as_instptr() const override { ShouldNotReachHere(); }
    +  const TypeAryPtrMirror*  as_aryptr()  const override { return this; }
     
    -  virtual void dump_on(outputStream& st) const override {
    +  void dump_on(outputStream& st) const override {
         st.print("AryPtr:");
         dump_ptr(st);
         st.print(" - ");
    @@ -1223,9 +1223,9 @@ class TypeKlassPtrMirror : public TypePtrMirror {
       constexpr InterfaceSet interfaces()     const { return _interfaces; }
       constexpr bool         klass_is_exact() const { return ptr() == TypePtr::Constant; }
     
    -  virtual const TypeKlassPtrMirror*     is_klassptr()     const { return this; }
    -  virtual const TypeInstKlassPtrMirror* is_instklassptr() const = 0;
    -  virtual const TypeAryKlassPtrMirror*  is_aryklassptr()  const = 0;
    +  const TypeKlassPtrMirror* as_klassptr() const override { return this; }
    +  virtual const TypeInstKlassPtrMirror* as_instklassptr() const = 0;
    +  virtual const TypeAryKlassPtrMirror*  as_aryklassptr()  const = 0;
     };
     
     static constexpr size_t TypeInstKlassPtr_samples_size() {
    @@ -1288,10 +1288,10 @@ class TypeInstKlassPtrMirror : public TypeKlassPtrMirror {
     
       constexpr const ciInstanceKlassMirror* instance_klass() const { return _klass; }
     
    -  virtual const TypeInstKlassPtrMirror* is_instklassptr() const override { return this; }
    -  virtual const TypeAryKlassPtrMirror*  is_aryklassptr()  const override { ShouldNotReachHere(); }
    +  const TypeInstKlassPtrMirror* as_instklassptr() const override { return this; }
    +  const TypeAryKlassPtrMirror*  as_aryklassptr()  const override { ShouldNotReachHere(); }
     
    -  virtual void dump_on(outputStream& st) const override {
    +  void dump_on(outputStream& st) const override {
         st.print("InstKlassPtr:");
         dump_ptr(st);
         st.print(" - ");
    @@ -1496,10 +1496,10 @@ class TypeAryKlassPtrMirror : public TypeKlassPtrMirror {
       bool is_atomic()        const { return true; }
       bool is_refined_type()  const { return false; }
     
    -  virtual const TypeInstKlassPtrMirror* is_instklassptr() const override { ShouldNotReachHere(); }
    -  virtual const TypeAryKlassPtrMirror*  is_aryklassptr()  const override { return this; }
    +  const TypeInstKlassPtrMirror* as_instklassptr() const override { ShouldNotReachHere(); }
    +  const TypeAryKlassPtrMirror*  as_aryklassptr()  const override { return this; }
     
    -  virtual void dump_on(outputStream& st) const override {
    +  void dump_on(outputStream& st) const override {
         st.print("AryKlassPtr:");
         dump_ptr(st);
         st.print(" - ");
    @@ -1726,9 +1726,9 @@ class OopPtrMirror {
     
           const typename PtrType::InstType* type_inst;
           if constexpr (PtrType::is_oopptr_type) {
    -        type_inst = type->is_oopptr()->is_instptr();
    +        type_inst = type->as_instptr();
           } else {
    -        type_inst = type->is_klassptr()->is_instklassptr();
    +        type_inst = type->as_instklassptr();
           }
     
           if (type_is_exact) {
    @@ -1743,9 +1743,9 @@ class OopPtrMirror {
         if (type->base() == Type::InstPtr || type->base() == Type::InstKlassPtr) {
           const typename PtrType::InstType* type_inst;
           if constexpr (PtrType::is_oopptr_type) {
    -        type_inst = type->is_oopptr()->is_instptr();
    +        type_inst = type->as_instptr();
           } else {
    -        type_inst = type->is_klassptr()->is_instklassptr();
    +        type_inst = type->as_instklassptr();
           }
     
           return !type_is_exact && type_inst->instance_klass()->is_java_lang_Object() &&
    @@ -1754,9 +1754,9 @@ class OopPtrMirror {
     
         const typename PtrType::AryType* type_ary;
         if constexpr (PtrType::is_oopptr_type) {
    -      type_ary = type->is_oopptr()->is_aryptr();
    +      type_ary = type->as_aryptr();
         } else {
    -      type_ary = type->is_klassptr()->is_aryklassptr();
    +      type_ary = type->as_aryklassptr();
         }
         auto type_elem = type_ary->elem();
         auto ary_klass = klass->as_ary();
    @@ -1791,9 +1791,9 @@ class OopPtrMirror {
         }
         assert(type->ptr() == TypePtr::BotPTR || type->ptr() == TypePtr::NotNull || type->ptr() == TypePtr::Constant, "only AnyPtr can be top or null");
     
    -    auto type_oop = type->is_oopptr();
    +    auto type_oop = type->as_oopptr();
         if (_pointee.klass()->is_ary() && type->base() == Type::AryPtr &&
    -        !type_oop->is_aryptr()->size()->contains(_pointee.array_length())) {
    +        !type_oop->as_aryptr()->size()->contains(_pointee.array_length())) {
           return false;
         }
     
    @@ -1890,7 +1890,7 @@ class KlassPtrMirror {
         }
     
         assert(type->ptr() == TypePtr::BotPTR || type->ptr() == TypePtr::NotNull || type->ptr() == TypePtr::Constant, "only AnyPtr can be top or null");
    -    return OopPtrMirror::klass_satisfies(_klass, type->is_klassptr(), false);
    +    return OopPtrMirror::klass_satisfies(_klass, type->as_klassptr(), false);
       }
     
       void dump_on(outputStream& st) const {
    @@ -1982,9 +1982,9 @@ static void test_meet_join() {
           if (join->base() != Type::AnyPtr) {
             const PtrType* typed_join;
             if constexpr (PtrType::is_oopptr_type) {
    -          typed_join = join->is_oopptr();
    +          typed_join = join->as_oopptr();
             } else {
    -          typed_join = join->is_klassptr();
    +          typed_join = join->as_klassptr();
             }
     
             // Verify that join must be a subset of both t1 and t2
    diff --git a/test/hotspot/gtest/runtime/test_os_windows.cpp b/test/hotspot/gtest/runtime/test_os_windows.cpp
    index 5efa0580edad..b86e3a185e73 100644
    --- a/test/hotspot/gtest/runtime/test_os_windows.cpp
    +++ b/test/hotspot/gtest/runtime/test_os_windows.cpp
    @@ -811,23 +811,12 @@ TEST_VM(os_windows, large_page_init_decide_size) {
       }
     
     #if defined(AMD64)
    -  FLAG_SET_CMDLINE(LargePageSizeInBytes, 5 * M); // Set large page size to 5MB
    +  FLAG_SET_CMDLINE(LargePageSizeInBytes, 8 * M); // Set large page size to 8MB
       if (!EnableAllLargePageSizesForWindows) {
         decided_size = os::win32::large_page_init_decide_size(); // Recalculate decided size
         EXPECT_EQ(decided_size, 0) << "Expected decided size to be 0 for large pages bigger than 4mb on AMD64";
       }
     #endif
    -
    -  // Additional check for non-multiple of minimum size
    -  // Set an arbitrary large page size which is not a multiple of min_size
    -  FLAG_SET_CMDLINE(LargePageSizeInBytes, 5 * min_size + 1);
    -
    -  // Recalculate decided size
    -  decided_size = os::win32::large_page_init_decide_size();
    -
    -  // Assert that the decided size defaults to minimum page size when LargePageSizeInBytes
    -  // is not a multiple of the minimum size, assuming conditions are always met
    -  EXPECT_EQ(decided_size, 0) << "Expected decided size to default to 0 when LargePageSizeInBytes is not a multiple of minimum size";
     }
     
     class ReserveMemorySpecialRunnable : public TestRunnable {
    diff --git a/test/hotspot/gtest/runtime/test_special_flags.cpp b/test/hotspot/gtest/runtime/test_special_flags.cpp
    index a8392111f052..863035143831 100644
    --- a/test/hotspot/gtest/runtime/test_special_flags.cpp
    +++ b/test/hotspot/gtest/runtime/test_special_flags.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    diff --git a/test/hotspot/jtreg/ProblemList-Virtual.txt b/test/hotspot/jtreg/ProblemList-Virtual.txt
    index 0561a0def81c..b716f6a48a83 100644
    --- a/test/hotspot/jtreg/ProblemList-Virtual.txt
    +++ b/test/hotspot/jtreg/ProblemList-Virtual.txt
    @@ -25,7 +25,6 @@
     # Bugs
     
     runtime/jni/critical/SuspendInCritical.java 8384369 generic-all
    -serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java 8308026 generic-all
     serviceability/jvmti/Heap/IterateHeapWithEscapeAnalysisEnabled.java 8264699 generic-all
     serviceability/jvmti/FollowReferences/KindSystemClass/KindSystemClass.java 8383422 generic-all
     vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manyDiff_a/TestDescription.java 8308367 generic-all
    diff --git a/test/hotspot/jtreg/ProblemList-Xcomp.txt b/test/hotspot/jtreg/ProblemList-Xcomp.txt
    index c6443fd3f932..c2a7a4367e99 100644
    --- a/test/hotspot/jtreg/ProblemList-Xcomp.txt
    +++ b/test/hotspot/jtreg/ProblemList-Xcomp.txt
    @@ -31,7 +31,8 @@ vmTestbase/nsk/jvmti/scenarios/sampling/SP07/sp07t002/TestDescription.java 82456
     
     vmTestbase/vm/mlvm/mixed/stress/regression/b6969574/INDIFY_Test.java 8265295 linux-x64,windows-x64
     
    -serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java 8303168 linux-all
    +serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java#platform 8303168 linux-all
    +serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java#virtual 8303168 linux-all
     
     vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manyDiff_a/TestDescription.java 8308367 generic-all
     vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manySame_a/TestDescription.java 8308367 generic-all
    diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt
    index 08f33216658d..ad66e0e20dd3 100644
    --- a/test/hotspot/jtreg/ProblemList.txt
    +++ b/test/hotspot/jtreg/ProblemList.txt
    @@ -70,7 +70,8 @@ compiler/c2/aarch64/TestStaticCallStub.java 8359963 generic-aarch64
     compiler/escapeAnalysis/TestBCEscapeAnalyzerOverflow.java 8387392 windows-aarch64
     
     compiler/igvn/TestIncorrectDeadPathTypeNode.java 8392354 generic-all
    -compiler/rangechecks/TestFoldComparesFuzzer.java 8396524 generic-all
    +
    +compiler/c1/TestMemoryEffects.java 8397213 generic-aarch64
     
     #############################################################################
     
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java b/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java
    new file mode 100644
    index 000000000000..4d0e6d471e62
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java
    @@ -0,0 +1,604 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @bug 8391181
    + * @summary Tests that memory state is killed appropriately while parsing.
    + * @library /test/lib /
    + * @modules java.base/jdk.internal.misc
    + * @requires vm.compiler1.enabled & vm.flagless
    + * @build jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ${test.main.class}
    + */
    +
    +package compiler.c1;
    +
    +import java.util.Set;
    +import jdk.internal.misc.Unsafe;
    +
    +import compiler.lib.ir_framework.*;
    +import jdk.test.lib.Asserts;
    +import jdk.test.whitebox.WhiteBox;
    +
    +public class TestMemoryEffects {
    +    private static final Unsafe UNSAFE = Unsafe.getUnsafe();
    +    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
    +
    +    public static void main(String[] args) {
    +        TestFramework tf = new TestFramework();
    +        tf.setDefaultWarmup(0); // All tests need -Xcomp.
    +        tf.addFlags("--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED");
    +        tf.addCrossProductScenarios(Set.of("", "--enable-preview", "-XX:+IgnoreUnrecognizedVMOptions -XX:+StressLoopInvariantCodeMotion"));
    +        tf.start();
    +    }
    +
    +    // Getstatic and putstatic tests
    +    static class Victim {
    +        int field;
    +    }
    +    public static final Victim VICTIM = new Victim();
    +
    +    @Run(test = { "testGetstatic", "testPutstatic" })
    +    static void runGetPutStatic(RunInfo info) {
    +        info.getTestNames()
    +            .stream()
    +            .forEach((String testName) -> {
    +            Integer res = 0;
    +            try {
    +                res = (Integer)info.getTest(testName).invoke(null);
    +            } catch (Exception e) { /* make javac happy */ }
    +            Asserts.assertEQ(42, res, "wrong result for " + testName + ":");
    +        });
    +    }
    +
    +    @Test(compLevel = CompLevel.C1_SIMPLE)
    +    static int testGetstatic() {
    +        VICTIM.field = 666;
    +        int result = SideEffectingGetstatic.bait; // Triggers (*) by loading the class.
    +        result += VICTIM.field;
    +        return result;
    +    }
    +
    +    @Test(compLevel = CompLevel.C1_SIMPLE)
    +    static int testPutstatic() {
    +        VICTIM.field = 1234;
    +        SideEffectingPutstatic.bait = 0xabc; // Triggers (**) by loading the class.
    +        return VICTIM.field;
    +    }
    +
    +    // Volatile load test
    +    static class BoxWithVolatiles {
    +        int value;
    +        volatile int sync;
    +        volatile boolean start;
    +        volatile boolean stop;
    +    }
    +
    +    static record VolatileTestResults(int before, int after, int value, int sink) {}
    +
    +    @Run(test = { "testVolatileLoad", "testUnsafeVolatileLoad" })
    +    static void runVolatileLoad(RunInfo info) {
    +        info.getTestNames()
    +            .stream()
    +            .forEach((String testName) -> {
    +            BoxWithVolatiles box = new BoxWithVolatiles();
    +            Thread writer = new Thread(() -> {
    +                int counter = 1;
    +                box.start = true;
    +                while (!box.stop) {
    +                    box.value = 42;
    +                    // Make the non-volatile write above visible with a release-acquire handshake by
    +                    // writing and reading the same volatile field.
    +                    box.sync = counter++;
    +                }
    +            });
    +
    +            writer.start();
    +            while (!box.start) {
    +                Thread.onSpinWait();
    +            }
    +
    +            try {
    +                for (int attempts = 1; attempts <= 500; attempts++) {
    +                    VolatileTestResults results = null;
    +                    try {
    +                        results = (VolatileTestResults)info.getTest(testName).invoke(null, box, 0xcafe);
    +                    } catch (Exception e) { /* make javac happy */ }
    +                    // The release-acquire handshake worked if before and after are not the same.
    +                    if (results.before != results.after) {
    +                        box.stop = true;
    +                        writer.join();
    +                        Asserts.assertEQ(42, results.value, "wrong execution for testVolatileLoad:");
    +                        // If we reach here, the test has passed.
    +                        return;
    +                    }
    +                }
    +                box.stop = true;
    +                writer.join();
    +            } catch (InterruptedException e) { /* make javac happy */ }
    +            throw new RuntimeException("The handshake for testVolatileLoad did not work.");
    +        });
    +    }
    +
    +    @Test(compLevel = CompLevel.C1_SIMPLE)
    +    static VolatileTestResults testVolatileLoad(BoxWithVolatiles box, int delay) {
    +        box.value = 0; // Establish fact in C1 MemoryBuffer.
    +        // The test depends on the write above not getting reordered below the read below. C1 emits instructions
    +        // inside a block in source order, so this works. C2, however, moves anything not nailed down, which is
    +        // why this test is flagless and only run on C1.
    +        int before = box.sync; // This volatile read must kill the memory state.
    +
    +        // This test method must be a single block as C1 kills its memory state at every block boundary.
    +        // To make the write of the writer thread visible, we delay with a number of dependent computations.
    +        delay = delay * 1461234786 + 1;
    +        delay = delay / 234 + 1;
    +        delay = delay * 1461234786 + 2;
    +        delay = delay / 234 + 2;
    +        delay = delay * 1461234786 + 3;
    +        delay = delay / 234 + 3;
    +        delay = delay * 1461234786 + 4;
    +        delay = delay / 234 + 4;
    +        delay = delay * 1461234786 + 5;
    +        delay = delay / 234 + 5;
    +        delay = delay * 1461234786 + 6;
    +        delay = delay / 234 + 6;
    +        delay = delay * 1461234786 + 7;
    +        delay = delay / 234 + 7;
    +        delay = delay * 1461234786 + 8;
    +        delay = delay / 234 + 8;
    +        delay = delay * 1461234786 + 9;
    +        delay = delay / 234 + 9;
    +        delay = delay * 1461234786 + 10;
    +        delay = delay / 234 + 10;
    +        delay = delay * 1461234786 + 11;
    +        delay = delay / 234 + 11;
    +        delay = delay * 1461234786 + 12;
    +        delay = delay / 234 + 12;
    +        delay = delay * 1461234786 + 13;
    +        delay = delay / 234 + 13;
    +        delay = delay * 1461234786 + 14;
    +        delay = delay / 234 + 14;
    +        delay = delay * 1461234786 + 15;
    +        delay = delay / 234 + 15;
    +        delay = delay * 1461234786 + 16;
    +        delay = delay / 234 + 16;
    +        delay = delay * 1461234786 + 17;
    +        delay = delay / 234 + 17;
    +        delay = delay * 1461234786 + 18;
    +        delay = delay / 234 + 18;
    +        delay = delay * 1461234786 + 19;
    +        delay = delay / 234 + 19;
    +        delay = delay * 1461234786 + 20;
    +        delay = delay / 234 + 20;
    +        delay = delay * 1461234786 + 21;
    +        delay = delay / 234 + 21;
    +        delay = delay * 1461234786 + 22;
    +        delay = delay / 234 + 22;
    +        delay = delay * 1461234786 + 23;
    +        delay = delay / 234 + 23;
    +        delay = delay * 1461234786 + 24;
    +        delay = delay / 234 + 24;
    +        delay = delay * 1461234786 + 25;
    +        delay = delay / 234 + 25;
    +        delay = delay * 1461234786 + 26;
    +        delay = delay / 234 + 26;
    +        delay = delay * 1461234786 + 27;
    +        delay = delay / 234 + 27;
    +        delay = delay * 1461234786 + 28;
    +        delay = delay / 234 + 28;
    +        delay = delay * 1461234786 + 29;
    +        delay = delay / 234 + 29;
    +        delay = delay * 1461234786 + 30;
    +        delay = delay / 234 + 30;
    +        delay = delay * 1461234786 + 31;
    +        delay = delay / 234 + 31;
    +        delay = delay * 1461234786 + 32;
    +        delay = delay / 234 + 32;
    +        delay = delay * 1461234786 + 33;
    +        delay = delay / 234 + 33;
    +        delay = delay * 1461234786 + 34;
    +        delay = delay / 234 + 34;
    +        delay = delay * 1461234786 + 35;
    +        delay = delay / 234 + 35;
    +        delay = delay * 1461234786 + 36;
    +        delay = delay / 234 + 36;
    +        delay = delay * 1461234786 + 37;
    +        delay = delay / 234 + 37;
    +        delay = delay * 1461234786 + 38;
    +        delay = delay / 234 + 38;
    +        delay = delay * 1461234786 + 39;
    +        delay = delay / 234 + 39;
    +        delay = delay * 1461234786 + 40;
    +        delay = delay / 234 + 40;
    +        delay = delay * 1461234786 + 41;
    +        delay = delay / 234 + 41;
    +        delay = delay * 1461234786 + 42;
    +        delay = delay / 234 + 42;
    +        delay = delay * 1461234786 + 43;
    +        delay = delay / 234 + 43;
    +        delay = delay * 1461234786 + 44;
    +        delay = delay / 234 + 44;
    +        delay = delay * 1461234786 + 45;
    +        delay = delay / 234 + 45;
    +        delay = delay * 1461234786 + 46;
    +        delay = delay / 234 + 46;
    +        delay = delay * 1461234786 + 47;
    +        delay = delay / 234 + 47;
    +        delay = delay * 1461234786 + 48;
    +        delay = delay / 234 + 48;
    +        delay = delay * 1461234786 + 49;
    +        delay = delay / 234 + 49;
    +        delay = delay * 1461234786 + 50;
    +        delay = delay / 234 + 50;
    +        delay = delay * 1461234786 + 51;
    +        delay = delay / 234 + 51;
    +        delay = delay * 1461234786 + 52;
    +        delay = delay / 234 + 52;
    +        delay = delay * 1461234786 + 53;
    +        delay = delay / 234 + 53;
    +        delay = delay * 1461234786 + 54;
    +        delay = delay / 234 + 54;
    +        delay = delay * 1461234786 + 55;
    +        delay = delay / 234 + 55;
    +        delay = delay * 1461234786 + 56;
    +        delay = delay / 234 + 56;
    +        delay = delay * 1461234786 + 57;
    +        delay = delay / 234 + 57;
    +        delay = delay * 1461234786 + 58;
    +        delay = delay / 234 + 58;
    +        delay = delay * 1461234786 + 59;
    +        delay = delay / 234 + 59;
    +        delay = delay * 1461234786 + 60;
    +        delay = delay / 234 + 60;
    +        delay = delay * 1461234786 + 61;
    +        delay = delay / 234 + 61;
    +        delay = delay * 1461234786 + 62;
    +        delay = delay / 234 + 62;
    +        delay = delay * 1461234786 + 63;
    +        delay = delay / 234 + 63;
    +        delay = delay * 1461234786 + 64;
    +        delay = delay / 234 + 64;
    +        delay = delay * 1461234786 + 65;
    +        delay = delay / 234 + 65;
    +        delay = delay * 1461234786 + 66;
    +        delay = delay / 234 + 66;
    +        delay = delay * 1461234786 + 67;
    +        delay = delay / 234 + 67;
    +        delay = delay * 1461234786 + 68;
    +        delay = delay / 234 + 68;
    +        delay = delay * 1461234786 + 69;
    +        delay = delay / 234 + 69;
    +        delay = delay * 1461234786 + 70;
    +        delay = delay / 234 + 70;
    +        delay = delay * 1461234786 + 71;
    +        delay = delay / 234 + 71;
    +        delay = delay * 1461234786 + 72;
    +        delay = delay / 234 + 72;
    +        delay = delay * 1461234786 + 73;
    +        delay = delay / 234 + 73;
    +        delay = delay * 1461234786 + 74;
    +        delay = delay / 234 + 74;
    +        delay = delay * 1461234786 + 75;
    +        delay = delay / 234 + 75;
    +        delay = delay * 1461234786 + 76;
    +        delay = delay / 234 + 76;
    +        delay = delay * 1461234786 + 77;
    +        delay = delay / 234 + 77;
    +        delay = delay * 1461234786 + 78;
    +        delay = delay / 234 + 78;
    +        delay = delay * 1461234786 + 79;
    +        delay = delay / 234 + 79;
    +        delay = delay * 1461234786 + 80;
    +        delay = delay / 234 + 80;
    +        delay = delay * 1461234786 + 81;
    +        delay = delay / 234 + 81;
    +        delay = delay * 1461234786 + 82;
    +        delay = delay / 234 + 82;
    +        delay = delay * 1461234786 + 83;
    +        delay = delay / 234 + 83;
    +        delay = delay * 1461234786 + 84;
    +        delay = delay / 234 + 84;
    +        delay = delay * 1461234786 + 85;
    +        delay = delay / 234 + 85;
    +        delay = delay * 1461234786 + 86;
    +        delay = delay / 234 + 86;
    +        delay = delay * 1461234786 + 87;
    +        delay = delay / 234 + 87;
    +        delay = delay * 1461234786 + 88;
    +        delay = delay / 234 + 88;
    +        delay = delay * 1461234786 + 89;
    +        delay = delay / 234 + 89;
    +        delay = delay * 1461234786 + 90;
    +        delay = delay / 234 + 90;
    +        delay = delay * 1461234786 + 91;
    +        delay = delay / 234 + 91;
    +        delay = delay * 1461234786 + 92;
    +        delay = delay / 234 + 92;
    +        delay = delay * 1461234786 + 93;
    +        delay = delay / 234 + 93;
    +        delay = delay * 1461234786 + 94;
    +        delay = delay / 234 + 94;
    +        delay = delay * 1461234786 + 95;
    +        delay = delay / 234 + 95;
    +        delay = delay * 1461234786 + 96;
    +        delay = delay / 234 + 96;
    +        delay = delay * 1461234786 + 97;
    +        delay = delay / 234 + 97;
    +        delay = delay * 1461234786 + 98;
    +        delay = delay / 234 + 98;
    +        delay = delay * 1461234786 + 99;
    +        delay = delay / 234 + 99;
    +        delay = delay * 1461234786 + 100;
    +        delay = delay / 234 + 100;
    +        // Enough dilly-dallying, let's get down to business.
    +
    +        // The following volatile load, which has acquire semantics, must make the write to box.value
    +        // from the writer thread visible.
    +        int after = box.sync;
    +        // If C1 does not kill the memory state for volatile loads, this might be folded to 0 due to
    +        // the first line of this test.
    +        int result = box.value;
    +
    +        return new VolatileTestResults(before, after, result, delay);
    +    }
    +
    +    @Test(compLevel = CompLevel.C1_SIMPLE)
    +    static VolatileTestResults testUnsafeVolatileLoad(BoxWithVolatiles box, int delay) throws NoSuchFieldException {
    +        long syncOffset = UNSAFE.objectFieldOffset(BoxWithVolatiles.class.getDeclaredField("sync"));
    +
    +        box.value = 0; // Establish fact in C1 MemoryBuffer.
    +        // The test depends on the write above not getting reordered below the read below. C1 emits instructions
    +        // inside a block in source order, so this works. C2, however, moves anything not nailed down, which is
    +        // why this test is flagless and only run on C1.
    +        int before = UNSAFE.getIntVolatile(box, syncOffset); // This volatile read must kill the memory state.
    +
    +        // This test method must be a single block as C1 kills its memory state at every block boundary.
    +        // To make the write of the writer thread visible, we delay with a number of dependent computations.
    +        delay = delay * 1461234786 + 1;
    +        delay = delay / 234 + 1;
    +        delay = delay * 1461234786 + 2;
    +        delay = delay / 234 + 2;
    +        delay = delay * 1461234786 + 3;
    +        delay = delay / 234 + 3;
    +        delay = delay * 1461234786 + 4;
    +        delay = delay / 234 + 4;
    +        delay = delay * 1461234786 + 5;
    +        delay = delay / 234 + 5;
    +        delay = delay * 1461234786 + 6;
    +        delay = delay / 234 + 6;
    +        delay = delay * 1461234786 + 7;
    +        delay = delay / 234 + 7;
    +        delay = delay * 1461234786 + 8;
    +        delay = delay / 234 + 8;
    +        delay = delay * 1461234786 + 9;
    +        delay = delay / 234 + 9;
    +        delay = delay * 1461234786 + 10;
    +        delay = delay / 234 + 10;
    +        delay = delay * 1461234786 + 11;
    +        delay = delay / 234 + 11;
    +        delay = delay * 1461234786 + 12;
    +        delay = delay / 234 + 12;
    +        delay = delay * 1461234786 + 13;
    +        delay = delay / 234 + 13;
    +        delay = delay * 1461234786 + 14;
    +        delay = delay / 234 + 14;
    +        delay = delay * 1461234786 + 15;
    +        delay = delay / 234 + 15;
    +        delay = delay * 1461234786 + 16;
    +        delay = delay / 234 + 16;
    +        delay = delay * 1461234786 + 17;
    +        delay = delay / 234 + 17;
    +        delay = delay * 1461234786 + 18;
    +        delay = delay / 234 + 18;
    +        delay = delay * 1461234786 + 19;
    +        delay = delay / 234 + 19;
    +        delay = delay * 1461234786 + 20;
    +        delay = delay / 234 + 20;
    +        delay = delay * 1461234786 + 21;
    +        delay = delay / 234 + 21;
    +        delay = delay * 1461234786 + 22;
    +        delay = delay / 234 + 22;
    +        delay = delay * 1461234786 + 23;
    +        delay = delay / 234 + 23;
    +        delay = delay * 1461234786 + 24;
    +        delay = delay / 234 + 24;
    +        delay = delay * 1461234786 + 25;
    +        delay = delay / 234 + 25;
    +        delay = delay * 1461234786 + 26;
    +        delay = delay / 234 + 26;
    +        delay = delay * 1461234786 + 27;
    +        delay = delay / 234 + 27;
    +        delay = delay * 1461234786 + 28;
    +        delay = delay / 234 + 28;
    +        delay = delay * 1461234786 + 29;
    +        delay = delay / 234 + 29;
    +        delay = delay * 1461234786 + 30;
    +        delay = delay / 234 + 30;
    +        delay = delay * 1461234786 + 31;
    +        delay = delay / 234 + 31;
    +        delay = delay * 1461234786 + 32;
    +        delay = delay / 234 + 32;
    +        delay = delay * 1461234786 + 33;
    +        delay = delay / 234 + 33;
    +        delay = delay * 1461234786 + 34;
    +        delay = delay / 234 + 34;
    +        delay = delay * 1461234786 + 35;
    +        delay = delay / 234 + 35;
    +        delay = delay * 1461234786 + 36;
    +        delay = delay / 234 + 36;
    +        delay = delay * 1461234786 + 37;
    +        delay = delay / 234 + 37;
    +        delay = delay * 1461234786 + 38;
    +        delay = delay / 234 + 38;
    +        delay = delay * 1461234786 + 39;
    +        delay = delay / 234 + 39;
    +        delay = delay * 1461234786 + 40;
    +        delay = delay / 234 + 40;
    +        delay = delay * 1461234786 + 41;
    +        delay = delay / 234 + 41;
    +        delay = delay * 1461234786 + 42;
    +        delay = delay / 234 + 42;
    +        delay = delay * 1461234786 + 43;
    +        delay = delay / 234 + 43;
    +        delay = delay * 1461234786 + 44;
    +        delay = delay / 234 + 44;
    +        delay = delay * 1461234786 + 45;
    +        delay = delay / 234 + 45;
    +        delay = delay * 1461234786 + 46;
    +        delay = delay / 234 + 46;
    +        delay = delay * 1461234786 + 47;
    +        delay = delay / 234 + 47;
    +        delay = delay * 1461234786 + 48;
    +        delay = delay / 234 + 48;
    +        delay = delay * 1461234786 + 49;
    +        delay = delay / 234 + 49;
    +        delay = delay * 1461234786 + 50;
    +        delay = delay / 234 + 50;
    +        delay = delay * 1461234786 + 51;
    +        delay = delay / 234 + 51;
    +        delay = delay * 1461234786 + 52;
    +        delay = delay / 234 + 52;
    +        delay = delay * 1461234786 + 53;
    +        delay = delay / 234 + 53;
    +        delay = delay * 1461234786 + 54;
    +        delay = delay / 234 + 54;
    +        delay = delay * 1461234786 + 55;
    +        delay = delay / 234 + 55;
    +        delay = delay * 1461234786 + 56;
    +        delay = delay / 234 + 56;
    +        delay = delay * 1461234786 + 57;
    +        delay = delay / 234 + 57;
    +        delay = delay * 1461234786 + 58;
    +        delay = delay / 234 + 58;
    +        delay = delay * 1461234786 + 59;
    +        delay = delay / 234 + 59;
    +        delay = delay * 1461234786 + 60;
    +        delay = delay / 234 + 60;
    +        delay = delay * 1461234786 + 61;
    +        delay = delay / 234 + 61;
    +        delay = delay * 1461234786 + 62;
    +        delay = delay / 234 + 62;
    +        delay = delay * 1461234786 + 63;
    +        delay = delay / 234 + 63;
    +        delay = delay * 1461234786 + 64;
    +        delay = delay / 234 + 64;
    +        delay = delay * 1461234786 + 65;
    +        delay = delay / 234 + 65;
    +        delay = delay * 1461234786 + 66;
    +        delay = delay / 234 + 66;
    +        delay = delay * 1461234786 + 67;
    +        delay = delay / 234 + 67;
    +        delay = delay * 1461234786 + 68;
    +        delay = delay / 234 + 68;
    +        delay = delay * 1461234786 + 69;
    +        delay = delay / 234 + 69;
    +        delay = delay * 1461234786 + 70;
    +        delay = delay / 234 + 70;
    +        delay = delay * 1461234786 + 71;
    +        delay = delay / 234 + 71;
    +        delay = delay * 1461234786 + 72;
    +        delay = delay / 234 + 72;
    +        delay = delay * 1461234786 + 73;
    +        delay = delay / 234 + 73;
    +        delay = delay * 1461234786 + 74;
    +        delay = delay / 234 + 74;
    +        delay = delay * 1461234786 + 75;
    +        delay = delay / 234 + 75;
    +        delay = delay * 1461234786 + 76;
    +        delay = delay / 234 + 76;
    +        delay = delay * 1461234786 + 77;
    +        delay = delay / 234 + 77;
    +        delay = delay * 1461234786 + 78;
    +        delay = delay / 234 + 78;
    +        delay = delay * 1461234786 + 79;
    +        delay = delay / 234 + 79;
    +        delay = delay * 1461234786 + 80;
    +        delay = delay / 234 + 80;
    +        delay = delay * 1461234786 + 81;
    +        delay = delay / 234 + 81;
    +        delay = delay * 1461234786 + 82;
    +        delay = delay / 234 + 82;
    +        delay = delay * 1461234786 + 83;
    +        delay = delay / 234 + 83;
    +        delay = delay * 1461234786 + 84;
    +        delay = delay / 234 + 84;
    +        delay = delay * 1461234786 + 85;
    +        delay = delay / 234 + 85;
    +        delay = delay * 1461234786 + 86;
    +        delay = delay / 234 + 86;
    +        delay = delay * 1461234786 + 87;
    +        delay = delay / 234 + 87;
    +        delay = delay * 1461234786 + 88;
    +        delay = delay / 234 + 88;
    +        delay = delay * 1461234786 + 89;
    +        delay = delay / 234 + 89;
    +        delay = delay * 1461234786 + 90;
    +        delay = delay / 234 + 90;
    +        delay = delay * 1461234786 + 91;
    +        delay = delay / 234 + 91;
    +        delay = delay * 1461234786 + 92;
    +        delay = delay / 234 + 92;
    +        delay = delay * 1461234786 + 93;
    +        delay = delay / 234 + 93;
    +        delay = delay * 1461234786 + 94;
    +        delay = delay / 234 + 94;
    +        delay = delay * 1461234786 + 95;
    +        delay = delay / 234 + 95;
    +        delay = delay * 1461234786 + 96;
    +        delay = delay / 234 + 96;
    +        delay = delay * 1461234786 + 97;
    +        delay = delay / 234 + 97;
    +        delay = delay * 1461234786 + 98;
    +        delay = delay / 234 + 98;
    +        delay = delay * 1461234786 + 99;
    +        delay = delay / 234 + 99;
    +        delay = delay * 1461234786 + 100;
    +        delay = delay / 234 + 100;
    +        // Enough dilly-dallying, let's get down to business.
    +
    +        // The following volatile load, which has acquire semantics, must make the write to box.value
    +        // from the writer thread visible.
    +        int after = UNSAFE.getIntVolatile(box, syncOffset);
    +        // If C1 does not kill the memory state for volatile loads, this might be folded to 0 due to
    +        // the first line of this test.
    +        int result = box.value;
    +
    +        return new VolatileTestResults(before, after, result, delay);
    +    }
    +}
    +
    +class SideEffectingGetstatic {
    +    public static int bait = 0xcafe;
    +    static {
    +        TestMemoryEffects.VICTIM.field = 42 - SideEffectingGetstatic.bait; // (*)
    +    }
    +}
    +
    +class SideEffectingPutstatic {
    +    public static int bait = 0xbaba;
    +    static {
    +        TestMemoryEffects.VICTIM.field = 42; // (**)
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsClassLoading.java b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsClassLoading.java
    new file mode 100644
    index 000000000000..a0844c323d93
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsClassLoading.java
    @@ -0,0 +1,166 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test id=c1
    + * @bug 8391181 8397423
    + * @summary Tests that memory state is killed appropriately for class loaders that might have side-effects.
    + * @requires vm.compiler1.enabled
    + * @library /test/lib
    + * @run main/othervm -Xcomp -XX:TieredStopAtLevel=1
    + *                   -XX:CompileCommand=compileonly,${test.main.class}$Test*::test
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=c2
    + * @bug 8391181 8397423
    + * @summary Tests that memory state is killed appropriately for class loaders that might have side-effects.
    + * @requires vm.compiler2.enabled
    + * @library /test/lib
    + * @run main/othervm -Xcomp -XX:-TieredCompilation
    + *                   -XX:CompileCommand=compileonly,${test.main.class}$Test*::test
    + *                   ${test.main.class}
    + */
    +
    +package compiler.c1;
    +
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.util.List;
    +
    +import jdk.test.lib.Asserts;
    +
    +public class TestMemoryEffectsClassLoading {
    +    public static class Victim {
    +        public int field;
    +    }
    +    public static final Victim VICTIM = new Victim();
    +
    +    public static Object SOME_OBJECT_FOR_INSTANCEOF = new Object();
    +    public static Object SOME_OBJECT_FOR_CHECKCAST = new LoadTargetCheckCast();
    +    private static final String TEST_CLASS = "compiler.c1.TestMemoryEffectsClassLoading";
    +
    +    public static final void main(String[] args) throws Exception {
    +        final SideEffectingClassLoader loader = new SideEffectingClassLoader();
    +        var tests = List.of("TestClassConstant", "TestInstanceOf", "TestCheckCast", "TestObjectArray",
    +                            "TestMultiArray");
    +        for (final String className : tests) {
    +            final Class klass = Class.forName(TEST_CLASS + "$" + className, false, loader);
    +            int result = (int) klass.getMethod("test").invoke(null);
    +            Asserts.assertEQ(42, result, "Wrong result for " + className + ":");
    +        }
    +    }
    +
    +    public static class TestClassConstant {
    +        public static int test() {
    +            VICTIM.field = 0xcafe;
    +            Class unused = LoadTargetClassConstant.class;
    +            return VICTIM.field;
    +        }
    +    }
    +
    +    public static class TestInstanceOf {
    +        public static int test() {
    +            VICTIM.field = 0xdead;
    +            IO.println("before");
    +            boolean unused = SOME_OBJECT_FOR_INSTANCEOF instanceof LoadTargetInstanceOf;
    +            return VICTIM.field;
    +        }
    +    }
    +
    +    public static class TestCheckCast {
    +        public static int test() {
    +            VICTIM.field = 0xdead;
    +            Object unused = (LoadTargetCheckCast) SOME_OBJECT_FOR_CHECKCAST;
    +            return VICTIM.field;
    +        }
    +    }
    +
    +    public static class TestObjectArray {
    +        public static int test() {
    +            VICTIM.field = 0xbad;
    +            Object unused = new LoadTargetObjectArray[0];
    +            return VICTIM.field;
    +        }
    +    }
    +
    +    public static class TestMultiArray {
    +        public static int test() {
    +            VICTIM.field = 0xbad;
    +            Object _ = new LoadTargetMultiArray[0][0];
    +            return VICTIM.field;
    +        }
    +    }
    +
    +    // Classes that trigger the side effect when loaded with the custom class loader below.
    +    public static class LoadTargetClassConstant {}
    +    public static class LoadTargetInstanceOf {}
    +    public static class LoadTargetCheckCast {}
    +    public static class LoadTargetObjectArray {}
    +    public static class LoadTargetMultiArray {}
    +
    +    static class SideEffectingClassLoader extends ClassLoader {
    +        SideEffectingClassLoader() {
    +            super(TestMemoryEffectsClassLoading.class.getClassLoader());
    +        }
    +
    +        @Override
    +        protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
    +            // Load all Test* subclasses here so the target classes are loaded with this
    +            // loader. The rest is delegated to the system class loader.
    +            if (name.contains("$Test")) {
    +                Class klass = findLoadedClass(name);
    +                if (klass == null) {
    +                    klass = findClass(name);
    +                }
    +                if (resolve) {
    +                    resolveClass(klass);
    +                }
    +                return klass;
    +            }
    +
    +            // Side-effect only for the specific classes where we want to observe it.
    +            if (name.contains("$LoadTarget")) {
    +                VICTIM.field = 42;
    +                IO.println("side-effect in classloader");
    +            }
    +
    +            return super.loadClass(name, resolve);
    +        }
    +
    +        @Override
    +        protected Class findClass(String name) throws ClassNotFoundException {
    +            String resourceName = name.replace('.', '/') + ".class";
    +            try (InputStream in = getSystemResourceAsStream(resourceName)) {
    +                if (in == null) {
    +                    throw new ClassNotFoundException(name);
    +                }
    +                byte[] bytes = in.readAllBytes();
    +                return defineClass(name, bytes, 0, bytes.length);
    +            } catch (IOException e) {
    +                throw new ClassNotFoundException(name, e);
    +            }
    +        }
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.jasm b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.jasm
    new file mode 100644
    index 000000000000..2e0eb8fb5941
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.jasm
    @@ -0,0 +1,41 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +// Test method for TestMemoryEffectsCondy
    +public class compiler/c1/TestMemoryEffectsCondyGenerated version 55:0 {
    +    public static Method test:"()I" stack 2 locals 0 {
    +        // Write 0 to VICTIM.field from the Java file.
    +        getstatic Field compiler/c1/TestMemoryEffectsCondy.VICTIM:"Lcompiler/c1/TestMemoryEffectsCondy$Victim;";
    +        iconst_0;
    +        putfield Field compiler/c1/TestMemoryEffectsCondy$Victim.field:"I";
    +
    +        // Do a condy with a bootstrap method that has a side-effect.
    +        ldc Dynamic REF_invokeStatic:compiler/c1/TestMemoryEffectsCondy.bootstrap:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;":sideEffectingBootstrap:I;
    +        pop;
    +
    +        // Reload and return VICTIM.field to observe the side-effect.
    +        getstatic Field compiler/c1/TestMemoryEffectsCondy.VICTIM:"Lcompiler/c1/TestMemoryEffectsCondy$Victim;";
    +        getfield Field compiler/c1/TestMemoryEffectsCondy$Victim.field:"I";
    +        ireturn;
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.java b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.java
    new file mode 100644
    index 000000000000..0886d49f2b9d
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsCondy.java
    @@ -0,0 +1,71 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test id=c1
    + * @bug 8391181
    + * @summary Tests that memory state is killed appropriately for dynamic constants.
    + * @requires vm.compiler1.enabled
    + * @library /test/lib
    + * @compile TestMemoryEffectsCondy.jasm
    + * @run main/othervm -Xcomp -XX:TieredStopAtLevel=1
    + *                   -XX:CompileCommand=compileonly,${test.main.class}Generated::test
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=c2
    + * @bug 8391181
    + * @summary Tests that memory state is killed appropriately for dynamic constants.
    + * @requires vm.compiler2.enabled
    + * @library /test/lib
    + * @compile TestMemoryEffectsCondy.jasm
    + * @run main/othervm -Xcomp -XX:-TieredCompilation
    + *                   -XX:CompileCommand=compileonly,${test.main.class}Generated::test
    + *                   ${test.main.class}
    + */
    +
    +package compiler.c1;
    +
    +import java.lang.invoke.MethodHandles;
    +
    +import jdk.test.lib.Asserts;
    +
    +import compiler.c1.TestMemoryEffectsCondyGenerated;
    +
    +public class TestMemoryEffectsCondy {
    +    public static class Victim {
    +        public int field;
    +    }
    +    public static final Victim VICTIM = new Victim();
    +
    +    public static Object bootstrap(MethodHandles.Lookup lookup, String name, Class type) {
    +        VICTIM.field = 42; // side-effect
    +        return Integer.valueOf(0xcafe);
    +    }
    +
    +    public static final void main(String[] args) throws ReflectiveOperationException {
    +        int result = TestMemoryEffectsCondyGenerated.test();
    +        Asserts.assertEQ(42, result);
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.jasm b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.jasm
    new file mode 100644
    index 000000000000..63b761122df2
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.jasm
    @@ -0,0 +1,42 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +// Test method for TestMemoryEffectsNewInstance
    +public class compiler/c1/TestMemoryEffectsNewInstanceGenerated version 55:0 {
    +    public static Method test:"()I" stack 2 locals 0 {
    +        // Write 0 to VICTIM.value from the Java file.
    +        getstatic Field compiler/c1/TestMemoryEffectsNewInstance.VICTIM:"Lcompiler/c1/TestMemoryEffectsNewInstance$Victim;";
    +        iconst_0;
    +        putfield Field compiler/c1/TestMemoryEffectsNewInstance$Victim.value:"I";
    +
    +        // Call `new` on a class that side-effects in its static initializer and discard the object reference.
    +        // Since `new` does not fully initialze the new instance if we do not explicitly invoke the instance initializer.
    +        new class compiler/c1/TestMemoryEffectsNewInstance$Culprit;
    +        pop;
    +
    +        // Reload and return VICTIM.value to observe the sideffect.
    +        getstatic Field compiler/c1/TestMemoryEffectsNewInstance.VICTIM:"Lcompiler/c1/TestMemoryEffectsNewInstance$Victim;";
    +        getfield Field compiler/c1/TestMemoryEffectsNewInstance$Victim.value:"I";
    +        ireturn;
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.java b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.java
    new file mode 100644
    index 000000000000..db1bc1185d02
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffectsNewInstance.java
    @@ -0,0 +1,75 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test id=c1
    + * @bug 8391181
    + * @summary Tests that memory state is killed appropriately while parsing `new`.
    + * @requires vm.compiler1.enabled
    + * @library /test/lib
    + * @compile TestMemoryEffectsNewInstance.jasm
    + * @run main/othervm -Xcomp -XX:TieredStopAtLevel=1
    + *                   -XX:CompileCommand=compileonly,${test.main.class}Generated::test
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=c2
    + * @bug 8391181
    + * @summary Tests that memory state is killed appropriately while parsing `new`.
    + * @requires vm.compiler2.enabled
    + * @library /test/lib
    + * @compile TestMemoryEffectsNewInstance.jasm
    + * @run main/othervm -Xcomp -XX:-TieredCompilation
    + *                   -XX:CompileCommand=compileonly,${test.main.class}Generated::test
    + *                   ${test.main.class}
    + */
    +
    +package compiler.c1;
    +
    +import jdk.test.lib.Asserts;
    +
    +import compiler.c1.TestMemoryEffectsNewInstanceGenerated;
    +
    +public class TestMemoryEffectsNewInstance {
    +    public static class Victim {
    +        public int value;
    +    }
    +    public static final Victim VICTIM = new Victim();
    +
    +    static class Culprit {
    +        static {
    +            VICTIM.value = 42; // side-effect
    +        }
    +
    +        public Culprit() {
    +            throw new RuntimeException("Culprit. should not get invoked.");
    +        }
    +    }
    +
    +    public static final void main(String[] args) throws ReflectiveOperationException {
    +        //Class klass = Class.forName("compiler.c1.TestMemoryEffectsNewInstanceGenerated");
    +        int result = TestMemoryEffectsNewInstanceGenerated.test();//(int) klass.getMethod("test").invoke(null);
    +        Asserts.assertEQ(42, result);
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c2/TestDeadStoreToHeader.java b/test/hotspot/jtreg/compiler/c2/TestDeadStoreToHeader.java
    new file mode 100644
    index 000000000000..b8e96c34c56d
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/c2/TestDeadStoreToHeader.java
    @@ -0,0 +1,48 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +package compiler.c2;
    +
    +/*
    + * @test
    + * @bug 8391179
    + * @summary dead Store to header after loop optimizations
    + * @run main ${test.main.class}
    + * @run main/othervm -Xbatch -XX:CompileCommand=compileonly,${test.main.class}::test -XX:+IgnoreUnrecognizedVMOptions -XX:+StressLoopPeeling ${test.main.class}
    + */
    +
    +public class TestDeadStoreToHeader {
    +    public static void main(String[] args) {
    +        for (int i = 0; i < 100; i++) {
    +            test(123);
    +        }
    +    }
    +
    +    static String test(long l) {
    +        String s = "";
    +        for (int i = 0; i < 50_000; i++) {
    +            s = Long.toString(l);
    +        }
    +        return s;
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/c2/irTests/CmpUWithZero.java b/test/hotspot/jtreg/compiler/c2/irTests/CmpUWithZero.java
    index 303b0995394b..dee210b0a53a 100644
    --- a/test/hotspot/jtreg/compiler/c2/irTests/CmpUWithZero.java
    +++ b/test/hotspot/jtreg/compiler/c2/irTests/CmpUWithZero.java
    @@ -1,5 +1,6 @@
     /*
      * Copyright (c) 2022, 2023, Red Hat, Inc. All rights reserved.
    + * Copyright (c) 2026, Alibaba Group Holding Limited. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -24,6 +25,7 @@
     package compiler.c2.irTests;
     
     import compiler.lib.ir_framework.*;
    +import jdk.test.lib.Asserts;
     
     /*
      * @test
    @@ -59,4 +61,39 @@ private void testRunner() {
             test(42);
         }
     
    +    @Test
    +    @IR(counts = { IRNode.CMP_L, "1" }, failOn = { IRNode.CMP_UL })
    +    public static boolean testLongLT(long x) {
    +        return Long.compareUnsigned(x, 1) < 0;
    +    }
    +
    +    @Test
    +    @IR(counts = { IRNode.CMP_L, "1" }, failOn = { IRNode.CMP_UL })
    +    public static boolean testLongLE(long x) {
    +        return Long.compareUnsigned(x, 0) <= 0;
    +    }
    +
    +    @Test
    +    @IR(counts = { IRNode.CMP_L, "1" }, failOn = { IRNode.CMP_UL })
    +    public static boolean testLongGT(long x) {
    +        return Long.compareUnsigned(x, 0) > 0;
    +    }
    +
    +    @Test
    +    @IR(counts = { IRNode.CMP_L, "1" }, failOn = { IRNode.CMP_UL })
    +    public static boolean testLongGE(long x) {
    +        return Long.compareUnsigned(x, 1) >= 0;
    +    }
    +
    +    @Run(test = { "testLongLT", "testLongLE", "testLongGT", "testLongGE" })
    +    @Warmup(0)
    +    public static void testLongRunner() {
    +        for (long x : new long[] { Long.MIN_VALUE, -1, 0, 1, 2, 1L << 32, Long.MAX_VALUE }) {
    +            Asserts.assertEQ(testLongLT(x), x == 0);
    +            Asserts.assertEQ(testLongLE(x), x == 0);
    +            Asserts.assertEQ(testLongGT(x), x != 0);
    +            Asserts.assertEQ(testLongGE(x), x != 0);
    +        }
    +    }
    +
     }
    diff --git a/test/hotspot/jtreg/compiler/c2/irTests/TestArrLenCheckOptimization.java b/test/hotspot/jtreg/compiler/c2/irTests/TestArrLenCheckOptimization.java
    index cb955bf14e7c..823513c71372 100644
    --- a/test/hotspot/jtreg/compiler/c2/irTests/TestArrLenCheckOptimization.java
    +++ b/test/hotspot/jtreg/compiler/c2/irTests/TestArrLenCheckOptimization.java
    @@ -56,7 +56,7 @@ void test_gt_int(int ia[]) {
         }
     
         @Test
    -    @IR(counts = {IRNode.CBZ_LS, "1"})
    +    @IR(counts = {IRNode.CBZW_LS, "1"})
         void test_le_long(int ia[]) {
             if (Long.compareUnsigned(ia.length, 0) > 0) {
                 result += 0x80;
    @@ -66,7 +66,7 @@ void test_le_long(int ia[]) {
         }
     
         @Test
    -    @IR(counts = {IRNode.CBZ_HI, "1"})
    +    @IR(counts = {IRNode.CBNZW_HI, "1"})
         void test_gt_long(int ia[]) {
             if (Long.compareUnsigned(ia.length, 0) > 0) {
                 result += 0x82;
    diff --git a/test/hotspot/jtreg/compiler/c2/irTests/scalarReplacement/AllocationMergesTests.java b/test/hotspot/jtreg/compiler/c2/irTests/scalarReplacement/AllocationMergesTests.java
    index 8f24cb46e205..3504c726f24f 100644
    --- a/test/hotspot/jtreg/compiler/c2/irTests/scalarReplacement/AllocationMergesTests.java
    +++ b/test/hotspot/jtreg/compiler/c2/irTests/scalarReplacement/AllocationMergesTests.java
    @@ -799,11 +799,7 @@ int testNestedObjectsNoEscapeObject(boolean cond, int x, int y) {
         }
     
         @Test
    -    @IR(counts = { IRNode.ALLOC, "2" }, applyIf = {"UseCompressedOops", "true"} )
    -    @IR(failOn = { IRNode.ALLOC }, applyIf = {"UseCompressedOops", "false"} )
    -    // The two Picture objects will be removed. The nested Point objects won't
    -    // be removed, if CompressedOops is enabled, because the Phi merging them will
    -    // have a DecodeN user - which currently isn't supported.
    +    @IR(failOn = { IRNode.ALLOC })
         int testNestedObjectsNoEscapeObject_C2(boolean cond, int x, int y) { return testNestedObjectsNoEscapeObject(cond, x, y); }
     
         @DontCompile
    diff --git a/test/hotspot/jtreg/compiler/gcbarriers/TestG1BarrierCapturedStoreLSpecial.java b/test/hotspot/jtreg/compiler/gcbarriers/TestG1BarrierCapturedStoreLSpecial.java
    new file mode 100644
    index 000000000000..372e41426343
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/gcbarriers/TestG1BarrierCapturedStoreLSpecial.java
    @@ -0,0 +1,522 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @bug 8387705
    + * @summary Test that G1 barriers for StoreLSpecial are generated and optimized as expected
    + * @enablePreview
    + * @modules java.base/jdk.internal.value
    + *          java.base/jdk.internal.vm.annotation
    + * @library /test/lib /
    + * @requires vm.gc.G1 & vm.bits == 64
    + * @run driver ${test.main.class}
    + */
    +
    +package compiler.gcbarriers;
    +
    +import compiler.lib.ir_framework.*;
    +import static compiler.lib.ir_framework.IRNode.*;
    +import jdk.internal.vm.annotation.NullRestricted;
    +import jdk.test.lib.Asserts;
    +
    +public class TestG1BarrierCapturedStoreLSpecial {
    +    static final String PRE_ONLY = "pre";
    +    static final String PRE_AND_POST = "pre post";
    +    static final String PRE_AND_POST_NOT_NULL = "pre post notnull";
    +    static final String POST_ONLY = "post";
    +    static final String POST_NOT_NULL_ONLY = "post notnull";
    +    static final String ANY = ".*";
    +
    +    public static void main(String[] args) {
    +        TestFramework framework = new TestFramework();
    +        Scenario[] scenarios = new Scenario[2 * 2];
    +        int scenarioIndex = 0;
    +        for (int i = 0; i < 2; i++) {
    +            for (int j = 0; j < 2; j++) {
    +                scenarios[scenarioIndex] =
    +                        new Scenario(scenarioIndex,
    +                                "--enable-preview",
    +                                "-XX:" + (i == 0 ? "-" : "+") + "UseCompressedOops",
    +                                "-XX:" + (j == 0 ? "-" : "+") + "ReduceInitialCardMarks"
    +                        );
    +                scenarioIndex++;
    +            }
    +        }
    +        framework.addScenarios(scenarios)
    +                .addFlags(
    +                        "-XX:+UseG1GC",
    +                        "--add-exports", "java.base/jdk.internal.value=ALL-UNNAMED",
    +                        "--add-exports", "java.base/jdk.internal.vm.annotation=ALL-UNNAMED"
    +                )
    +                .start();
    +    }
    +
    +    static value class MyValue {
    +        Object value;
    +
    +        MyValue(Object value) {
    +            this.value = value;
    +        }
    +    }
    +
    +    static class Holder {
    +        Integer i = null;
    +        MyValue v = null;
    +    }
    +
    +    static value class MyValueWithTwoOops {
    +        Object v1;
    +        Object v2;
    +
    +        MyValueWithTwoOops(Object v1, Object v2) {
    +            this.v1 = v1;
    +            this.v2 = v2;
    +        }
    +    }
    +
    +    static class HolderWithTwoOops {
    +        @NullRestricted
    +        MyValueWithTwoOops v;
    +
    +        HolderWithTwoOops() {
    +            this.v = new MyValueWithTwoOops(null, null);
    +            super();
    +        }
    +        HolderWithTwoOops(MyValueWithTwoOops v) {
    +            this.v = v;
    +            super();
    +        }
    +    }
    +
    +    static abstract value class MyValueOopFirstBase {
    +        Object v;
    +
    +        MyValueOopFirstBase(Object v) {
    +            this.v = v;
    +        }
    +    }
    +    static value class MyValueOopFirst extends MyValueOopFirstBase {
    +        int i;
    +
    +        MyValueOopFirst(int i, Object v) {
    +            this.i = i;
    +            super(v);
    +        }
    +    }
    +    static class HolderWithOopsFirst {
    +        @NullRestricted
    +        MyValueOopFirst v;
    +
    +        HolderWithOopsFirst() {
    +            this.v = new MyValueOopFirst(0, null);
    +            super();
    +        }
    +        HolderWithOopsFirst(MyValueOopFirst v) {
    +            this.v = v;
    +            super();
    +        }
    +    }
    +
    +    static abstract value class MyValueOopSecondBase {
    +        int i;
    +
    +        MyValueOopSecondBase(int i) {
    +            this.i = i;
    +        }
    +    }
    +    static value class MyValueOopSecond extends MyValueOopSecondBase {
    +        Object v;
    +
    +        MyValueOopSecond(int i, Object v) {
    +            this.v = v;
    +            super(i);
    +        }
    +    }
    +    static class HolderWithOopsSecond {
    +        @NullRestricted
    +        MyValueOopSecond v;
    +
    +        HolderWithOopsSecond() {
    +            this.v = new MyValueOopSecond(0, null);
    +            super();
    +        }
    +        HolderWithOopsSecond(MyValueOopSecond v) {
    +            this.v = v;
    +            super();
    +        }
    +    }
    +
    +    // Assignment of value of unknown nullness, just after allocation
    +    // No barrier needed. Store could be captured.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "true"},
    +        counts = {G1_STORE_L_SPECIAL, "2"},  // Should be 1 with store capturing
    +        failOn = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "false"},
    +        counts = {G1_STORE_L_SPECIAL, "2",   // Should be 1 with store capturing
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY, "1",  // 1 with post only, one without barriers
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, POST_ONLY, "1"})
    +    static Holder test1(Integer i, MyValue v) {
    +        Holder t = new Holder();
    +        t.i = i;
    +        t.v = v;
    +        return t;
    +    }
    +
    +    @Run(test = {"test1"})
    +    public void test1_verifier() {
    +        MyValue v = new MyValue(new Object());
    +        Holder h = test1(42, v);
    +        Asserts.assertEQ(h.i, 42);
    +        Asserts.assertEQ(h.v, v);
    +    }
    +
    +    // Assignment of value of unknown nullness, in existing object.
    +    // Pre- and post-barrier needed.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static Holder test1_no_capture(Holder t, Integer i, MyValue v) {
    +        t.i = i;
    +        t.v = v;
    +        return t;
    +    }
    +
    +    @Run(test = {"test1_no_capture"})
    +    public void test1_no_capture_verifier() {
    +        MyValue v = new MyValue(new Object());
    +        Holder t = new Holder();
    +        Holder h = test1_no_capture(t, 42, v);
    +        Asserts.assertEQ(t.i, 42);
    +        Asserts.assertEQ(t.v, v);
    +        Asserts.assertEQ(t, h);
    +    }
    +
    +    // Similar to test1, but v is also freshly allocated, hence not-null.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "true"},
    +        counts = {G1_STORE_L_SPECIAL, "2"},  // Should be 1 with store capturing
    +        failOn = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "false"},
    +        counts = {G1_STORE_L_SPECIAL, "2",   // Should be 1 with store capturing
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY, "1",  // 1 with post not null only, one without barriers
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, POST_NOT_NULL_ONLY, "1"})
    +    static Holder test2(Integer i) {
    +        MyValue v = new MyValue(new Object());
    +        Holder t = new Holder();
    +        t.i = i;
    +        t.v = v;
    +        return t;
    +    }
    +
    +    @Run(test = {"test2"})
    +    public void test2_verifier() {
    +        Holder h = test2(42);
    +        Asserts.assertEQ(h.i, 42);
    +        Asserts.assertNE(h.v, null);
    +    }
    +
    +    // Similar to test1, but v is known to be null.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL, "2"},  // Should be 1 with store capturing
    +        failOn = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY})
    +    static Holder test3(Integer i) {
    +        Holder t = new Holder();
    +        t.i = i;
    +        t.v = null;
    +        return t;
    +    }
    +
    +    @Run(test = {"test3"})
    +    public void test3_verifier() {
    +        Holder h = test3(42);
    +        Asserts.assertEQ(h.i, 42);
    +        Asserts.assertEQ(h.v, null);
    +    }
    +
    +    // Similar to test2, v is still not-null at assignment point, but it is already allocated
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static HolderWithTwoOops test4(HolderWithTwoOops h, MyValueWithTwoOops v) {
    +        var _ = v.v1;  // Force v != null
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test4"})
    +    public void test4_verifier() {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(new Object(), new Object());
    +        HolderWithTwoOops h = new HolderWithTwoOops();
    +        HolderWithTwoOops h2 = test4(h, v);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertEQ(h.v, v);
    +    }
    +
    +    // Assign 2 oops in a single StoreLSpecial. Both are known to be not-null.
    +    // We can use a not-null post-barrier.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, PRE_AND_POST_NOT_NULL, "1"})
    +    static HolderWithTwoOops test5(HolderWithTwoOops h) {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(new Object(), new Object());
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test5"})
    +    public void test5_verifier() {
    +        HolderWithTwoOops h = new HolderWithTwoOops();
    +        HolderWithTwoOops h2 = test5(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertNE(h2.v.v1, null);
    +        Asserts.assertNE(h2.v.v2, null);
    +    }
    +
    +    // Assign 2 oops in a single StoreLSpecial. Only left is known to be not-null.
    +    // We cannot use a not-null post-barrier.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static HolderWithTwoOops test6(HolderWithTwoOops h) {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(new Object(), null);
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test6"})
    +    public void test6_verifier() {
    +        HolderWithTwoOops h = new HolderWithTwoOops();
    +        HolderWithTwoOops h2 = test6(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertNE(h2.v.v1, null);
    +        Asserts.assertEQ(h2.v.v2, null);
    +    }
    +
    +    // Similar to test6, but this time, only right is not-null.
    +    // We cannot use a not-null post-barrier.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static HolderWithTwoOops test7(HolderWithTwoOops h) {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(null, new Object());
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test7"})
    +    public void test7_verifier() {
    +        HolderWithTwoOops h = new HolderWithTwoOops();
    +        HolderWithTwoOops h2 = test7(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertEQ(h2.v.v1, null);
    +        Asserts.assertNE(h2.v.v2, null);
    +    }
    +
    +    // Assign 2 null in a single StoreLSpecial.
    +    // Not post barrier is needed.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, PRE_ONLY, "1"})
    +    static HolderWithTwoOops test8(HolderWithTwoOops h) {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(null, null);
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test8"})
    +    public void test8_verifier() {
    +        HolderWithTwoOops h = new HolderWithTwoOops();
    +        HolderWithTwoOops h2 = test8(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertEQ(h2.v.v1, null);
    +        Asserts.assertEQ(h2.v.v2, null);
    +    }
    +
    +    // Assign a single not-null oop at offset 0 with a StoreLSpecial. Not-null post-barrier does the trick.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_ONE_OOP_0_WITH_BARRIER_FLAG, PRE_AND_POST_NOT_NULL, "1"})
    +    static HolderWithOopsFirst test9_non_null(HolderWithOopsFirst h) {
    +        MyValueOopFirst v = new MyValueOopFirst(42, new Object());
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test9_non_null"})
    +    public void test9_non_null_verifier() {
    +        HolderWithOopsFirst h = new HolderWithOopsFirst();
    +        HolderWithOopsFirst h2 = test9_non_null(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertEQ(h2.v.i, 42);
    +        Asserts.assertNE(h2.v.v, null);
    +    }
    +
    +    // Assign a single null at offset 0 with a StoreLSpecial. No post-barrier needed.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_ONE_OOP_0_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static HolderWithOopsFirst test9_maybe_null(HolderWithOopsFirst h, Object o) {
    +        MyValueOopFirst v = new MyValueOopFirst(42, o);
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test9_maybe_null"})
    +    public void test9_maybe_null_verifier() {
    +        HolderWithOopsFirst h = new HolderWithOopsFirst();
    +        {
    +            HolderWithOopsFirst h2 = test9_maybe_null(h, null);
    +            Asserts.assertEQ(h2, h);
    +            Asserts.assertEQ(h2.v.i, 42);
    +            Asserts.assertEQ(h2.v.v, null);
    +        }
    +        {
    +            HolderWithOopsFirst h2 = test9_maybe_null(h, new Object());
    +            Asserts.assertEQ(h2, h);
    +            Asserts.assertEQ(h2.v.i, 42);
    +            Asserts.assertNE(h2.v.v, null);
    +        }
    +    }
    +
    +    // Same as test9_non_null, but oop is at offset 4.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_ONE_OOP_4_WITH_BARRIER_FLAG, PRE_AND_POST_NOT_NULL, "1"})
    +    static HolderWithOopsSecond test10_non_null(HolderWithOopsSecond h) {
    +        MyValueOopSecond v = new MyValueOopSecond(42, new Object());
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test10_non_null"})
    +    public void test10_non_null_verifier() {
    +        HolderWithOopsSecond h = new HolderWithOopsSecond();
    +        HolderWithOopsSecond h2 = test10_non_null(h);
    +        Asserts.assertEQ(h2, h);
    +        Asserts.assertEQ(h2.v.i, 42);
    +        Asserts.assertNE(h2.v.v, null);
    +    }
    +
    +    // Same as test9_maybe_null, but null is at offset 4.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIf = {"UseCompressedOops", "true"},
    +        counts = {G1_STORE_L_SPECIAL_ONE_OOP_4_WITH_BARRIER_FLAG, PRE_AND_POST, "1"})
    +    static HolderWithOopsSecond test10_maybe_null(HolderWithOopsSecond h, Object o) {
    +        MyValueOopSecond v = new MyValueOopSecond(42, o);
    +        h.v = v;
    +        return h;
    +    }
    +
    +    @Run(test = {"test10_maybe_null"})
    +    public void test10_maybe_null_verifier() {
    +        HolderWithOopsSecond h = new HolderWithOopsSecond();
    +        {
    +            HolderWithOopsSecond h2 = test10_maybe_null(h, null);
    +            Asserts.assertEQ(h2, h);
    +            Asserts.assertEQ(h2.v.i, 42);
    +            Asserts.assertEQ(h2.v.v, null);
    +        }
    +        {
    +            HolderWithOopsSecond h2 = test10_maybe_null(h, new Object());
    +            Asserts.assertEQ(h2, h);
    +            Asserts.assertEQ(h2.v.i, 42);
    +            Asserts.assertNE(h2.v.v, null);
    +        }
    +    }
    +
    +    // Assign two oops in a single StoreLSpecial, just after initialization
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "true"},
    +        counts = {G1_STORE_L_SPECIAL, "1"},
    +        failOn = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "false"},
    +        counts = {G1_STORE_L_SPECIAL, "1",
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, POST_ONLY, "1"})
    +    static HolderWithTwoOops test11(MyValueWithTwoOops v) {
    +        var _ = v.v1;  // Force v != null
    +        HolderWithTwoOops h = new HolderWithTwoOops(v);
    +        return h;
    +    }
    +
    +    @Run(test = {"test11"})
    +    public void test11_verifier() {
    +        MyValueWithTwoOops v = new MyValueWithTwoOops(new Object(), new Object());
    +        HolderWithTwoOops h = test11(v);
    +        Asserts.assertEQ(h.v, v);
    +    }
    +
    +    // Variation of test11: instead of getting the value object containing the two oops, we create it here.
    +    @Test
    +    @IR(applyIf = {"UseCompressedOops", "false"},
    +        failOn = {G1_STORE_L_SPECIAL})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "true"},
    +        counts = {G1_STORE_L_SPECIAL, "1"},
    +        failOn = {G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, ANY})
    +    @IR(applyIfAnd = {"UseCompressedOops", "true", "ReduceInitialCardMarks", "false"},
    +        counts = {G1_STORE_L_SPECIAL, "1",
    +                  G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, POST_ONLY, "1"})
    +    static HolderWithTwoOops test12(Object first, Object second) {
    +        HolderWithTwoOops h = new HolderWithTwoOops(new MyValueWithTwoOops(first, second));
    +        return h;
    +    }
    +
    +    @Run(test = {"test12"})
    +    public void test12_verifier() {
    +        Object first = new Object();
    +        Object second = new Object();
    +        HolderWithTwoOops holder = test12(first, second);
    +        Asserts.assertEQ(first, holder.v.v1);
    +        Asserts.assertEQ(second, holder.v.v2);
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/igvn/TestMinMax3HopNotification.java b/test/hotspot/jtreg/compiler/igvn/TestMinMax3HopNotification.java
    new file mode 100644
    index 000000000000..42a052216e1d
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/igvn/TestMinMax3HopNotification.java
    @@ -0,0 +1,60 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @bug 8396457
    + * @summary Test that the three-hop notification for MinI/MaxI happens.
    + * @library /test/lib
    + * @run main/othervm -Xcomp -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
    + *                   -XX:CompileCommand=compileonly,${test.main.class}::test*
    + *                   ${test.main.class}
    + * @run main ${test.main.class}
    + */
    +
    +package compiler.igvn;
    +
    +import jdk.test.lib.Asserts;
    +
    +public class TestMinMax3HopNotification {
    +    public static void main(String[] args) {
    +        for (int i = 0; i < 1_000; i++) {
    +            testMin(i, i + 1, i + 2);
    +            testMax(i, i + 1, i + 2);
    +        }
    +    }
    +
    +    static int testMin(int x, int y, int z) {
    +        int dz = 100; for (int i = 0; i < 100; i++) { dz--; }
    +        int a = x & 0xFF;
    +        int inner = (dz == 0) ? a : (y & 0xFF);
    +        return Math.min(Math.min(inner + 1, z), a + 2);
    +    }
    +
    +    static int testMax(int x, int y, int z) {
    +        int dz = 100; for (int i = 0; i < 100; i++) { dz--; }
    +        int a = x & 0xFF;
    +        int inner = (dz == 0) ? a : (y & 0xFF);
    +        return Math.max(Math.max(inner + 1, z), a + 2);
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java
    index a7dc8830677d..1fa8e5ec4abe 100644
    --- a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java
    +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java
    @@ -999,6 +999,36 @@ public static void callLeafNoFpOfMethodNodes(String irNodePlaceholder, String ca
             machOnly(G1_STORE_P_WITH_BARRIER_FLAG, regex);
         }
     
    +    public static final String G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG = COMPOSITE_PREFIX + "G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_ONE_OOP_0_WITH_BARRIER_FLAG = COMPOSITE_PREFIX + "G1_STORE_L_SPECIAL_ONE_OOP_0_WITH_BARRIER_FLAG" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_ONE_OOP_4_WITH_BARRIER_FLAG = COMPOSITE_PREFIX + "G1_STORE_L_SPECIAL_ONE_OOP_4_WITH_BARRIER_FLAG" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG = COMPOSITE_PREFIX + "G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG" + POSTFIX;
    +    static {
    +        String regex_any = START + "g1StoreLSpecial\\S*" + MID + "barrier\\(\\s*" + IS_REPLACED + "\\s*\\)" + END;
    +        String regex_one_oop0 = START + "g1StoreLSpecialOneOopOff0" + MID + "barrier\\(\\s*" + IS_REPLACED + "\\s*\\)" + END;
    +        String regex_one_oop4 = START + "g1StoreLSpecialOneOopOff4" + MID + "barrier\\(\\s*" + IS_REPLACED + "\\s*\\)" + END;
    +        String regex_two_oops = START + "g1StoreLSpecialTwoOops" + MID + "barrier\\(\\s*" + IS_REPLACED + "\\s*\\)" + END;
    +        machOnly(G1_STORE_L_SPECIAL_WITH_BARRIER_FLAG, regex_any);
    +        machOnly(G1_STORE_L_SPECIAL_ONE_OOP_0_WITH_BARRIER_FLAG, regex_one_oop0);
    +        machOnly(G1_STORE_L_SPECIAL_ONE_OOP_4_WITH_BARRIER_FLAG, regex_one_oop4);
    +        machOnly(G1_STORE_L_SPECIAL_TWO_OOPS_WITH_BARRIER_FLAG, regex_two_oops);
    +    }
    +
    +    public static final String G1_STORE_L_SPECIAL = PREFIX + "G1_STORE_L_SPECIAL" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_ONE_OOP_0 = PREFIX + "G1_STORE_L_SPECIAL_ONE_OOP_0" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_ONE_OOP_4 = PREFIX + "G1_STORE_L_SPECIAL_ONE_OOP_4" + POSTFIX;
    +    public static final String G1_STORE_L_SPECIAL_TWO_OOPS = PREFIX + "G1_STORE_L_SPECIAL_TWO_OOPS" + POSTFIX;
    +    static {
    +        String regex_any = START + "g1StoreLSpecial\\S*" + MID + END;
    +        String regex_one_oop0 = START + "g1StoreLSpecialOneOopOff0" + MID + END;
    +        String regex_one_oop4 = START + "g1StoreLSpecialOneOopOff4" + MID + END;
    +        String regex_two_oops = START + "g1StoreLSpecialTwoOops" + MID + END;
    +        machOnly(G1_STORE_L_SPECIAL, regex_any);
    +        machOnly(G1_STORE_L_SPECIAL_ONE_OOP_0, regex_one_oop0);
    +        machOnly(G1_STORE_L_SPECIAL_ONE_OOP_4, regex_one_oop4);
    +        machOnly(G1_STORE_L_SPECIAL_TWO_OOPS, regex_two_oops);
    +    }
    +
         public static final String IF = PREFIX + "IF" + POSTFIX;
         static {
             beforeMatchingNameRegex(IF, "If\\b");
    @@ -3112,6 +3142,11 @@ public static void anyStoreOfNodes(String irNodePlaceholder, String fieldHolder)
             machOnlyNameRegex(X86_VMULDQ_REG, "vmuldq_reg");
         }
     
    +    public static final String X86_VSHIFT_B_GFNI = PREFIX + "X86_VSHIFT_B_GFNI" + POSTFIX;
    +    static {
    +        machOnlyNameRegex(X86_VSHIFT_B_GFNI, "vshiftB_gfni");
    +    }
    +
         public static final String AARCH64_VMULL_UINT_SVE2 = PREFIX + "AARCH64_VMULL_UINT_SVE2" + POSTFIX;
         static {
             machOnlyNameRegex(AARCH64_VMULL_UINT_SVE2, "vmulL_uint_sve2");
    @@ -3608,6 +3643,16 @@ public static void anyStoreOfNodes(String irNodePlaceholder, String fieldHolder)
             staticCallOfMethodNodes(CLONE_INTRINSIC_SLOW_PATH, "java.lang.Object::clone");
         }
     
    +    public static final String SLOW_ARRAYCOPY = PREFIX + "SLOW_ARRAYCOPY" + POSTFIX;
    +    static {
    +        staticCallOfMethodNodes(SLOW_ARRAYCOPY, "slow_arraycopy");
    +    }
    +
    +    public static final String JINT_ARRAYCOPY = PREFIX + "JINT_ARRAYCOPY" + POSTFIX;
    +    static {
    +        callLeafNoFpOfMethodNodes(JINT_ARRAYCOPY, "jint_disjoint_arraycopy");
    +    }
    +
         public static final String JLONG_ARRAYCOPY = PREFIX + "JLONG_ARRAYCOPY" + POSTFIX;
         static {
             callLeafNoFpOfMethodNodes(JLONG_ARRAYCOPY, "jlong_disjoint_arraycopy");
    diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/RunInfo.java b/test/hotspot/jtreg/compiler/lib/ir_framework/RunInfo.java
    index 4d5961a19fee..e81eeb6b057e 100644
    --- a/test/hotspot/jtreg/compiler/lib/ir_framework/RunInfo.java
    +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/RunInfo.java
    @@ -31,6 +31,7 @@
     import java.util.HashMap;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     /**
      * Test info class which provides some useful utility methods and information about a custom run test.
    @@ -84,6 +85,19 @@ public Method getTest(String testName) {
             return getMethod(testName);
         }
     
    +    /**
    +     * Get the set of names of the associated tests.
    +     *
    +     * @return the set of names of the tests specified for this custom run test in {@link Run#test()}.
    +     */
    +    public Set getTestNames() {
    +        if (hasMultipleTests) {
    +            return tests.keySet();
    +        } else {
    +            return Set.of(test.getTestMethod().getName());
    +        }
    +    }
    +
         /**
          * Return a boolean indicating if the framework skipped a compilation of the associated test method after the warm-up
          * due to VM flags not allowing a compilation on the requested level in {@link Test#compLevel()}. This method can only
    diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java b/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java
    index 96399e222849..87ed6fbe8e68 100644
    --- a/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java
    +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java
    @@ -99,6 +99,7 @@ public class ApplicableIRRulesPrinter {
             // Intel AVX
             "avx",
             "avx2",
    +        "gfni",
             "avx512",
             "avx512bw",
             "avx512dq",
    diff --git a/test/hotspot/jtreg/compiler/rangechecks/TestFoldComparesFuzzer.java b/test/hotspot/jtreg/compiler/rangechecks/TestFoldComparesFuzzer.java
    index 93c7c7b1fd29..63e5da676467 100644
    --- a/test/hotspot/jtreg/compiler/rangechecks/TestFoldComparesFuzzer.java
    +++ b/test/hotspot/jtreg/compiler/rangechecks/TestFoldComparesFuzzer.java
    @@ -478,10 +478,9 @@ public Template.ZeroArgs getIRTemplate(boolean withWarmup) {
                             // Not yet folded at parsing, because lo != hi
                             // BoolNode::Ideal: x  x==0 (signed)
                             cmpIParse = "= 2"; cmpUParse = "= 0";
    -                        // BoolNode::Ideal only converts CmpU, not CmpUL, to a signed equality.
    -                        cmpIFinal = isLong ? "= 0" : "= 1";
    -                        cmpUFinal = isLong ? "= 1" : "= 0";
    -                        comment = "a) single element: unsigned compare, or signed equality for int";
    +                        cmpIFinal = "= 1";
    +                        cmpUFinal = "= 0";
    +                        comment = "a) single element -> signed equality";
                         } else if (lo < hi && lo+1 == hi) {
                             // Not yet folded at parsing, because lo != hi
                             cmpIParse = "= 2"; cmpUParse = "= 0"; cmpIFinal = "= 0"; cmpUFinal = "= 0";
    @@ -505,10 +504,9 @@ public Template.ZeroArgs getIRTemplate(boolean withWarmup) {
                         } else if (lo < hi && lo+1 == hi) {
                             // BoolNode::Ideal: x  x==0 (signed)
                             cmpIParse = "= 2"; cmpUParse = "= 0";
    -                        // BoolNode::Ideal only converts CmpU, not CmpUL, to a signed equality.
    -                        cmpIFinal = isLong ? "= 0" : "= 1";
    -                        cmpUFinal = isLong ? "= 1" : "= 0";
    -                        comment = "b) single element: unsigned compare, or signed equality for int";
    +                        cmpIFinal = "= 1";
    +                        cmpUFinal = "= 0";
    +                        comment = "b) single element -> signed equality";
                         } else if (lo < hi && lo+1 < hi) {
                             cmpIParse = "= 2"; cmpUParse = "= 0"; cmpIFinal = "= 0"; cmpUFinal = "= 1";
                             comment = "b) replace with CmpU (non-empty)";
    @@ -527,10 +525,9 @@ public Template.ZeroArgs getIRTemplate(boolean withWarmup) {
                         } else if (lo < hi && lo+1 == hi) {
                             // BoolNode::Ideal: x  x==0 (signed)
                             cmpIParse = "= 2"; cmpUParse = "= 0";
    -                        // BoolNode::Ideal only converts CmpU, not CmpUL, to a signed equality.
    -                        cmpIFinal = isLong ? "= 0" : "= 1";
    -                        cmpUFinal = isLong ? "= 1" : "= 0";
    -                        comment = "c) single element: unsigned compare, or signed equality for int";
    +                        cmpIFinal = "= 1";
    +                        cmpUFinal = "= 0";
    +                        comment = "c) single element -> signed equality";
                         } else if (lo < hi && lo+1 < hi) {
                             cmpIParse = "= 2"; cmpUParse = "= 0"; cmpIFinal = "= 0"; cmpUFinal = "= 1";
                             comment = "c) replace with CmpU (non-empty)";
    @@ -548,10 +545,11 @@ public Template.ZeroArgs getIRTemplate(boolean withWarmup) {
                             cmpIParse = "< 2"; cmpUParse = "= 0"; cmpIFinal = "< 2"; cmpUFinal = "= 0";
                             comment = "d) one or both checks fold at parse time";
                         } else if (lo == hi) {
    -                        // same CmpI at parse time
    -                        // BoolNode::Ideal: x  x==0 (signed)
    -                        cmpIParse = "= 1"; cmpUParse = "= 0"; cmpIFinal = "= 1"; cmpUFinal = "= 0";
    -                        comment = "d) replace with CmpU (single element) -> CmpI eq";
    +                        // Both checks share one signed comparison at parse time.
    +                        cmpIParse = "= 1"; cmpUParse = "= 0";
    +                        cmpIFinal = "= 1";
    +                        cmpUFinal = "= 0";
    +                        comment = "d) single element -> signed equality";
                         } else if (lo < hi) {
                             cmpIParse = "= 2"; cmpUParse = "= 0"; cmpIFinal = "= 0"; cmpUFinal = "= 1";
                             comment = "d) replace with CmpU (non-empty)";
    diff --git a/test/hotspot/jtreg/compiler/stringopts/TestStackedConcatsManyUTF16Overflow.java b/test/hotspot/jtreg/compiler/stringopts/TestStackedConcatsManyUTF16Overflow.java
    index fc19276beb4d..0d415f39a125 100644
    --- a/test/hotspot/jtreg/compiler/stringopts/TestStackedConcatsManyUTF16Overflow.java
    +++ b/test/hotspot/jtreg/compiler/stringopts/TestStackedConcatsManyUTF16Overflow.java
    @@ -50,9 +50,9 @@ public static void main (String... args) {
                 }
                 Asserts.assertEQ(s, z);
             } catch (OutOfMemoryError e) {
    -          Asserts.assertTrue(e.getMessage().equals("Required array length 1073741824 + 1073741824 is too large"));
    -          // Specifically, we should not get "`main' threw exception: java.lang.NegativeArraySizeException: -2147483648"
    -          return;
    +            Asserts.assertEquals("Required length exceeds implementation limit", e.getMessage());
    +            // Specifically, we should not get "`main' threw exception: java.lang.NegativeArraySizeException: -2147483648"
    +            return;
             }
             throw new RuntimeException("Unreachable.");
         }
    diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrayCopy.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrayCopy.java
    index ed2e922e6ea2..5751c40aa6c1 100644
    --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrayCopy.java
    +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrayCopy.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -24,50 +24,75 @@
     /*
      * @test id=default
      * @summary Test correctness of arraycopy intrinsic.
    - * @library /test/lib
    + * @library /test/lib /
      * @enablePreview
      * @modules java.base/jdk.internal.value
      *          java.base/jdk.internal.vm.annotation
      * @run main/othervm -Xbatch
    - *                   compiler.valhalla.valuetypes.TestArrayCopy
    + *                   ${test.main.class}
      */
     
     /*
      * @test id=NoTraps
    - * @library /test/lib
    + * @library /test/lib /
      * @enablePreview
      * @modules java.base/jdk.internal.value
      *          java.base/jdk.internal.vm.annotation
      * @run main/othervm -Xbatch -XX:-TieredCompilation
      *                   -XX:+UnlockExperimentalVMOptions -XX:PerMethodSpecTrapLimit=0 -XX:PerMethodTrapLimit=0
    - *                   compiler.valhalla.valuetypes.TestArrayCopy
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=NoTrapsNoCompressedOops
    + * @library /test/lib /
    + * @enablePreview
    + * @modules java.base/jdk.internal.value
    + *          java.base/jdk.internal.vm.annotation
    + * @run main/othervm -Xbatch -XX:-TieredCompilation
    + *                   -XX:+UnlockExperimentalVMOptions -XX:PerMethodSpecTrapLimit=0 -XX:PerMethodTrapLimit=0
    + *                   -XX:-UseCompressedOops
    + *                   ${test.main.class}
      */
     
     /*
      * @test id=AlwaysIncrementalInline
    - * @library /test/lib
    + * @library /test/lib /
      * @enablePreview
      * @modules java.base/jdk.internal.value
      *          java.base/jdk.internal.vm.annotation
      * @run main/othervm -Xbatch -XX:-TieredCompilation
      *                   -XX:+IgnoreUnrecognizedVMOptions -XX:+AlwaysIncrementalInline
    - *                   compiler.valhalla.valuetypes.TestArrayCopy
    + *                   ${test.main.class}
      */
     
     /*
      * @test id=NoArrayFlattening
    - * @library /test/lib
    + * @library /test/lib /
      * @enablePreview
      * @modules java.base/jdk.internal.value
      *          java.base/jdk.internal.vm.annotation
      * @run main/othervm -Xbatch -XX:+UnlockDiagnosticVMOptions -XX:-UseArrayFlattening
    - *                   compiler.valhalla.valuetypes.TestArrayCopy
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=ir
    + * @library /test/lib /
    + * @enablePreview
    + * @modules java.base/jdk.internal.value
    + *          java.base/jdk.internal.vm.annotation
    + * @run driver ${test.main.class} ir
      */
     
     package compiler.valhalla.valuetypes;
     
     import java.util.Random;
    +import java.util.function.BiConsumer;
    +import java.util.function.Consumer;
    +import java.util.function.IntFunction;
     
    +import compiler.lib.ir_framework.*;
     import jdk.test.lib.Asserts;
     import jdk.test.lib.Utils;
     
    @@ -77,6 +102,8 @@
     public class TestArrayCopy {
         static final Random RAND = Utils.getRandomInstance();
         static final int LEN = RAND.nextInt(10) + 1;
    +    static final int SRC_INIT = 444;
    +    static final int DEST_INIT = 555;
     
         @LooselyConsistentValue
         static value class MyInt {
    @@ -647,7 +674,805 @@ static void testConstantLen16() {
             }
         }
     
    +    /*
    +     * Test cases where we have the same null free non-atomic array flavors but actual different value classes.
    +     *
    +     * We distinguish these cases:
    +     * - Same elem width
    +     * - Smaller to larger elem width
    +     * - Larger to smaller elem width
    +     *
    +     * All of these should result in an ArrayStoreException and the dest array should not be modified.
    +     */
    +    static class NullFreeArraysOfDifferentClasses {
    +        static final VInt[] SRC_INT = newSrc(VInt.class, VInt::new);
    +        static final VInt2[] SRC_INT2 = newSrc(VInt2.class, VInt2::new);
    +        static final VLong[] SRC_LONG = newSrc(VLong.class, VLong::new);
    +        static final VLong2[] SRC_LONG2 = newSrc(VLong2.class, VLong2::new);
    +
    +        static final VInt[] DEST_INT = newDest(VInt.class, VInt::new);
    +        static final VInt2[] DEST_INT2 = newDest(VInt2.class, VInt2::new);
    +        static final VLong[] DEST_LONG = newDest(VLong.class, VLong::new);
    +        static final VLong2[] DEST_LONG2 = newDest(VLong2.class, VLong2::new);
    +
    +        static final VInt[] DEST_INT_UNMODIFIED = newDest(VInt.class, VInt::new);
    +        static final VLong[] DEST_LONG_UNMODIFIED = newDest(VLong.class, VLong::new);
    +        static final VInt2[] DEST_INT2_UNMODIFIED = newDest(VInt2.class, VInt2::new);
    +        static final VLong2[] DEST_LONG2_UNMODIFIED = newDest(VLong2.class, VLong2::new);
    +
    +        static int srcIdx;
    +        static int destIdx;
    +        static int length;
    +        static boolean flag;
    +
    +        static  V[] newSrc(Class type, IntFunction constructor) {
    +            return newArr(type, constructor, SRC_INIT);
    +        }
    +
    +        static  V[] newDest(Class type, IntFunction constructor) {
    +            return newArr(type, constructor, DEST_INIT);
    +        }
    +
    +        @SuppressWarnings("unchecked")
    +        static  V[] newArr(Class type, IntFunction constructor, int initValue) {
    +            V[] arr = (V[]) ValueClass.newNullRestrictedNonAtomicArray(type, LEN, constructor.apply(0));
    +            init(arr, constructor, initValue);
    +            return arr;
    +        }
    +
    +        static void run() {
    +            for (int i = 0; i < 10_000; i++) {
    +                flag = !flag;
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToLarge, DEST_LONG, DEST_LONG_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToSmall, DEST_INT, DEST_INT_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToSmall, DEST_INT2, DEST_INT2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToLarge, DEST_LONG2, DEST_LONG2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToLargeAbstract,
    +                        flag ? DEST_LONG : DEST_LONG2,
    +                        flag ? DEST_LONG_UNMODIFIED : DEST_LONG2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToSmallAbstract,
    +                        flag ? DEST_INT : DEST_INT2,
    +                        flag ? DEST_INT_UNMODIFIED : DEST_INT2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToSmallAbstract,
    +                        flag ? DEST_INT2 : DEST_INT,
    +                        flag ? DEST_INT2_UNMODIFIED : DEST_INT_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToLargeAbstract,
    +                        flag ? DEST_LONG2 : DEST_LONG,
    +                        flag ? DEST_LONG2_UNMODIFIED : DEST_LONG_UNMODIFIED);
    +                if (LEN > 1) {
    +                    length = 1 + RAND.nextInt(LEN - 1);      // 1..LEN-1
    +                    srcIdx = 1 + RAND.nextInt(LEN - length); // 1..LEN-length
    +                    destIdx = 1 + RAND.nextInt(LEN - length); // 1..LEN-length
    +                } else {
    +                    length = 1;
    +                    srcIdx = 0;
    +                    destIdx = 0;
    +                }
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToLargeRandom, DEST_LONG, DEST_LONG_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToSmallRandom, DEST_INT, DEST_INT_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToSmallRandom, DEST_INT2, DEST_INT2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToLargeRandom, DEST_LONG2, DEST_LONG2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToLargeAbstractRandom,
    +                        flag ? DEST_LONG : DEST_LONG2,
    +                        flag ? DEST_LONG_UNMODIFIED : DEST_LONG2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToSmallAbstractRandom,
    +                        flag ? DEST_INT : DEST_INT2,
    +                        flag ? DEST_INT_UNMODIFIED : DEST_INT2_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testSmallToSmallAbstractRandom,
    +                        flag ? DEST_INT2 : DEST_INT,
    +                        flag ? DEST_INT2_UNMODIFIED : DEST_INT_UNMODIFIED);
    +                runTest(NullFreeArraysOfDifferentClasses::testLargeToLargeAbstractRandom,
    +                        flag ? DEST_LONG2 : DEST_LONG,
    +                        flag ? DEST_LONG2_UNMODIFIED : DEST_LONG_UNMODIFIED);
    +            }
    +        }
    +
    +        static  void runTest(Runnable test, V[] dest, V[] expectedDest) {
    +            try {
    +                test.run();
    +                throw new RuntimeException("Should throw ArrayStoreException");
    +            } catch (ArrayStoreException e) {
    +                // Expected
    +            }
    +
    +            for (int j = 0; j < LEN; j++) {
    +                V actual = dest[j];
    +                V expected = expectedDest[j];
    +                if (actual != expected) {
    +                    throw new RuntimeException("Should be unchanged: actual=" + actual + " != expected=" + expected);
    +                }
    +            }
    +        }
    +
    +        static void testSmallToLarge() {
    +            System.arraycopy(SRC_INT, 0, DEST_LONG, 0, LEN);
    +        }
    +
    +        static void testSmallToLargeAbstract() {
    +            VBase[] src = flag ? SRC_INT : SRC_INT2;
    +            VBase[] dest = flag ? DEST_LONG : DEST_LONG2;
    +            System.arraycopy(src, 0, dest, 0, LEN);
    +        }
    +
    +        static void testSmallToLargeRandom() {
    +            System.arraycopy(SRC_INT, srcIdx, DEST_LONG, destIdx, length);
    +        }
    +
    +        static void testSmallToLargeAbstractRandom() {
    +            VBase[] src = flag ? SRC_INT : SRC_INT2;
    +            VBase[] dest = flag ? DEST_LONG : DEST_LONG2;
    +            System.arraycopy(src, srcIdx, dest, destIdx, length);
    +        }
    +
    +        static void testLargeToSmall() {
    +            System.arraycopy(SRC_LONG, 0, DEST_INT, 0, LEN);
    +        }
    +
    +        static void testLargeToSmallAbstract() {
    +            VBase[] src = flag ? SRC_LONG : SRC_LONG2;
    +            VBase[] dest = flag ? DEST_INT : DEST_INT2;
    +            System.arraycopy(src, 0, dest, 0, LEN);
    +        }
    +
    +        static void testLargeToSmallRandom() {
    +            System.arraycopy(SRC_LONG, srcIdx, DEST_INT, destIdx, length);
    +        }
    +
    +        static void testLargeToSmallAbstractRandom() {
    +            VBase[] src = flag ? SRC_LONG : SRC_LONG2;
    +            VBase[] dest = flag ? DEST_INT : DEST_INT2;
    +            System.arraycopy(src, srcIdx, dest, destIdx, length);
    +        }
    +
    +        static void testSmallToSmall() {
    +            System.arraycopy(SRC_INT, 0, DEST_INT2, 0, LEN);
    +        }
    +
    +        static void testSmallToSmallAbstract() {
    +            VBase[] src = flag ? SRC_INT : SRC_INT2;
    +            VBase[] dest = flag ? DEST_INT2 : DEST_INT;
    +            System.arraycopy(src, 0, dest, 0, LEN);
    +        }
    +
    +        static void testSmallToSmallRandom() {
    +            System.arraycopy(SRC_INT, srcIdx, DEST_INT2, destIdx, length);
    +        }
    +
    +        static void testSmallToSmallAbstractRandom() {
    +            VBase[] src = flag ? SRC_INT : SRC_INT2;
    +            VBase[] dest = flag ? DEST_INT2 : DEST_INT;
    +            System.arraycopy(src, srcIdx, dest, destIdx, length);
    +        }
    +
    +        static void testLargeToLarge() {
    +            System.arraycopy(SRC_LONG, 0, DEST_LONG2, 0, LEN);
    +        }
    +
    +        static void testLargeToLargeAbstract() {
    +            VBase[] src = flag ? SRC_LONG : SRC_LONG2;
    +            VBase[] dest = flag ? DEST_LONG2 : DEST_LONG;
    +            System.arraycopy(src, 0, dest, 0, LEN);
    +        }
    +
    +        static void testLargeToLargeRandom() {
    +            System.arraycopy(SRC_LONG, srcIdx, DEST_LONG2, destIdx, length);
    +        }
    +
    +        static void testLargeToLargeAbstractRandom() {
    +            VBase[] src = flag ? SRC_LONG : SRC_LONG2;
    +            VBase[] dest = flag ? DEST_LONG2 : DEST_LONG;
    +            System.arraycopy(src, srcIdx, dest, destIdx, length);
    +        }
    +    }
    +
    +    /*
    +     * Test cases where src and dest have the same class but different layouts.
    +     *
    +     * We cover all variations of src/dest <-> dest/src:
    +     * - null-free-atomic     <-> nullable
    +     * - null-free-non-atomic <-> nullable
    +     * - null-free-atomic     <-> null-free-non-atomic
    +     *
    +     * To make this work, we add branches such that C2 falls back to the type in [] to have the same src and dest property:
    +     * - null-free-atomic      [C2: nullable] <-> nullable
    +     * - null-free-non-atomic  [C2: nullable] <-> nullable
    +     * - null-free-atomic      [C2: unknown atomicity] <-> null-free-non-atomic
    +     * - null-free-non-atomic  [C2: unknown atomicity] <-> null-free-atomic
    +     *
    +     * Finally, we also add branches for src and dest where C2 only knows unknown atomicity + nullable
    +     *
    +     * We also add tests where we have a null element in a nullable src array. When calling arraycopy, we first copy
    +     * all non-null elements up to the null element and then throw a NPE for that null element. The rest of the dest
    +     * array should remain unmodified.
    +     */
    +    static class SameClassDifferentLayout {
    +        static final VTwoShorts[] SRC_REFERENCE = (VTwoShorts[]) ValueClass.newReferenceArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] SRC_NULLABLE = (VTwoShorts[]) ValueClass.newNullableAtomicArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] SRC_NULL_FREE_ATOMIC = (VTwoShorts[]) ValueClass.newNullRestrictedAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +        static final VTwoShorts[] SRC_NULL_FREE_NON_ATOMIC = (VTwoShorts[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +
    +        static final VTwoShorts[] DEST_REFERENCE = (VTwoShorts[]) ValueClass.newReferenceArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] DEST_NULLABLE = (VTwoShorts[]) ValueClass.newNullableAtomicArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] DEST_NULL_FREE_ATOMIC = (VTwoShorts[]) ValueClass.newNullRestrictedAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +        static final VTwoShorts[] DEST_NULL_FREE_NON_ATOMIC = (VTwoShorts[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +
    +        static final VTwoShorts[] DEST_REFERENCE_UNMODIFIED = (VTwoShorts[]) ValueClass.newReferenceArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] DEST_NULLABLE_UNMODIFIED = (VTwoShorts[]) ValueClass.newNullableAtomicArray(VTwoShorts.class, LEN);
    +        static final VTwoShorts[] DEST_NULL_FREE_ATOMIC_UNMODIFIED = (VTwoShorts[]) ValueClass.newNullRestrictedAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +        static final VTwoShorts[] DEST_NULL_FREE_NON_ATOMIC_UNMODIFIED = (VTwoShorts[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts.class, LEN, new VTwoShorts(0));
    +
    +        static final VTwoShorts[] SRC_NULL_FREE_NON_ATOMIC_SIZE_10 = (VTwoShorts[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts.class, 10, new VTwoShorts(0));
    +        static final VTwoShorts[] DEST_NULL_FREE_NON_ATOMIC_SIZE_10 = (VTwoShorts[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts.class, 10, new VTwoShorts(0));
    +
    +        static final VTwoShorts2[] SRC_NULL_FREE_NON_ATOMIC2 = (VTwoShorts2[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts2.class, LEN, new VTwoShorts2(0));
    +        static final VTwoShorts2[] DEST_NULL_FREE_NON_ATOMIC2 = (VTwoShorts2[]) ValueClass.newNullRestrictedNonAtomicArray(VTwoShorts2.class, LEN, new VTwoShorts2(0));
    +
    +        static {
    +            initSrc(SRC_REFERENCE);
    +            initSrc(SRC_NULLABLE);
    +            initSrc(SRC_NULL_FREE_ATOMIC);
    +            initSrc(SRC_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_REFERENCE);
    +            initDest(DEST_NULLABLE_UNMODIFIED);
    +            initDest(DEST_NULL_FREE_ATOMIC_UNMODIFIED);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC_UNMODIFIED);
    +
    +            init(SRC_NULL_FREE_NON_ATOMIC2, VTwoShorts2::new, SRC_INIT);
    +        }
    +
    +        static void initSrc(VTwoShorts[] arr) {
    +            init(arr, VTwoShorts::new, SRC_INIT);
    +        }
    +
    +        static void initDest(VTwoShorts[] arr) {
    +            init(arr, VTwoShorts::new, DEST_INIT);
    +        }
    +
    +        @Run(test = {"testRefToNullable",
    +                     "testNullableToRef",
    +                     "testRefToNullFreeAtomic",
    +                     "testNullFreeAtomicToRef",
    +                     "testRefToNullFreeNonAtomic",
    +                     "testNullFreeNonAtomicToRef",
    +                     "testRefToNullableExact",
    +                     "testNullableToRefExact",
    +                     "testRefToNullFreeAtomicExact",
    +                     "testNullFreeAtomicToRefExact",
    +                     "testRefToNullFreeNonAtomicExact",
    +                     "testNullFreeNonAtomicToRefExact",
    +                     "testNullFreeAtomicToNullable",
    +                     "testNullableToNullFreeAtomic",
    +                     "testNullFreeNonAtomicToNullable",
    +                     "testNullableToNullFreeNonAtomic",
    +                     "testNullFreeToNonAtomic",
    +                     "testNullFreeToAtomic",
    +                     "testMergedNullableNullFreeAtomic",
    +                     "testMergedNullableNullFreeNonAtomic",
    +                     "testFastPathMacroExpansion",
    +                     "testFastPathAtomic",
    +                     "testAbstract"})
    +        static void run() {
    +            boolean flag = RAND.nextBoolean();
    +            boolean flag2 = RAND.nextBoolean();
    +            initDest(DEST_NULLABLE);
    +            runTest(SameClassDifferentLayout::testRefToNullable, flag,
    +                    SRC_REFERENCE, SRC_NULLABLE, DEST_NULLABLE);
    +
    +            initDest(DEST_REFERENCE);
    +            initDest(DEST_NULLABLE);
    +            runTest(SameClassDifferentLayout::testNullableToRef, flag,
    +                    DEST_REFERENCE, DEST_NULLABLE, SRC_NULLABLE);
    +
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            runTest(SameClassDifferentLayout::testRefToNullFreeAtomic, flag,
    +                    SRC_REFERENCE, SRC_NULL_FREE_ATOMIC, DEST_NULL_FREE_ATOMIC);
    +
    +            initDest(DEST_REFERENCE);
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullFreeAtomicToRef, flag,
    +                    DEST_REFERENCE, DEST_NULL_FREE_ATOMIC, SRC_NULL_FREE_ATOMIC);
    +
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testRefToNullFreeNonAtomic, flag,
    +                    SRC_REFERENCE, SRC_NULL_FREE_NON_ATOMIC, DEST_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_REFERENCE);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullFreeNonAtomicToRef, flag,
    +                    DEST_REFERENCE, DEST_NULL_FREE_NON_ATOMIC, SRC_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_NULLABLE);
    +            runTest(SameClassDifferentLayout::testRefToNullableExact, SRC_REFERENCE, DEST_NULLABLE);
    +
    +            initDest(DEST_REFERENCE);
    +            runTest(SameClassDifferentLayout::testNullableToRefExact, SRC_NULLABLE, DEST_REFERENCE);
    +
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            runTest(SameClassDifferentLayout::testRefToNullFreeAtomicExact, SRC_REFERENCE, DEST_NULL_FREE_ATOMIC);
    +
    +            initDest(DEST_REFERENCE);
    +            runTest(SameClassDifferentLayout::testNullFreeAtomicToRefExact, SRC_NULL_FREE_ATOMIC, DEST_REFERENCE);
    +
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testRefToNullFreeNonAtomicExact, SRC_REFERENCE, DEST_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_REFERENCE);
    +            runTest(SameClassDifferentLayout::testNullFreeNonAtomicToRefExact, SRC_NULL_FREE_NON_ATOMIC, DEST_REFERENCE);
    +
    +            initDest(DEST_NULLABLE);
    +            runTest(SameClassDifferentLayout::testNullFreeAtomicToNullable, flag,
    +                    SRC_NULL_FREE_ATOMIC, SRC_NULLABLE, DEST_NULLABLE);
    +
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullableToNullFreeAtomic, flag,
    +                    DEST_NULL_FREE_ATOMIC, DEST_NULLABLE, SRC_NULLABLE);
    +
    +            initDest(DEST_NULLABLE);
    +            runTest(SameClassDifferentLayout::testNullFreeNonAtomicToNullable, flag,
    +                    SRC_NULL_FREE_NON_ATOMIC, SRC_NULLABLE, DEST_NULLABLE);
    +
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullableToNullFreeNonAtomic, flag,
    +                    DEST_NULL_FREE_NON_ATOMIC, DEST_NULLABLE, SRC_NULLABLE);
    +
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullFreeToNonAtomic, flag,
    +                    SRC_NULL_FREE_ATOMIC, SRC_NULL_FREE_NON_ATOMIC, DEST_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTest(SameClassDifferentLayout::testNullFreeToAtomic, flag,
    +                    DEST_NULL_FREE_ATOMIC, DEST_NULL_FREE_NON_ATOMIC, SRC_NULL_FREE_NON_ATOMIC);
    +
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            VTwoShorts[] vTwoShortsSrc = flag ? SRC_NULL_FREE_ATOMIC : SRC_NULLABLE;
    +            VTwoShorts[] vTwoShortsDest = flag2 ? DEST_NULL_FREE_ATOMIC : DEST_NULLABLE;
    +            runTestMerged(SameClassDifferentLayout::testMergedNullableNullFreeAtomic, flag, flag2,
    +                          vTwoShortsSrc, vTwoShortsDest);
    +
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            vTwoShortsSrc = flag ? SRC_NULL_FREE_NON_ATOMIC : SRC_NULLABLE;
    +            vTwoShortsDest = flag2 ? DEST_NULL_FREE_NON_ATOMIC : DEST_NULLABLE;
    +            runTestMerged(SameClassDifferentLayout::testMergedNullableNullFreeNonAtomic, flag, flag2,
    +                          vTwoShortsSrc, vTwoShortsDest);
    +
    +            int nullIndex = RAND.nextInt(LEN);
    +            VTwoShorts backup = SRC_NULLABLE[nullIndex];
    +
    +            SRC_NULLABLE[nullIndex] = null;
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            runTestPrefixWithNull(SameClassDifferentLayout::testNullableToNullFreeAtomic, flag, nullIndex,
    +                                  DEST_NULL_FREE_ATOMIC,
    +                                  DEST_NULL_FREE_ATOMIC_UNMODIFIED);
    +
    +            initDest(DEST_NULLABLE);
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            runTestPrefixWithNull(SameClassDifferentLayout::testNullableToNullFreeNonAtomic, flag, nullIndex,
    +                                  DEST_NULL_FREE_NON_ATOMIC,
    +                                  DEST_NULL_FREE_NON_ATOMIC_UNMODIFIED);
    +            SRC_NULLABLE[nullIndex] = backup;
    +
    +            initDest(DEST_NULL_FREE_NON_ATOMIC_SIZE_10);
    +            testFastPathMacroExpansion();
    +            verifySame(SRC_NULL_FREE_NON_ATOMIC_SIZE_10, DEST_NULL_FREE_NON_ATOMIC_SIZE_10);
    +
    +            initDest(DEST_NULL_FREE_ATOMIC);
    +            testFastPathAtomic();
    +            verifySame(SRC_NULL_FREE_ATOMIC, DEST_NULL_FREE_ATOMIC);
    +
    +            initDest(DEST_NULL_FREE_NON_ATOMIC);
    +            init(DEST_NULL_FREE_NON_ATOMIC2, VTwoShorts2::new, DEST_INIT);
    +            testAbstract(SRC_NULL_FREE_NON_ATOMIC, DEST_NULL_FREE_NON_ATOMIC);
    +            verifySame(SRC_NULL_FREE_NON_ATOMIC, DEST_NULL_FREE_NON_ATOMIC);
    +            testAbstract(SRC_NULL_FREE_NON_ATOMIC2, DEST_NULL_FREE_NON_ATOMIC2);
    +            verifySame(SRC_NULL_FREE_NON_ATOMIC2, DEST_NULL_FREE_NON_ATOMIC2);
    +        }
    +
    +        static void runTest(Runnable test, VTwoShorts[] src, VTwoShorts[] expected) {
    +            test.run();
    +            verifySame(src, expected);
    +        }
    +
    +        static void runTest(Consumer test, boolean flag,
    +                            VTwoShorts[] choice1, VTwoShorts[] choice2, VTwoShorts[] expected) {
    +            test.accept(flag);
    +            VTwoShorts[] vTwoShorts = flag ? choice1 : choice2;
    +            verifySame(vTwoShorts, expected);
    +        }
    +
    +        static void runTestMerged(BiConsumer test, boolean flag, boolean flag2,
    +                                  VTwoShorts[] src, VTwoShorts[] dest) {
    +            test.accept(flag, flag2);
    +            verifySame(src, dest);
    +        }
    +
    +        static void runTestPrefixWithNull(Consumer test, boolean isNullFree, int nullIndex,
    +                                          VTwoShorts[] nullFreeArr,
    +                                          VTwoShorts[] nullFreeArrUnmodified) {
    +            VTwoShorts[] vTwoShorts = isNullFree ? nullFreeArr : DEST_NULLABLE;
    +            VTwoShorts[] vTwoShortsUnmodified = isNullFree ? nullFreeArrUnmodified : DEST_NULLABLE_UNMODIFIED;
    +            try {
    +                test.accept(isNullFree);
    +                Asserts.assertFalse(isNullFree);
    +
    +                // Nullable case: Can successfully copy null.
    +                verifySame(SRC_NULLABLE, vTwoShorts);
    +            } catch (NullPointerException e) {
    +                // Null Free case -> threw when encounter null at nullIndex
    +                Asserts.assertTrue(isNullFree);
    +                verifyPrefixCopied(vTwoShorts, vTwoShortsUnmodified, nullIndex);
    +            }
    +        }
    +
    +        static void verifyPrefixCopied(VTwoShorts[] dest, VTwoShorts[] destUnmodified, int nullIdx) {
    +            for (int i = 0; i < nullIdx; i++) {
    +                // Prefix copied
    +                Asserts.assertEQ(SRC_NULLABLE[i], dest[i]);
    +            }
    +
    +            for (int i = nullIdx; i < LEN; i++) {
    +                // Null + postfix NOT copied
    +                Asserts.assertEQ(dest[i], destUnmodified[i]);
    +            }
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullable(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_REFERENCE : SRC_NULLABLE; // Type: nullable
    +            System.arraycopy(vTwoShorts, 0, DEST_NULLABLE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullableToRef(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_REFERENCE : DEST_NULLABLE; // Type: nullable
    +            System.arraycopy(SRC_NULLABLE, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullFreeAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_REFERENCE : SRC_NULL_FREE_ATOMIC; // Type: nullable
    +            System.arraycopy(vTwoShorts, 0, DEST_NULL_FREE_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeAtomicToRef(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_REFERENCE : DEST_NULL_FREE_ATOMIC; // Type: nullable
    +            System.arraycopy(SRC_NULL_FREE_ATOMIC, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullFreeNonAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_REFERENCE : SRC_NULL_FREE_NON_ATOMIC; // Type: nullable
    +            System.arraycopy(vTwoShorts, 0, DEST_NULL_FREE_NON_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeNonAtomicToRef(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_REFERENCE : DEST_NULL_FREE_NON_ATOMIC; // Type: nullable
    +            System.arraycopy(SRC_NULL_FREE_NON_ATOMIC, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullableExact() {
    +            System.arraycopy(SRC_REFERENCE, 0, DEST_NULLABLE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullableToRefExact() {
    +            System.arraycopy(SRC_NULLABLE, 0, DEST_REFERENCE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullFreeAtomicExact() {
    +            System.arraycopy(SRC_REFERENCE, 0, DEST_NULL_FREE_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeAtomicToRefExact() {
    +            System.arraycopy(SRC_NULL_FREE_ATOMIC, 0, DEST_REFERENCE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testRefToNullFreeNonAtomicExact() {
    +            System.arraycopy(SRC_REFERENCE, 0, DEST_NULL_FREE_NON_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +                failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeNonAtomicToRefExact() {
    +            System.arraycopy(SRC_NULL_FREE_NON_ATOMIC, 0, DEST_REFERENCE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeAtomicToNullable(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_NULL_FREE_ATOMIC : SRC_NULLABLE; // Type: nullable
    +            System.arraycopy(vTwoShorts, 0, DEST_NULLABLE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullableToNullFreeAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_NULL_FREE_ATOMIC : DEST_NULLABLE; // Type: nullable
    +            System.arraycopy(SRC_NULLABLE, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeNonAtomicToNullable(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_NULL_FREE_NON_ATOMIC : SRC_NULLABLE; // Type: Unknown atomicity + nullable
    +            System.arraycopy(vTwoShorts, 0, DEST_NULLABLE, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullableToNullFreeNonAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_NULL_FREE_NON_ATOMIC : DEST_NULLABLE; // Type: Unknown atomicity + nullable
    +            System.arraycopy(SRC_NULLABLE, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeToNonAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? SRC_NULL_FREE_ATOMIC : SRC_NULL_FREE_NON_ATOMIC; // Type: null free + unknown atomicity
    +            System.arraycopy(vTwoShorts, 0, DEST_NULL_FREE_NON_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testNullFreeToAtomic(boolean flag) {
    +            VTwoShorts[] vTwoShorts = flag ? DEST_NULL_FREE_ATOMIC : DEST_NULL_FREE_NON_ATOMIC; // Type: null free + unknown atomicity
    +            System.arraycopy(SRC_NULL_FREE_NON_ATOMIC, 0, vTwoShorts, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testMergedNullableNullFreeAtomic(boolean flag, boolean flag2) {
    +            VTwoShorts[] vTwoShortsSrc = flag ? SRC_NULL_FREE_ATOMIC : SRC_NULLABLE; // Type: nullable
    +            VTwoShorts[] vTwoShortsDest = flag2 ? DEST_NULL_FREE_ATOMIC : DEST_NULLABLE; // Type: nullable
    +            System.arraycopy(vTwoShortsSrc, 0, vTwoShortsDest, 0, LEN);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" }, // Different layouts
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testMergedNullableNullFreeNonAtomic(boolean flag, boolean flag2) {
    +            VTwoShorts[] vTwoShortsSrc = flag ? SRC_NULL_FREE_NON_ATOMIC : SRC_NULLABLE; // Type: Unknown atomicity + nullable
    +            VTwoShorts[] vTwoShortsDest = flag2 ? DEST_NULL_FREE_NON_ATOMIC : DEST_NULLABLE; // Type: Unknown atomicity + nullable
    +            System.arraycopy(vTwoShortsSrc, 0, vTwoShortsDest, 0, LEN);
    +        }
    +
    +        // Without traps: Not verified but known to be same layout + not atomic
    +        //                -> Select fast path in macro expansion.
    +        @Test
    +        @IR(counts = { IRNode.JINT_ARRAYCOPY, "1" }, // Matching layout + non-atomic -> fast path
    +            failOn = { IRNode.SLOW_ARRAYCOPY })      // and no slow path
    +        static void testFastPathMacroExpansion() {
    +            System.arraycopy(SRC_NULL_FREE_NON_ATOMIC_SIZE_10, 0,
    +                             DEST_NULL_FREE_NON_ATOMIC_SIZE_10, 0, 10);
    +        }
    +
    +        @Test
    +        @IR(counts = { IRNode.JINT_ARRAYCOPY, "1" }, // Matching layout and atomic -> fast path
    +            failOn = { IRNode.SLOW_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no slow path
    +        static void testFastPathAtomic() {
    +            System.arraycopy(SRC_NULL_FREE_ATOMIC, 0,
    +                             DEST_NULL_FREE_ATOMIC, 0, LEN);
    +        }
    +
    +        @Test
    +        // Cannot prove same layouts due to abstract types (i.e. inexact) -> slow path
    +        @IR(counts = { IRNode.SLOW_ARRAYCOPY, "1" },
    +            failOn = { IRNode.JINT_ARRAYCOPY, IRNode.JLONG_ARRAYCOPY }) // no fast path
    +        static void testAbstract(VBaseTwoShorts[] src, VBaseTwoShorts[] dest) {
    +            System.arraycopy(src, 0, dest, 0, LEN);
    +        }
    +
    +        static void verifySame(Object[] src, Object[] dest) {
    +            Asserts.assertEQ(src.length, dest.length);
    +            for (int i = 0; i < src.length; i++) {
    +                if (src[i] != dest[i]) {
    +                    throw new RuntimeException(arrayAsString(dest));
    +                }
    +            }
    +        }
    +
    +        static String arrayAsString(Object[] arr) {
    +            StringBuilder builder = new StringBuilder();
    +            for (int i = 0; i < arr.length; i++) {
    +                builder.append(i).append(": ").append(arr[i]).append(System.lineSeparator());
    +            }
    +            return builder.toString();
    +        }
    +
    +        @LooselyConsistentValue
    +        static abstract value class VBaseTwoShorts {}
    +
    +        @LooselyConsistentValue
    +        static value class VTwoShorts extends VBaseTwoShorts {
    +            short x;
    +            short y;
    +
    +            VTwoShorts(int i) {
    +                x = (short) i;
    +                y = (short) (i + 1);
    +            }
    +
    +            @Override
    +            public String toString() {
    +                return "x=" + x + ", y=" + y;
    +            }
    +        }
    +
    +        @LooselyConsistentValue
    +        static value class VTwoShorts2 extends VBaseTwoShorts {
    +            short x;
    +            short y;
    +
    +            VTwoShorts2(int i) {
    +                x = (short) i;
    +                y = (short) (i + 1);
    +            }
    +
    +            @Override
    +            public String toString() {
    +                return "x=" + x + ", y=" + y;
    +            }
    +        }
    +    }
    +
    +    /*
    +     * Test cases where src and dest are different classes but src starts with some null elements.
    +     *
    +     * The semantics of arraycopy allow the first few nulls to be copied until we hit the first non-null element where
    +     * we then throw an ArrayStoreException.
    +     *
    +     * For example, with NON_NULL_INDEX = 3:
    +     *
    +     * Before Arraycopy:
    +     *   VInt[] src:   [null,     null, null, VInt(... ), VInt(... ), ...]
    +     *   VInt2[] dest: [D0,       D1,   D2,   D3,         D4,         ...]
    +     * After Arraycopy:
    +     *   VInt2[] dest: [null,     null, null, D3,         D4,         ...]
    +     *   -> Index 0 - 2: Successfully copy null to VInt2[]
    +     *   -> At index 3:  Copying VInt(34) to VInt2[] throws an ArrayStoreException without updating index 3.
    +     */
    +    static class DifferentClassWithNull {
    +        static final VInt[] SRC_NULLABLE = (VInt[]) ValueClass.newNullableAtomicArray(VInt.class, LEN + 3);
    +        static final VInt2[] DEST_NULLABLE = (VInt2[]) ValueClass.newNullableAtomicArray(VInt2.class, LEN + 3);
    +        static final VInt2[] DEST_NULLABLE_UNMODIFIED = (VInt2[]) ValueClass.newNullableAtomicArray(VInt2.class, LEN + 3);
    +        static final int NON_NULL_INDEX = RAND.nextInt(1, SRC_NULLABLE.length - 2);
    +
    +        static void run() {
    +            for (int i = 0; i < SRC_NULLABLE.length; i++) {
    +                if (i < NON_NULL_INDEX) {
    +                    SRC_NULLABLE[i] = null;
    +                } else {
    +                    SRC_NULLABLE[i] = new VInt(SRC_INIT + i);
    +                }
    +                DEST_NULLABLE[i] = new VInt2(DEST_INIT + i); // reset again
    +                DEST_NULLABLE_UNMODIFIED[i] = new VInt2(DEST_INIT + i);
    +            }
    +
    +            for (int i = 0; i < 10_000; i++) {
    +                runTest();
    +            }
    +        }
    +
    +        private static void runTest() {
    +            try {
    +                test();
    +                Asserts.fail("Should throw ArrayStoreException");
    +            } catch (ArrayStoreException e) {
    +                // Expected
    +                for (int i = 0; i < SRC_NULLABLE.length; i++) {
    +                    if (i < NON_NULL_INDEX) {
    +                        Asserts.assertEQ(DEST_NULLABLE[i], null);
    +                    } else {
    +                        Asserts.assertEQ(DEST_NULLABLE[i], DEST_NULLABLE_UNMODIFIED[i]);
    +                    }
    +                    DEST_NULLABLE[i] = new VInt2(DEST_INIT + i); // reset again
    +                }
    +            }
    +        }
    +
    +        static void test() {
    +            System.arraycopy(SRC_NULLABLE, 0, DEST_NULLABLE, 0, LEN + 3);
    +        }
    +    }
    +
    +    private static  void init(V[] arr, IntFunction constructor, int initValue) {
    +        for (int i = 0; i < arr.length; i++) {
    +            arr[i] = constructor.apply(initValue + i);
    +        }
    +    }
    +
    +    static abstract value class VBase {}
    +
    +    static value class VInt extends VBase {
    +        int x;
    +
    +        VInt(int x) {
    +            this.x = x;
    +        }
    +    }
    +
    +    static value class VInt2 extends VBase {
    +        int x;
    +
    +        VInt2(int x) {
    +            this.x = x;
    +        }
    +    }
    +
    +    static value class VLong extends VBase {
    +        long x;
    +
    +        VLong(long x) {
    +            this.x = x;
    +        }
    +    }
    +
    +    static value class VLong2 extends VBase {
    +        long x;
    +
    +        VLong2(long x) {
    +            this.x = x;
    +        }
    +    }
    +
         public static void main(String[] args) {
    +        if (args.length == 1) {
    +            Asserts.assertEQ(args[0], "ir");
    +            new TestFramework(SameClassDifferentLayout.class)
    +                    .addFlags(
    +                            "--enable-preview",
    +                            "--add-exports", "java.base/jdk.internal.value=ALL-UNNAMED",
    +                            "--add-exports", "java.base/jdk.internal.vm.annotation=ALL-UNNAMED",
    +                            "-XX:-TieredCompilation",
    +                            "-XX:+UnlockExperimentalVMOptions",
    +                            "-XX:PerMethodSpecTrapLimit=0",
    +                            "-XX:PerMethodTrapLimit=0")
    +                    .start();
    +            return;
    +        }
    +
             for (int i = 0; i < 50_000; ++i) {
                 int len = (i % 10) + 1;
                 test1(len);
    @@ -692,5 +1517,12 @@ public static void main(String[] args) {
                 testConstantLen15NoInit();
                 testConstantLen16();
             }
    +
    +        NullFreeArraysOfDifferentClasses.run();
    +        for (int i = 0; i < 10_000; i++) {
    +            // Invoke normally, no need for IR Framework interaction.
    +            SameClassDifferentLayout.run();
    +        }
    +        DifferentClassWithNull.run();
         }
     }
    diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestAtomicFlatFieldLoadBarrier.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestAtomicFlatFieldLoadBarrier.java
    new file mode 100644
    index 000000000000..5dbdac7523ed
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestAtomicFlatFieldLoadBarrier.java
    @@ -0,0 +1,121 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +package compiler.valhalla.valuetypes;
    +
    +import jdk.test.lib.Asserts;
    +import jdk.test.whitebox.WhiteBox;
    +
    +/*
    + * @test id=plain
    + * @bug 8397208
    + * @summary Test GC barriers when buffering at atomic flat field loads.
    + * @enablePreview
    + * @library /test/lib /compiler/whitebox /
    + * @build jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=serial
    + * @bug 8397208
    + * @summary Test GC barriers when buffering at atomic flat field loads.
    + * @enablePreview
    + * @library /test/lib /compiler/whitebox /
    + * @build jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @requires vm.gc.Serial
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
    + *                   -Xbatch -Xmn4m -XX:+UseSerialGC
    + *                   -XX:CompileCommand=compileonly,${test.main.class}::load
    + *                   ${test.main.class}
    + */
    +
    +/*
    + * @test id=c2
    + * @bug 8397208
    + * @summary Test GC barriers when buffering at atomic flat field loads.
    + * @enablePreview
    + * @library /test/lib /compiler/whitebox /
    + * @build jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @requires vm.gc.Serial & vm.compiler2.enabled
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
    + *                   -Xbatch -Xmn4m -XX:+UseSerialGC -XX:-TieredCompilation
    + *                   -XX:-ReduceInitialCardMarks
    + *                   -XX:CompileCommand=compileonly,${test.main.class}::load
    + *                   ${test.main.class}
    + */
    +public class TestAtomicFlatFieldLoadBarrier {
    +    static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
    +
    +    static value class ValueWithOop {
    +        int[] array;
    +
    +        ValueWithOop(int[] array) {
    +            this.array = array;
    +        }
    +    }
    +
    +    static Object sink;
    +    ValueWithOop field;
    +
    +    TestAtomicFlatFieldLoadBarrier(int value) {
    +        field = new ValueWithOop(new int[] {value});
    +    }
    +
    +    Object load() {
    +        // Loading flat 'field' requires buffering which needs a GC barrier to store 'array'
    +        return field;
    +    }
    +
    +    public static void main(String[] args) {
    +        TestAtomicFlatFieldLoadBarrier t = new TestAtomicFlatFieldLoadBarrier(42);
    +        int[] expectedArray = t.field.array;
    +        // Make sure that 'load' is compiled
    +        for (int i = 0; i < 10_000; i++) {
    +            t.load();
    +        }
    +
    +        // We want to create a buffer in the old generation with an 'array'
    +        // field that points to an array in the young generation.
    +
    +        // Fill up most of young and old and then trigger a full GC to
    +        // convince the GC to allocate new buffers in old.
    +        int youngSize = (int)(long)WHITE_BOX.getSizeTVMFlag("NewSize");
    +        sink = new Object[] {new byte[youngSize / 2], new byte[youngSize]};
    +        WHITE_BOX.fullGC();
    +
    +        // Each load creates a new buffer. The first ones might still end up in the young
    +        // generation until it's occupied and they end up in old. A young collection then
    +        // moves 'expectedArray' into old but without a proper GC post-barrier, the GC
    +        // won't update the reference from 'value.array' and a stale reference remains.
    +        for (int i = 0; i < 100_000; i++) {
    +            ValueWithOop value = (ValueWithOop)t.load();
    +            Asserts.assertSame(expectedArray, value.array, "Stale reference?");
    +        }
    +    }
    +}
    +
    diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArrayCheckCloneLoop.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArrayCheckCloneLoop.java
    new file mode 100644
    index 000000000000..59a586cf4ff6
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArrayCheckCloneLoop.java
    @@ -0,0 +1,118 @@
    +/*
    + * Copyright (c) 2026 IBM Corporation. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +import jdk.internal.value.ValueClass;
    +
    +/*
    + * @test
    + * @bug 8395724
    + * @summary [valhalla] "adr_type for memory phis only" assert failure
    + * @enablePreview
    + * @modules java.base/jdk.internal.value
    + * @run main/othervm -XX:CompileCommand=dontinline,${test.main.class}::notInlined -XX:-BackgroundCompilation ${test.main.class}
    + * @run main ${test.main.class}
    + */
    +
    +public class TestFlatArrayCheckCloneLoop {
    +    public static void main(String[] args) {
    +        for (int i = 0; i < 20_000; i++) {
    +            test1(0, false, false);
    +            earlyReturn1 = false;
    +            earlyReturn2 = false;
    +            array = notFlatArray1;
    +            test1(999, true, true);
    +            inlined(999, true, false);
    +            earlyReturn1 = true;
    +            earlyReturn2 = false;
    +            array = notFlatArray1;
    +            inlined(999, false, true);
    +            inlined(999, true, true);
    +            array = notFlatArray2;
    +            inlined(999, false, true);
    +            inlined(999, true, true);
    +            earlyReturn1 = false;
    +            earlyReturn2 = true;
    +            array = notFlatArray1;
    +            inlined(999, false, true);
    +            inlined(999, true, true);
    +            array = notFlatArray2;
    +            inlined(999, false, true);
    +            inlined(999, true, true);
    +        }
    +    }
    +
    +    static class A {
    +    }
    +
    +    static value class B {
    +        long field1;
    +        B(long field1, long field2) {
    +            this.field1 = field1;
    +        }
    +    }
    +
    +    static Object[] notFlatArray1 = new A[1000];
    +    static Object[] notFlatArray2 = ValueClass.newNullRestrictedAtomicArray(B.class, 1000, new B(42, 42));
    +    static Object[] array;
    +    static Object field;
    +    static int intField;
    +    static boolean earlyReturn1;
    +    static boolean earlyReturn2;
    +    static Boolean alwaysFalse = false;
    +
    +    static void test1(int len, boolean flag1, boolean flag2) {
    +        if (flag2) {
    +            inlined(len, flag1, flag2);
    +        }
    +    }
    +
    +    static void inlined(int len, boolean flag1, boolean flag2) {
    +        boolean flag = flag1;
    +        for (int i = 0; i < len; i++) {
    +            if (flag) {
    +                notInlined();
    +            }
    +            Object[] localArray1 = array;
    +            if (localArray1 == null) {
    +                throw new RuntimeException("unreachable");
    +            }
    +            if (earlyReturn2) {
    +                intField = ValueClass.isFlatArray(localArray1) ? 0 : 1;
    +                return;
    +            }
    +
    +            if (earlyReturn1) {
    +                field = localArray1[i+1];
    +                return;
    +            }
    +            if (flag2) {
    +                flag = flag1;
    +            } else {
    +                flag = alwaysFalse;
    +            }
    +        }
    +    }
    +
    +    static void notInlined() {
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestValueConstruction.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestValueConstruction.java
    index ef4d6b2815a9..774888537a8a 100644
    --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestValueConstruction.java
    +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestValueConstruction.java
    @@ -30,6 +30,7 @@
     import java.lang.reflect.Constructor;
     import java.util.Random;
     
    +import jdk.internal.misc.Unsafe;
     import jdk.test.lib.Asserts;
     import jdk.test.lib.Utils;
     import jdk.test.whitebox.WhiteBox;
    @@ -37,9 +38,11 @@
     
     /*
      * @test id=Xbatch
    + * @bug 8396321
      * @summary Test construction of value objects.
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -51,8 +54,10 @@
     
     /*
      * @test id=DeoptimizeALot
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -64,8 +69,10 @@
     
     /*
      * @test id=CompileonlyTest
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -78,9 +85,11 @@
     
     /*
      * @test id=DontInlineHelper
    + * @bug 8396321
      * @summary Test construction of value objects.
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -93,8 +102,10 @@
     
     /*
      * @test id=DontInlineMyValueInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -107,8 +118,10 @@
     
     /*
      * @test id=DontInlineObjectInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -121,8 +134,10 @@
     
     /*
      * @test id=DontInlineObjectInitDeoptimizeALot
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -135,8 +150,10 @@
     
     /*
      * @test id=DontInlineMyAbstractInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires (vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000) | vm.opt.final.StressIncrementalInlining == false
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -149,8 +166,10 @@
     
     /*
      * @test id=StressIncrementalInlining
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -164,8 +183,10 @@
     
     /*
      * @test id=StressIncrementalInliningCompileOnlyTest
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -178,8 +199,10 @@
      */
     
     /* @test id=StressIncrementalInliningDontInlineMyValueInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -193,8 +216,10 @@
     
     /*
      * @test id=StressIncrementalInliningDontInlineObjectInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -208,8 +233,10 @@
     
     /*
      * @test id=StressIncrementalInliningDontInlineMyAbstractInit
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -224,8 +251,10 @@
     
     /*
      * @test id=StressIncrementalInliningOnStackReplacement
    + * @bug 8396321
      * @key randomness
      * @library /testlibrary /test/lib /compiler/whitebox /test/jdk/java/lang/invoke/common /
    + * @modules java.base/jdk.internal.misc
      * @enablePreview
      * @requires vm.opt.final.PerMethodTrapLimit >= 100 & vm.opt.final.PerMethodSpecTrapLimit >= 5000
      * @build jdk.test.whitebox.WhiteBox test.java.lang.invoke.lib.InstructionHelper
    @@ -238,8 +267,17 @@
      *                   compiler.valhalla.valuetypes.TestValueConstruction
      */
     
    +class UnresolvedValue {
    +    static int value;
    +}
    +
     public class TestValueConstruction {
         static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
    +    static final Unsafe UNSAFE = Unsafe.getUnsafe();
    +    static final Object[] ARRAY = new Integer[1];
    +    static final Integer[] UNSAFE_ARRAY = new Integer[1];
    +    static final long UNSAFE_ARRAY_BASE = UNSAFE.arrayInstanceBaseOffset(UNSAFE_ARRAY);
    +    static final int UNSAFE_ARRAY_LAYOUT = UNSAFE.arrayLayout(UNSAFE_ARRAY);
     
         static boolean VERBOSE = false;
         static boolean[] deopt = new boolean[14];
    @@ -1772,6 +1810,121 @@ public static MyValue1 testMethodHandleVar(MethodHandle mh, int x) throws Throwa
             return (MyValue1) mh.invoke(x);
         }
     
    +    // Below tests construct value objects whose aliases are represented by different C2
    +    // nodes and verify that all aliases are correctly scalarized after construction.
    +
    +    static void sink(Integer value) { }
    +
    +    // Pass alias to a non-inlined call
    +    static void testCall(int i) {
    +        do {
    +            sink(new Integer(i < 1 ? 1 : UnresolvedValue.value));
    +        } while (i++ < 0);
    +    }
    +
    +    // Keep alias live through a merge
    +    static Integer testMerge(int i) {
    +        Integer value;
    +        do {
    +            value = new Integer(i < 1 ? 1 : UnresolvedValue.value);
    +            if (i != 0) {
    +                i = 1;
    +            }
    +        } while (i++ < 0);
    +        return value;
    +    }
    +
    +    Integer field;
    +
    +    // Store alias into a field
    +    static Integer testFieldStore(int i) {
    +        TestValueConstruction holder = new TestValueConstruction();
    +        do {
    +            holder.field = new Integer(i < 1 ? 1 : UnresolvedValue.value);
    +        } while (i++ < 0);
    +        return holder.field;
    +    }
    +
    +    // Store alias into a value array
    +    static Object testArrayStore(int i) {
    +        do {
    +            ARRAY[0] = new Integer(i < 1 ? 1 : UnresolvedValue.value);
    +        } while (i++ < 0);
    +        return ARRAY[0];
    +    }
    +
    +    // Pass alias to the flat value store intrinsic
    +    static Integer testUnsafeFlatStore(int i) {
    +        do {
    +            Integer value = new Integer(i < 1 ? 1 : UnresolvedValue.value);
    +            UNSAFE.putFlatValue(UNSAFE_ARRAY, UNSAFE_ARRAY_BASE, UNSAFE_ARRAY_LAYOUT, Integer.class, value);
    +        } while (i++ < 0);
    +        return UNSAFE_ARRAY[0];
    +    }
    +
    +    static DeadLocalValue deadLocal1;
    +    static DeadLocalValue deadLocal2;
    +
    +    static value class DeadLocalValue {
    +        int x;
    +
    +        DeadLocalValue(int x) {
    +            this.x = x;
    +            super();
    +            if (x == 42) {
    +                deadLocal1 = this;
    +            } else if (x == 43) {
    +                deadLocal2 = this;
    +            }
    +        }
    +    }
    +
    +    // Test that C2 does not use a Phi of dead local values to canonicalize distinct live values
    +    private static final MethodHandle DEAD_LOCAL_ALIAS = InstructionHelper.buildMethodHandle(MethodHandles.lookup(),
    +            "deadLocalAlias",
    +            MethodType.methodType(void.class, int.class),
    +            CODE -> {
    +                var deadLocalValueDesc = DeadLocalValue.class.describeConstable().get();
    +                var constructorDesc = MethodType.methodType(void.class, int.class).describeConstable().get();
    +                Label skip = CODE.newLabel();
    +                Label merge = CODE.newLabel();
    +                CODE.
    +                    // DeadLocalValue A is stored in local 2
    +                    new_(deadLocalValueDesc).
    +                    astore(2).
    +                    // DeadLocalValue B is stored in local 3
    +                    new_(deadLocalValueDesc).
    +                    astore(3).
    +                    iload(0).
    +                    ifne(skip).
    +                    // A is stored local 1
    +                    aload(2).
    +                    astore(1).
    +                    goto_(merge).
    +                    labelBinding(skip).
    +                    // B is stored local 1
    +                    aload(3).
    +                    astore(1).
    +                    labelBinding(merge).
    +                    // The verifier does not merge A and B because local 1 is dead here, so its
    +                    // stack-map type is top. But with DeoptimizeALot, C2 still keeps the dead Phi:
    +                    //   Local 1: Phi(A, B)
    +                    //   Local 2: A
    +                    //   Local 3: B
    +                    // ciTypeFlow meets the stale values in local 1 and keeps only one early larval
    +                    // wrapper because both unwrap to the same type. If canonicalization visits
    +                    // the dead local, Phi(A, B) can replace the corresponding live value in
    +                    // local 2 or 3. The different values passed to the constructors below make this
    +                    // observable through deadLocal1 or deadLocal2 which store the escaped values.
    +                    aload(2).
    +                    bipush(42).
    +                    invokespecial(deadLocalValueDesc, "", constructorDesc).
    +                    aload(3).
    +                    bipush(43).
    +                    invokespecial(deadLocalValueDesc, "", constructorDesc).
    +                    return_();
    +            });
    +
         public static void main(String[] args) throws Throwable {
             Random rand = Utils.getRandomInstance();
     
    @@ -1807,6 +1960,11 @@ public static void main(String[] args) throws Throwable {
                     WHITE_BOX.testSetDontInlineMethod(MyAbstract16.class.getConstructor(int.class), rand.nextBoolean());
                 }
             }
    +        // More compiler control needed by some tests
    +        WHITE_BOX.testSetDontInlineMethod(TestValueConstruction.class.getDeclaredMethod("sink", Integer.class), true);
    +        Constructor deadLocalConstructor = DeadLocalValue.class.getDeclaredConstructor(int.class);
    +        WHITE_BOX.testSetDontInlineMethod(deadLocalConstructor, true);
    +        WHITE_BOX.makeMethodNotCompilable(deadLocalConstructor);
     
             Integer deoptNum = Integer.getInteger("deoptNum");
             Integer deoptNumBig = Integer.getInteger("deoptNumBig");
    @@ -1905,6 +2063,19 @@ private static void run(int x, boolean doCheck) throws Throwable {
             check(testReflectionVar(MY_VALUE1_CONSTRUCTOR, x), new MyValue1(x), doCheck);
             check(testMethodHandleCon(x), new MyValue1(x), doCheck);
             check(testMethodHandleVar(MY_VALUE1_CONSTRUCTOR_HANDLE, x), new MyValue1(x), doCheck);
    +        testCall(0);
    +        check(testMerge(0), Integer.valueOf(1), doCheck);
    +        check(testFieldStore(0), Integer.valueOf(1), doCheck);
    +        check(testArrayStore(0), Integer.valueOf(1), doCheck);
    +        if (UNSAFE_ARRAY_LAYOUT != Unsafe.NON_FLAT_LAYOUT) {
    +            check(testUnsafeFlatStore(0), Integer.valueOf(1), doCheck);
    +        }
    +        DEAD_LOCAL_ALIAS.invokeExact(0);
    +        Asserts.assertEQ(deadLocal1.x, 42);
    +        Asserts.assertEQ(deadLocal2.x, 43);
    +        DEAD_LOCAL_ALIAS.invokeExact(1);
    +        Asserts.assertEQ(deadLocal1.x, 42);
    +        Asserts.assertEQ(deadLocal2.x, 43);
         }
     
         private static void check(Object testResult, Object expectedResult, boolean check) {
    diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestVolatileEmptyValueFields.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestVolatileEmptyValueFields.java
    new file mode 100644
    index 000000000000..3a398777abc6
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestVolatileEmptyValueFields.java
    @@ -0,0 +1,92 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +package compiler.valhalla.valuetypes;
    +
    +import compiler.lib.ir_framework.IR;
    +import compiler.lib.ir_framework.IRNode;
    +import compiler.lib.ir_framework.Test;
    +import compiler.lib.ir_framework.TestFramework;
    +import jdk.internal.vm.annotation.NullRestricted;
    +
    +/*
    + * @test
    + * @bug 8397215
    + * @summary Empty value fields must retain volatile accesses and memory barriers
    + * @library /test/lib /
    + * @enablePreview
    + * @modules java.base/jdk.internal.vm.annotation
    + * @run driver ${test.main.class}
    + */
    +public class TestVolatileEmptyValueFields {
    +
    +    public static void main(String[] args) {
    +        new TestFramework().addFlags("--enable-preview",
    +                                     "--add-exports", "java.base/jdk.internal.vm.annotation=ALL-UNNAMED")
    +                           .start();
    +    }
    +
    +    static value class Empty { }
    +    static final Empty EMPTY = new Empty();
    +    static final TestVolatileEmptyValueFields INSTANCE = new TestVolatileEmptyValueFields();
    +
    +    @NullRestricted
    +    volatile Empty instanceField;
    +
    +    @NullRestricted
    +    static volatile Empty staticField = new Empty();
    +
    +    TestVolatileEmptyValueFields() {
    +        instanceField = new Empty();
    +        super();
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.LOAD_OF_FIELD, "instanceField", "1",
    +                  IRNode.MEMBAR_ACQUIRE, "1"})
    +    static Object testInstanceLoad() {
    +        return INSTANCE.instanceField;
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.LOAD_OF_FIELD, "staticField", "1",
    +                  IRNode.MEMBAR_ACQUIRE, "1"})
    +    static Object testStaticLoad() {
    +        return staticField;
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.STORE_OF_FIELD, "instanceField", "1",
    +                  IRNode.MEMBAR_RELEASE, "1"})
    +    static void testInstanceStore() {
    +        INSTANCE.instanceField = EMPTY;
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.STORE_OF_FIELD, "staticField", "1",
    +                  IRNode.MEMBAR_RELEASE, "1"})
    +    static void testStaticStore() {
    +        staticField = EMPTY;
    +    }
    +}
    +
    diff --git a/test/hotspot/jtreg/compiler/vectorapi/TestGFNIUniformByteShift.java b/test/hotspot/jtreg/compiler/vectorapi/TestGFNIUniformByteShift.java
    new file mode 100644
    index 000000000000..9f6ee46a51b4
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/vectorapi/TestGFNIUniformByteShift.java
    @@ -0,0 +1,252 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +package compiler.vectorapi;
    +
    +import compiler.lib.generators.Generator;
    +import compiler.lib.generators.Generators;
    +import compiler.lib.ir_framework.Check;
    +import compiler.lib.ir_framework.CompilePhase;
    +import compiler.lib.ir_framework.IR;
    +import compiler.lib.ir_framework.IRNode;
    +import compiler.lib.ir_framework.CheckAt;
    +import compiler.lib.ir_framework.Test;
    +import compiler.lib.ir_framework.TestFramework;
    +import compiler.lib.verify.Verify;
    +import jdk.incubator.vector.ByteVector;
    +import jdk.incubator.vector.VectorOperators;
    +import jdk.incubator.vector.VectorSpecies;
    +
    +/*
    + * @test id=default
    + * @bug 8393068
    + * @key randomness
    + * @summary Optimize vector byte shift operations using x86 GFNI instructions
    + * @modules jdk.incubator.vector
    + * @library /test/lib /
    + * @requires vm.compiler2.enabled
    + * @run driver ${test.main.class}
    + */
    +
    +/*
    + * @test id=useavx
    + * @bug 8393068
    + * @key randomness
    + * @library /test/lib /
    + * @modules jdk.incubator.vector
    + * @requires vm.compiler2.enabled
    + * @requires os.arch == "amd64" | os.arch == "x86_64"
    + * @run driver ${test.main.class} -XX:UseAVX=0
    + * @run driver ${test.main.class} -XX:UseAVX=1
    + * @run driver ${test.main.class} -XX:UseAVX=2
    + */
    +
    +public class TestGFNIUniformByteShift {
    +    static final VectorSpecies B128 = ByteVector.SPECIES_128;
    +    static final VectorSpecies B256 = ByteVector.SPECIES_256;
    +    static final VectorSpecies B512 = ByteVector.SPECIES_512;
    +
    +    static final int LENGTH = 256;
    +    static final byte[] SRC = new byte[LENGTH];
    +    static final byte[][] LSHL = new byte[8][LENGTH];
    +    static final byte[][] ASHR = new byte[8][LENGTH];
    +    static final byte[][] LSHR = new byte[8][LENGTH];
    +
    +    // Auto-vectorized Java shifts mask the count to 0..31.
    +    static final int SHIFT = 32;
    +    static final int[] OUT_OF_RANGE = {-1, 32, 40, 63};
    +    static final byte[] DST_L = new byte[SHIFT * LENGTH];
    +    static final byte[] DST_A = new byte[SHIFT * LENGTH];
    +    static final byte[][] DST_L_OOR = new byte[OUT_OF_RANGE.length][LENGTH];
    +    static final byte[][] DST_A_OOR = new byte[OUT_OF_RANGE.length][LENGTH];
    +
    +    static final Generators RD = Generators.G;
    +
    +    static {
    +        Generator bytes = RD.ints();
    +        for (int i = 0; i < LENGTH; i++) {
    +            SRC[i] = bytes.next().byteValue();
    +        }
    +    }
    +
    +    public static void main(String[] args) {
    +        TestFramework testFramework = new TestFramework();
    +        testFramework.setDefaultWarmup(10000)
    +                     .addFlags("--add-modules=jdk.incubator.vector")
    +                     .addFlags(args)
    +                     .start();
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.X86_VSHIFT_B_GFNI, ">= 3"},
    +        phase = CompilePhase.FINAL_CODE,
    +        applyIf = {"UseAVX", "> 0"},
    +        applyIfCPUFeatureAnd = {"gfni", "true", "avx", "true"})
    +    public static void test128() {
    +        for (int s = 0; s < 8; s++) {
    +            for (int i = 0; i < LENGTH; i += B128.length()) {
    +                ByteVector v = ByteVector.fromArray(B128, SRC, i);
    +                v.lanewise(VectorOperators.LSHL, s).intoArray(LSHL[s], i);
    +                v.lanewise(VectorOperators.ASHR, s).intoArray(ASHR[s], i);
    +                v.lanewise(VectorOperators.LSHR, s).intoArray(LSHR[s], i);
    +            }
    +        }
    +    }
    +
    +    @Check(test = "test128", when = CheckAt.COMPILED)
    +    public static void check128() {
    +        check();
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.X86_VSHIFT_B_GFNI, ">= 3"},
    +        phase = CompilePhase.FINAL_CODE,
    +        applyIf = {"UseAVX", "> 1"},
    +        applyIfCPUFeatureAnd = {"gfni", "true", "avx2", "true"})
    +    public static void test256() {
    +        for (int s = 0; s < 8; s++) {
    +            for (int i = 0; i < LENGTH; i += B256.length()) {
    +                ByteVector v = ByteVector.fromArray(B256, SRC, i);
    +                v.lanewise(VectorOperators.LSHL, s).intoArray(LSHL[s], i);
    +                v.lanewise(VectorOperators.ASHR, s).intoArray(ASHR[s], i);
    +                v.lanewise(VectorOperators.LSHR, s).intoArray(LSHR[s], i);
    +            }
    +        }
    +    }
    +
    +    @Check(test = "test256", when = CheckAt.COMPILED)
    +    public static void check256() {
    +        check();
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.X86_VSHIFT_B_GFNI, ">= 3"},
    +        phase = CompilePhase.FINAL_CODE,
    +        applyIf = {"UseAVX", "> 2"},
    +        applyIfCPUFeatureAnd = {"gfni", "true", "avx512bw", "true"})
    +    public static void test512() {
    +        for (int s = 0; s < 8; s++) {
    +            for (int i = 0; i < LENGTH; i += B512.length()) {
    +                ByteVector v = ByteVector.fromArray(B512, SRC, i);
    +                v.lanewise(VectorOperators.LSHL, s).intoArray(LSHL[s], i);
    +                v.lanewise(VectorOperators.ASHR, s).intoArray(ASHR[s], i);
    +                v.lanewise(VectorOperators.LSHR, s).intoArray(LSHR[s], i);
    +            }
    +        }
    +    }
    +
    +    @Check(test = "test512", when = CheckAt.COMPILED)
    +    public static void check512() {
    +        check();
    +    }
    +
    +    static void check() {
    +        for (int s = 0; s < 8; s++) {
    +            byte[] expL = new byte[LENGTH];
    +            byte[] expA = new byte[LENGTH];
    +            byte[] expU = new byte[LENGTH];
    +            for (int i = 0; i < LENGTH; i++) {
    +                int x = SRC[i];
    +                expL[i] = (byte) (x << s);
    +                expA[i] = (byte) (x >> s);
    +                expU[i] = (byte) ((x & 0xff) >>> s);
    +            }
    +            Verify.checkEQ(LSHL[s], expL);
    +            Verify.checkEQ(ASHR[s], expA);
    +            Verify.checkEQ(LSHR[s], expU);
    +        }
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.X86_VSHIFT_B_GFNI, ">= 1"},
    +        phase = CompilePhase.FINAL_CODE,
    +        applyIf = {"UseAVX", "> 0"},
    +        applyIfCPUFeatureAnd = {"gfni", "true", "avx", "true"})
    +    public static void testAutoVecLogicalLeftShift() {
    +        for (int s = 0; s < SHIFT; s++) {
    +            int base = s * LENGTH;
    +            for (int i = 0; i < LENGTH; i++) {
    +                DST_L[base + i] = (byte) (SRC[i] << s);
    +            }
    +        }
    +        for (int k = 0; k < OUT_OF_RANGE.length; k++) {
    +            int s = OUT_OF_RANGE[k];
    +            for (int i = 0; i < LENGTH; i++) {
    +                DST_L_OOR[k][i] = (byte) (SRC[i] << s);
    +            }
    +        }
    +    }
    +
    +    @Check(test = "testAutoVecLogicalLeftShift", when = CheckAt.COMPILED)
    +    public static void checkAutoVecLogicalLeftShift() {
    +        checkVariableShiftForAllCounts(DST_L, DST_L_OOR, true);
    +    }
    +
    +    @Test
    +    @IR(counts = {IRNode.X86_VSHIFT_B_GFNI, ">= 1"},
    +        phase = CompilePhase.FINAL_CODE,
    +        applyIf = {"UseAVX", "> 0"},
    +        applyIfCPUFeatureAnd = {"gfni", "true", "avx", "true"})
    +    public static void testAutoVecArithmeticRightShift() {
    +        for (int s = 0; s < SHIFT; s++) {
    +            int base = s * LENGTH;
    +            for (int i = 0; i < LENGTH; i++) {
    +                DST_A[base + i] = (byte) (SRC[i] >> s);
    +            }
    +        }
    +        for (int k = 0; k < OUT_OF_RANGE.length; k++) {
    +            int s = OUT_OF_RANGE[k];
    +            for (int i = 0; i < LENGTH; i++) {
    +                DST_A_OOR[k][i] = (byte) (SRC[i] >> s);
    +            }
    +        }
    +    }
    +
    +    @Check(test = "testAutoVecArithmeticRightShift", when = CheckAt.COMPILED)
    +    public static void checkAutoVecArithmeticRightShift() {
    +        checkVariableShiftForAllCounts(DST_A, DST_A_OOR, false);
    +    }
    +
    +    static void checkVariableShiftForAllCounts(byte[] actual, byte[][] actualOutOfRange, boolean leftShift) {
    +        for (int s = 0; s < SHIFT; s++) {
    +            int base = s * LENGTH;
    +            byte[] ref = new byte[LENGTH];
    +            byte[] slice = new byte[LENGTH];
    +            for (int i = 0; i < LENGTH; i++) {
    +                int x = SRC[i];
    +                ref[i] = leftShift ? (byte) (x << s) : (byte) (x >> s);
    +                slice[i] = actual[base + i];
    +            }
    +            Verify.checkEQ(slice, ref);
    +        }
    +        for (int k = 0; k < OUT_OF_RANGE.length; k++) {
    +            int s = OUT_OF_RANGE[k];
    +            byte[] ref = new byte[LENGTH];
    +            for (int i = 0; i < LENGTH; i++) {
    +                int x = SRC[i];
    +                ref[i] = leftShift ? (byte) (x << s) : (byte) (x >> s);
    +            }
    +            Verify.checkEQ(actualOutOfRange[k], ref);
    +        }
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/vectorapi/VectorGatherMaskFoldingTest.java b/test/hotspot/jtreg/compiler/vectorapi/VectorGatherMaskFoldingTest.java
    index 7e16c5e5e864..040df3ace326 100644
    --- a/test/hotspot/jtreg/compiler/vectorapi/VectorGatherMaskFoldingTest.java
    +++ b/test/hotspot/jtreg/compiler/vectorapi/VectorGatherMaskFoldingTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -156,7 +156,7 @@ public class VectorGatherMaskFoldingTest {
         // LongVector tests
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherNotEqualArray() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray2, 0, longIndices, 0);
    @@ -164,7 +164,7 @@ public static void testTwoLongVectorLoadGatherNotEqualArray() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherNotEqualIndices() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices2, 0);
    @@ -172,7 +172,7 @@ public static void testTwoLongVectorLoadGatherNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_L, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_L, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadGather() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
    @@ -180,7 +180,7 @@ public static void testOneLongVectorLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_L, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_L, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadMasked() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
    @@ -188,7 +188,7 @@ public static void testOneLongVectorLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherEquals() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
    @@ -196,7 +196,7 @@ public static void testTwoLongVectorLoadGatherEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadMaskedEquals() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
    @@ -204,7 +204,7 @@ public static void testTwoLongVectorLoadMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadMaskedNotEqualMask() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask2);
    @@ -212,7 +212,7 @@ public static void testTwoLongVectorLoadMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherMaskedEquals() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0, longVectorMask);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0, longVectorMask);
    @@ -220,7 +220,7 @@ public static void testTwoLongVectorLoadGatherMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherMaskedNotEqualMask() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0, longVectorMask);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0, longVectorMask2);
    @@ -228,7 +228,7 @@ public static void testTwoLongVectorLoadGatherMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorLoadGatherMaskedNotEqualIndices() {
             LongVector res = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0, longVectorMask);
             LongVector res2 = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices2, 0, longVectorMask);
    @@ -239,7 +239,7 @@ public static void testTwoLongVectorLoadGatherMaskedNotEqualIndices() {
         // IntVector tests
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherNotEqualArray() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray2, 0, intIndices, 0);
    @@ -247,7 +247,7 @@ public static void testTwoIntVectorLoadGatherNotEqualArray() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherNotEqualIndices() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices2, 0);
    @@ -255,7 +255,7 @@ public static void testTwoIntVectorLoadGatherNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_I, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_I, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadGather() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
    @@ -263,7 +263,7 @@ public static void testOneIntVectorLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_I, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_I, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadMasked() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
    @@ -271,7 +271,7 @@ public static void testOneIntVectorLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherEquals() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
    @@ -279,7 +279,7 @@ public static void testTwoIntVectorLoadGatherEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadMaskedEquals() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
    @@ -287,7 +287,7 @@ public static void testTwoIntVectorLoadMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadMaskedNotEqualMask() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask2);
    @@ -295,7 +295,7 @@ public static void testTwoIntVectorLoadMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherMaskedEquals() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0, intVectorMask);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0, intVectorMask);
    @@ -303,7 +303,7 @@ public static void testTwoIntVectorLoadGatherMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherMaskedNotEqualMask() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0, intVectorMask);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0, intVectorMask2);
    @@ -311,7 +311,7 @@ public static void testTwoIntVectorLoadGatherMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorLoadGatherMaskedNotEqualIndices() {
             IntVector res = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0, intVectorMask);
             IntVector res2 = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices2, 0, intVectorMask);
    @@ -322,7 +322,7 @@ public static void testTwoIntVectorLoadGatherMaskedNotEqualIndices() {
         // DoubleVector tests
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherNotEqualArray() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray2, 0, doubleIndices, 0);
    @@ -330,7 +330,7 @@ public static void testTwoDoubleVectorLoadGatherNotEqualArray() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherNotEqualIndices() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices2, 0);
    @@ -338,7 +338,7 @@ public static void testTwoDoubleVectorLoadGatherNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_D, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_D, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadGather() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
    @@ -346,7 +346,7 @@ public static void testOneDoubleVectorLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_D, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_D, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadMasked() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
    @@ -354,7 +354,7 @@ public static void testOneDoubleVectorLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherEquals() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
    @@ -362,7 +362,7 @@ public static void testTwoDoubleVectorLoadGatherEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadMaskedEquals() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
    @@ -370,7 +370,7 @@ public static void testTwoDoubleVectorLoadMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadMaskedNotEqualMask() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask2);
    @@ -378,7 +378,7 @@ public static void testTwoDoubleVectorLoadMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherMaskedEquals() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0, doubleVectorMask);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0, doubleVectorMask);
    @@ -386,7 +386,7 @@ public static void testTwoDoubleVectorLoadGatherMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherMaskedNotEqualMask() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0, doubleVectorMask);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0, doubleVectorMask2);
    @@ -394,7 +394,7 @@ public static void testTwoDoubleVectorLoadGatherMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorLoadGatherMaskedNotEqualIndices() {
             DoubleVector res = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0, doubleVectorMask);
             DoubleVector res2 = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices2, 0, doubleVectorMask);
    @@ -405,7 +405,7 @@ public static void testTwoDoubleVectorLoadGatherMaskedNotEqualIndices() {
         // FloatVector tests
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherNotEqualArray() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray2, 0, floatIndices, 0);
    @@ -413,7 +413,7 @@ public static void testTwoFloatVectorLoadGatherNotEqualArray() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherNotEqualIndices() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices2, 0);
    @@ -421,7 +421,7 @@ public static void testTwoFloatVectorLoadGatherNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_F, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_F, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadGather() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
    @@ -429,7 +429,7 @@ public static void testOneFloatVectorLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_F, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_F, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadMasked() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
    @@ -437,7 +437,7 @@ public static void testOneFloatVectorLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherEquals() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
    @@ -445,7 +445,7 @@ public static void testTwoFloatVectorLoadGatherEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadMaskedEquals() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
    @@ -453,7 +453,7 @@ public static void testTwoFloatVectorLoadMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx2", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadMaskedNotEqualMask() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask2);
    @@ -461,7 +461,7 @@ public static void testTwoFloatVectorLoadMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherMaskedEquals() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0, floatVectorMask);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0, floatVectorMask);
    @@ -469,7 +469,7 @@ public static void testTwoFloatVectorLoadGatherMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherMaskedNotEqualMask() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0, floatVectorMask);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0, floatVectorMask2);
    @@ -477,7 +477,7 @@ public static void testTwoFloatVectorLoadGatherMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.LOAD_VECTOR_GATHER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorLoadGatherMaskedNotEqualIndices() {
             FloatVector res = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0, floatVectorMask);
             FloatVector res2 = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices2, 0, floatVectorMask);
    @@ -490,7 +490,7 @@ public static void testTwoFloatVectorLoadGatherMaskedNotEqualIndices() {
         // LongVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterNotEqualVector() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -500,7 +500,7 @@ public static void testTwoLongVectorStoreScatterNotEqualVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterNotEqualIndices() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -510,7 +510,7 @@ public static void testTwoLongVectorStoreScatterNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreScatter() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -520,7 +520,7 @@ public static void testOneLongVectorStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreMasked() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -530,7 +530,7 @@ public static void testOneLongVectorStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterEquals() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -540,7 +540,7 @@ public static void testTwoLongVectorStoreScatterEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreMaskedEquals() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -550,7 +550,7 @@ public static void testTwoLongVectorStoreMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreMaskedNotEqualMask() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -560,7 +560,7 @@ public static void testTwoLongVectorStoreMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterMaskedEquals() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -570,7 +570,7 @@ public static void testTwoLongVectorStoreScatterMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterMaskedNotEqualMask() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -580,7 +580,7 @@ public static void testTwoLongVectorStoreScatterMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoLongVectorStoreScatterMaskedNotEqualIndices() {
             long[] res = new long[L_SPECIES.length()];
             long[] res2 = new long[L_SPECIES.length()];
    @@ -593,7 +593,7 @@ public static void testTwoLongVectorStoreScatterMaskedNotEqualIndices() {
         // IntVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterNotEqualVector() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -603,7 +603,7 @@ public static void testTwoIntVectorStoreScatterNotEqualVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterNotEqualIndices() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -613,7 +613,7 @@ public static void testTwoIntVectorStoreScatterNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreScatter() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -623,7 +623,7 @@ public static void testOneIntVectorStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreMasked() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -633,7 +633,7 @@ public static void testOneIntVectorStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterEquals() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -643,7 +643,7 @@ public static void testTwoIntVectorStoreScatterEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreMaskedEquals() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -653,7 +653,7 @@ public static void testTwoIntVectorStoreMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreMaskedNotEqualMask() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -663,7 +663,7 @@ public static void testTwoIntVectorStoreMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterMaskedEquals() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -673,7 +673,7 @@ public static void testTwoIntVectorStoreScatterMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterMaskedNotEqualMask() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -683,7 +683,7 @@ public static void testTwoIntVectorStoreScatterMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoIntVectorStoreScatterMaskedNotEqualIndices() {
             int[] res = new int[I_SPECIES.length()];
             int[] res2 = new int[I_SPECIES.length()];
    @@ -696,7 +696,7 @@ public static void testTwoIntVectorStoreScatterMaskedNotEqualIndices() {
         // DoubleVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterNotEqualVector() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -706,7 +706,7 @@ public static void testTwoDoubleVectorStoreScatterNotEqualVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterNotEqualIndices() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -716,7 +716,7 @@ public static void testTwoDoubleVectorStoreScatterNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreScatter() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -726,7 +726,7 @@ public static void testOneDoubleVectorStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreMasked() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -736,7 +736,7 @@ public static void testOneDoubleVectorStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterEquals() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -746,7 +746,7 @@ public static void testTwoDoubleVectorStoreScatterEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreMaskedEquals() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -756,7 +756,7 @@ public static void testTwoDoubleVectorStoreMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreMaskedNotEqualMask() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -766,7 +766,7 @@ public static void testTwoDoubleVectorStoreMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterMaskedEquals() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -776,7 +776,7 @@ public static void testTwoDoubleVectorStoreScatterMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterMaskedNotEqualMask() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -786,7 +786,7 @@ public static void testTwoDoubleVectorStoreScatterMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoDoubleVectorStoreScatterMaskedNotEqualIndices() {
             double[] res = new double[D_SPECIES.length()];
             double[] res2 = new double[D_SPECIES.length()];
    @@ -799,7 +799,7 @@ public static void testTwoDoubleVectorStoreScatterMaskedNotEqualIndices() {
         // FloatVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterNotEqualVector() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -809,7 +809,7 @@ public static void testTwoFloatVectorStoreScatterNotEqualVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterNotEqualIndices() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -819,7 +819,7 @@ public static void testTwoFloatVectorStoreScatterNotEqualIndices() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreScatter() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -829,7 +829,7 @@ public static void testOneFloatVectorStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreMasked() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -839,7 +839,7 @@ public static void testOneFloatVectorStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterEquals() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -849,7 +849,7 @@ public static void testTwoFloatVectorStoreScatterEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreMaskedEquals() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -859,7 +859,7 @@ public static void testTwoFloatVectorStoreMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreMaskedNotEqualMask() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -869,7 +869,7 @@ public static void testTwoFloatVectorStoreMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterMaskedEquals() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -879,7 +879,7 @@ public static void testTwoFloatVectorStoreScatterMaskedEquals() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterMaskedNotEqualMask() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -889,7 +889,7 @@ public static void testTwoFloatVectorStoreScatterMaskedNotEqualMask() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER_MASKED, ">= 2" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testTwoFloatVectorStoreScatterMaskedNotEqualIndices() {
             float[] res = new float[F_SPECIES.length()];
             float[] res2 = new float[F_SPECIES.length()];
    @@ -904,7 +904,7 @@ public static void testTwoFloatVectorStoreScatterMaskedNotEqualIndices() {
         // LongVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreLoadGather() {
             long[] array = new long[L_SPECIES.length()];
             longVector.intoArray(array, 0);
    @@ -913,7 +913,7 @@ public static void testOneLongVectorStoreLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreScatterLoad() {
             long[] array = new long[L_SPECIES.length()];
             longVector.intoArray(array, 0, longIndices, 0);
    @@ -922,7 +922,7 @@ public static void testOneLongVectorStoreScatterLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreLoadMasked() {
             long[] array = new long[L_SPECIES.length()];
             longVector.intoArray(array, 0);
    @@ -931,7 +931,7 @@ public static void testOneLongVectorStoreLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorStoreMaskedLoad() {
             long[] array = new long[L_SPECIES.length()];
             longVector.intoArray(array, 0, longVectorMask);
    @@ -940,7 +940,7 @@ public static void testOneLongVectorStoreMaskedLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testLongVectorLoadGatherStoreScatterDuplicateIndicesVector() {
             long[] res = new long[L_SPECIES.length()];
             longVector.intoArray(res, 0, duplicateLongIndices, 0);
    @@ -949,7 +949,7 @@ public static void testLongVectorLoadGatherStoreScatterDuplicateIndicesVector()
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testLongVectorStoreLoadMaskedVector() {
             long[] res = new long[L_SPECIES.length()];
             longVector.intoArray(res, 0, longVectorMask);
    @@ -958,7 +958,7 @@ public static void testLongVectorStoreLoadMaskedVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testStoreLoadLongVectorDifferentSpeciesVector() {
             long[] res = new long[L_SPECIES.length()];
             longVector.intoArray(res, 0);
    @@ -970,7 +970,7 @@ public static void testStoreLoadLongVectorDifferentSpeciesVector() {
         // IntVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreLoadGather() {
             int[] array = new int[I_SPECIES.length()];
             intVector.intoArray(array, 0);
    @@ -979,7 +979,7 @@ public static void testOneIntVectorStoreLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreScatterLoad() {
             int[] array = new int[I_SPECIES.length()];
             intVector.intoArray(array, 0, intIndices, 0);
    @@ -988,7 +988,7 @@ public static void testOneIntVectorStoreScatterLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreLoadMasked() {
             int[] array = new int[I_SPECIES.length()];
             intVector.intoArray(array, 0);
    @@ -997,7 +997,7 @@ public static void testOneIntVectorStoreLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorStoreMaskedLoad() {
             int[] array = new int[I_SPECIES.length()];
             intVector.intoArray(array, 0, intVectorMask);
    @@ -1006,7 +1006,7 @@ public static void testOneIntVectorStoreMaskedLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testIntVectorLoadGatherStoreScatterDuplicateIndicesVector() {
             int[] res = new int[I_SPECIES.length()];
             intVector.intoArray(res, 0, duplicateIntIndices, 0);
    @@ -1015,7 +1015,7 @@ public static void testIntVectorLoadGatherStoreScatterDuplicateIndicesVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testIntVectorStoreLoadMaskedVector() {
             int[] res = new int[I_SPECIES.length()];
             intVector.intoArray(res, 0, intVectorMask);
    @@ -1024,7 +1024,7 @@ public static void testIntVectorStoreLoadMaskedVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testStoreLoadIntVectorDifferentSpeciesVector() {
             int[] res = new int[I_SPECIES.length()];
             intVector.intoArray(res, 0);
    @@ -1036,7 +1036,7 @@ public static void testStoreLoadIntVectorDifferentSpeciesVector() {
         // DoubleVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreLoadGather() {
             double[] array = new double[D_SPECIES.length()];
             doubleVector.intoArray(array, 0);
    @@ -1045,7 +1045,7 @@ public static void testOneDoubleVectorStoreLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreScatterLoad() {
             double[] array = new double[D_SPECIES.length()];
             doubleVector.intoArray(array, 0, doubleIndices, 0);
    @@ -1054,7 +1054,7 @@ public static void testOneDoubleVectorStoreScatterLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreLoadMasked() {
             double[] array = new double[D_SPECIES.length()];
             doubleVector.intoArray(array, 0);
    @@ -1063,7 +1063,7 @@ public static void testOneDoubleVectorStoreLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorStoreMaskedLoad() {
             double[] array = new double[D_SPECIES.length()];
             doubleVector.intoArray(array, 0, doubleVectorMask);
    @@ -1072,7 +1072,7 @@ public static void testOneDoubleVectorStoreMaskedLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testDoubleVectorLoadGatherStoreScatterDuplicateIndicesVector() {
             double[] res = new double[D_SPECIES.length()];
             doubleVector.intoArray(res, 0, duplicateDoubleIndices, 0);
    @@ -1081,7 +1081,7 @@ public static void testDoubleVectorLoadGatherStoreScatterDuplicateIndicesVector(
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testDoubleVectorStoreLoadMaskedVector() {
             double[] res = new double[D_SPECIES.length()];
             doubleVector.intoArray(res, 0, doubleVectorMask);
    @@ -1090,7 +1090,7 @@ public static void testDoubleVectorStoreLoadMaskedVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testStoreLoadDoubleVectorDifferentSpeciesVector() {
             double[] res = new double[D_SPECIES.length()];
             doubleVector.intoArray(res, 0);
    @@ -1102,7 +1102,7 @@ public static void testStoreLoadDoubleVectorDifferentSpeciesVector() {
         // FloatVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreLoadGather() {
             float[] array = new float[F_SPECIES.length()];
             floatVector.intoArray(array, 0);
    @@ -1111,7 +1111,7 @@ public static void testOneFloatVectorStoreLoadGather() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreScatterLoad() {
             float[] array = new float[F_SPECIES.length()];
             floatVector.intoArray(array, 0, floatIndices, 0);
    @@ -1120,7 +1120,7 @@ public static void testOneFloatVectorStoreScatterLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreLoadMasked() {
             float[] array = new float[F_SPECIES.length()];
             floatVector.intoArray(array, 0);
    @@ -1129,7 +1129,7 @@ public static void testOneFloatVectorStoreLoadMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorStoreMaskedLoad() {
             float[] array = new float[F_SPECIES.length()];
             floatVector.intoArray(array, 0, floatVectorMask);
    @@ -1138,7 +1138,7 @@ public static void testOneFloatVectorStoreMaskedLoad() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testFloatVectorLoadGatherStoreScatterDuplicateIndicesVector() {
             float[] res = new float[F_SPECIES.length()];
             floatVector.intoArray(res, 0, duplicateFloatIndices, 0);
    @@ -1147,7 +1147,7 @@ public static void testFloatVectorLoadGatherStoreScatterDuplicateIndicesVector()
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testFloatVectorStoreLoadMaskedVector() {
             float[] res = new float[F_SPECIES.length()];
             floatVector.intoArray(res, 0, floatVectorMask);
    @@ -1156,7 +1156,7 @@ public static void testFloatVectorStoreLoadMaskedVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testStoreLoadFloatVectorDifferentSpeciesVector() {
             float[] res = new float[F_SPECIES.length()];
             floatVector.intoArray(res, 0);
    @@ -1170,7 +1170,7 @@ public static void testStoreLoadFloatVectorDifferentSpeciesVector() {
         // LongVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadGatherStore() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0, longIndices, 0);
    @@ -1179,7 +1179,7 @@ public static void testOneLongVectorLoadGatherStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadStoreScatter() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0);
    @@ -1188,7 +1188,7 @@ public static void testOneLongVectorLoadStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadMaskedStore() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
    @@ -1197,7 +1197,7 @@ public static void testOneLongVectorLoadMaskedStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_L, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneLongVectorLoadStoreMasked() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0);
    @@ -1206,7 +1206,7 @@ public static void testOneLongVectorLoadStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testLongVectorStoreScatterLoadGatherDuplicateIndicesVector() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0, duplicateLongIndices, 0);
    @@ -1215,7 +1215,7 @@ public static void testLongVectorStoreScatterLoadGatherDuplicateIndicesVector()
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testLongVectorLoadMaskedStoreVector() {
             long[] res = new long[L_SPECIES.length()];
             LongVector vector = LongVector.fromArray(L_SPECIES, longArray, 0, longVectorMask);
    @@ -1227,7 +1227,7 @@ public static void testLongVectorLoadMaskedStoreVector() {
         // IntVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadGatherStore() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0, intIndices, 0);
    @@ -1236,7 +1236,7 @@ public static void testOneIntVectorLoadGatherStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadStoreScatter() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0);
    @@ -1245,7 +1245,7 @@ public static void testOneIntVectorLoadStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadMaskedStore() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
    @@ -1254,7 +1254,7 @@ public static void testOneIntVectorLoadMaskedStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_I, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneIntVectorLoadStoreMasked() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0);
    @@ -1263,7 +1263,7 @@ public static void testOneIntVectorLoadStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testIntVectorStoreScatterLoadGatherDuplicateIndicesVector() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0, duplicateIntIndices, 0);
    @@ -1272,7 +1272,7 @@ public static void testIntVectorStoreScatterLoadGatherDuplicateIndicesVector() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testIntVectorLoadMaskedStoreVector() {
             int[] res = new int[I_SPECIES.length()];
             IntVector vector = IntVector.fromArray(I_SPECIES, intArray, 0, intVectorMask);
    @@ -1284,7 +1284,7 @@ public static void testIntVectorLoadMaskedStoreVector() {
         // DoubleVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadGatherStore() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleIndices, 0);
    @@ -1293,7 +1293,7 @@ public static void testOneDoubleVectorLoadGatherStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadStoreScatter() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0);
    @@ -1302,7 +1302,7 @@ public static void testOneDoubleVectorLoadStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadMaskedStore() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
    @@ -1311,7 +1311,7 @@ public static void testOneDoubleVectorLoadMaskedStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_D, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneDoubleVectorLoadStoreMasked() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0);
    @@ -1320,7 +1320,7 @@ public static void testOneDoubleVectorLoadStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testDoubleVectorStoreScatterLoadGatherDuplicateIndicesVector() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, duplicateDoubleIndices, 0);
    @@ -1329,7 +1329,7 @@ public static void testDoubleVectorStoreScatterLoadGatherDuplicateIndicesVector(
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testDoubleVectorLoadMaskedStoreVector() {
             double[] res = new double[D_SPECIES.length()];
             DoubleVector vector = DoubleVector.fromArray(D_SPECIES, doubleArray, 0, doubleVectorMask);
    @@ -1341,7 +1341,7 @@ public static void testDoubleVectorLoadMaskedStoreVector() {
         // FloatVector tests
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadGatherStore() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatIndices, 0);
    @@ -1350,7 +1350,7 @@ public static void testOneFloatVectorLoadGatherStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadStoreScatter() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0);
    @@ -1359,7 +1359,7 @@ public static void testOneFloatVectorLoadStoreScatter() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadMaskedStore() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
    @@ -1368,7 +1368,7 @@ public static void testOneFloatVectorLoadMaskedStore() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_F, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testOneFloatVectorLoadStoreMasked() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0);
    @@ -1377,7 +1377,7 @@ public static void testOneFloatVectorLoadStoreMasked() {
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_SCATTER, ">= 1", IRNode.LOAD_VECTOR_GATHER, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testFloatVectorStoreScatterLoadGatherDuplicateIndicesVector() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0, duplicateFloatIndices, 0);
    @@ -1386,7 +1386,7 @@ public static void testFloatVectorStoreScatterLoadGatherDuplicateIndicesVector()
         }
     
         @Test
    -    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true"})
    +    @IR(counts = { IRNode.STORE_VECTOR_MASKED, ">= 1", IRNode.LOAD_VECTOR_MASKED, ">= 1" }, applyIfCPUFeatureOr = {"avx512", "true", "sve", "true", "rvv", "true"})
         public static void testFloatVectorLoadMaskedStoreVector() {
             float[] res = new float[F_SPECIES.length()];
             FloatVector vector = FloatVector.fromArray(F_SPECIES, floatArray, 0, floatVectorMask);
    diff --git a/test/hotspot/jtreg/compiler/vectorapi/VectorGatherScatterTest.java b/test/hotspot/jtreg/compiler/vectorapi/VectorGatherScatterTest.java
    index 4298f1d7000e..7d089d219665 100644
    --- a/test/hotspot/jtreg/compiler/vectorapi/VectorGatherScatterTest.java
    +++ b/test/hotspot/jtreg/compiler/vectorapi/VectorGatherScatterTest.java
    @@ -35,6 +35,7 @@
     import jdk.incubator.vector.VectorSpecies;
     
     import jdk.test.lib.Asserts;
    +import jdk.test.lib.Platform;
     import jdk.test.lib.Utils;
     
     /**
    @@ -42,8 +43,9 @@
      * @bug 8288397
      * @key randomness
      * @library /test/lib /
    - * @requires vm.cpu.features ~= ".*sve.*" & (vm.opt.MaxVectorSize == "null" | vm.opt.MaxVectorSize >= 16)
    - * @summary AArch64: Fix register issues in SVE backend match rules
    + * @requires (vm.cpu.features ~= ".*sve.*" & (vm.opt.MaxVectorSize == "null" | vm.opt.MaxVectorSize >= 16)) |
    + *            vm.cpu.features ~= ".*rvv.*"
    + * @summary Test vector gather/scatter on SVE and RVV
      * @modules jdk.incubator.vector
      *
      * @run driver compiler.vectorapi.VectorGatherScatterTest
    @@ -146,7 +148,11 @@ public static void testStoreScatterMasked() {
         }
     
         public static void main(String[] args) {
    -        TestFramework.runWithFlags("--add-modules=jdk.incubator.vector",
    -                                   "-XX:UseSVE=1");
    +        TestFramework testFramework = new TestFramework();
    +        testFramework.addFlags("--add-modules=jdk.incubator.vector");
    +        if (Platform.isAArch64()) {
    +            testFramework.addFlags("-XX:UseSVE=1");
    +        }
    +        testFramework.start();
         }
     }
    diff --git a/test/hotspot/jtreg/compiler/vectorization/TestVmlaAArch64.java b/test/hotspot/jtreg/compiler/vectorization/TestVmlaAArch64.java
    new file mode 100644
    index 000000000000..052c470882eb
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/vectorization/TestVmlaAArch64.java
    @@ -0,0 +1,443 @@
    +/*
    + * Copyright 2026 Arm Limited and/or its affiliates.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/**
    + * @test
    + * @bug 8372153
    + * @summary AArch64: Performance regression in long reduction microbenchmarks after JDK-8340093
    + * @requires vm.compiler2.enabled
    + * @modules jdk.incubator.vector
    + * @library /test/lib /
    + * @run driver compiler.vectorization.TestVmlaAArch64
    + */
    +
    +package compiler.vectorization;
    +
    +import compiler.lib.ir_framework.*;
    +
    +import jdk.incubator.vector.LongVector;
    +import jdk.incubator.vector.VectorMask;
    +import jdk.incubator.vector.VectorOperators;
    +import jdk.incubator.vector.VectorSpecies;
    +
    +import jdk.test.lib.Asserts;
    +import jdk.test.lib.Platform;
    +
    +public class TestVmlaAArch64 {
    +  private static final int ARRLEN = 1024;
    +  private static final int ITERS  = 11000;
    +  private static final VectorSpecies SPECIES_128 = LongVector.SPECIES_128;
    +
    +  private static long[] a;
    +  private static long[] b;
    +  private static long[] c;
    +  private static VectorMask mask;
    +
    +  public static void main(String args[]) {
    +      if (Platform.isAArch64()) {
    +          TestFramework.runWithFlags("--add-modules=jdk.incubator.vector", "-XX:-AvoidMLAChain");
    +          TestFramework.runWithFlags("--add-modules=jdk.incubator.vector", "-XX:+AvoidMLAChain");
    +      } else {
    +          TestFramework.runWithFlags("--add-modules=jdk.incubator.vector");
    +      }
    +      System.out.println("PASSED");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIfAnd = {"MaxVectorSize", "<= 16", "AvoidMLAChain", "true"},
    +      counts = {IRNode.VMLA, "=0"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLA, ">0"})
    +  public long vector_add_dot_product() {
    +      long res = 0L;
    +      for (int i = 0; i < a.length; i++) {
    +          long val = a[i] * b[i];
    +          res += val;
    +      }
    +      return res;
    +  }
    +
    +  @Run(test = {"vector_add_dot_product"}, mode = RunMode.STANDALONE)
    +  public void test_vector_add_dot_product() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          expected += a[i] * b[i];
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_add_dot_product();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_add_dot_product");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIfAnd = {"MaxVectorSize", "<= 16", "AvoidMLAChain", "true"},
    +      counts = {IRNode.VMLS, "=0"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLS, ">0"})
    +  public long vector_sub_dot_product() {
    +      long res = 0L;
    +      for (int i = 0; i < a.length; i++) {
    +          long val = (a[i] * b[i]) + (a[i] * c[i]) - (b[i] * c[i]);
    +          res += val;
    +      }
    +      return res;
    +  }
    +
    +  @Run(test = {"vector_sub_dot_product"}, mode = RunMode.STANDALONE)
    +  public void test_vector_sub_dot_product() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      c = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          c[i] = i;
    +          expected += (a[i] * b[i]) + (a[i] * c[i]) - (b[i] * c[i]);
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_sub_dot_product();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_sub_dot_product");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      // The peeled first iteration generates one VMLA, but the main loop should not.
    +      counts = {IRNode.VMLA, "=1"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLA, ">0"})
    +  public long vector_api_add_dot_product() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          acc = acc.add(av.mul(bv));
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"vector_api_add_dot_product"}, mode = RunMode.STANDALONE)
    +  public void test_vector_api_add_dot_product() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          expected += a[i] * b[i];
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_api_add_dot_product();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_api_add_dot_product");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      // The peeled first iteration generates one VMLS, but the main loop should not.
    +      counts = {IRNode.VMLS, "=1"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLS, ">0"})
    +  public long vector_api_sub_dot_product() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          acc = acc.sub(av.mul(bv));
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"vector_api_sub_dot_product"}, mode = RunMode.STANDALONE)
    +  public void test_vector_api_sub_dot_product() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          expected -= a[i] * b[i];
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_api_sub_dot_product();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_api_sub_dot_product");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      // The peeled first iteration generates one VMLA, but the main loop should not.
    +      counts = {IRNode.VMLA_MASKED, "=1"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLA_MASKED, ">0"})
    +  public long vector_api_add_dot_product_masked() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          acc = acc.add(av.mul(bv), mask);
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"vector_api_add_dot_product_masked"}, mode = RunMode.STANDALONE)
    +  public void test_vector_api_add_dot_product_masked() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      mask = VectorMask.fromLong(SPECIES_128, 1);
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          if (mask.laneIsSet(i % SPECIES_128.length())) {
    +              expected += a[i] * b[i];
    +          }
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_api_add_dot_product_masked();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_api_add_dot_product_masked");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      // The peeled first iteration generates one VMLS, but the main loop should not.
    +      counts = {IRNode.VMLS_MASKED, "=1"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLS_MASKED, ">0"})
    +  public long vector_api_sub_dot_product_masked() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          acc = acc.sub(av.mul(bv), mask);
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"vector_api_sub_dot_product_masked"}, mode = RunMode.STANDALONE)
    +  public void test_vector_api_sub_dot_product_masked() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      mask = VectorMask.fromLong(SPECIES_128, 1);
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          if (mask.laneIsSet(i % SPECIES_128.length())) {
    +              expected -= a[i] * b[i];
    +          }
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_api_sub_dot_product_masked();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_api_sub_dot_product_masked");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      counts = {IRNode.VMLA, ">0"})
    +  public long vector_mul_add_shared() {
    +      long res = 0L;
    +      for (int i = 0; i < a.length; i++) {
    +          long val = a[i] * b[i];
    +          res += val + val * c[i];
    +      }
    +      return res;
    +  }
    +
    +  @Run(test = {"vector_mul_add_shared"}, mode = RunMode.STANDALONE)
    +  public void test_vector_mul_add_shared() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      c = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          c[i] = i;
    +          long val = a[i] * b[i];
    +          expected += val + val * c[i];
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_mul_add_shared();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_mul_add_shared");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      counts = {IRNode.VMLS, ">0"})
    +  public long vector_mul_sub_shared() {
    +      long res = 0L;
    +      for (int i = 0; i < a.length; i++) {
    +          long val = a[i] * b[i];
    +          res += val - val * c[i];
    +      }
    +      return res;
    +  }
    +
    +  @Run(test = {"vector_mul_sub_shared"}, mode = RunMode.STANDALONE)
    +  public void test_vector_mul_sub_shared() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      c = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          c[i] = i;
    +          long val = a[i] * b[i];
    +          expected += val - val * c[i];
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = vector_mul_sub_shared();
    +      }
    +      Asserts.assertEQ(expected, result, "vector_mul_sub_shared");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      counts = {IRNode.VMLA, "=0"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLA, ">0"})
    +  public long if_else_phi_add() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          LongVector cv = LongVector.fromArray(SPECIES_128, c, i);
    +          LongVector selected;
    +          if ((i & SPECIES_128.length()) == 0) {
    +              selected = av.mul(bv);
    +          } else {
    +              selected = bv.mul(cv);
    +          }
    +          acc = acc.add(selected.add(av.mul(cv)));
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"if_else_phi_add"}, mode = RunMode.STANDALONE)
    +  public void test_if_else_phi_add() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      c = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          c[i] = i;
    +      }
    +      for (int i = 0; i < SPECIES_128.loopBound(ARRLEN); i += SPECIES_128.length()) {
    +          boolean first = (i & SPECIES_128.length()) == 0;
    +          for (int lane = 0; lane < SPECIES_128.length(); lane++) {
    +              int index = i + lane;
    +              long selected = first ? a[index] * b[index] : b[index] * c[index];
    +              expected += selected + a[index] * c[index];
    +          }
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = if_else_phi_add();
    +      }
    +      Asserts.assertEQ(expected, result, "if_else_phi_add");
    +  }
    +
    +  @Test
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "true"},
    +      counts = {IRNode.VMLS, "=0"})
    +  @IR(applyIfCPUFeature = {"sve", "true"},
    +      applyIf = {"AvoidMLAChain", "false"},
    +      counts = {IRNode.VMLS, ">0"})
    +  public long if_else_phi_sub() {
    +      LongVector acc = LongVector.zero(SPECIES_128);
    +      for (int i = 0; i < SPECIES_128.loopBound(a.length); i += SPECIES_128.length()) {
    +          LongVector av = LongVector.fromArray(SPECIES_128, a, i);
    +          LongVector bv = LongVector.fromArray(SPECIES_128, b, i);
    +          LongVector cv = LongVector.fromArray(SPECIES_128, c, i);
    +          LongVector selected;
    +          if ((i & SPECIES_128.length()) == 0) {
    +              selected = av.mul(bv);
    +          } else {
    +              selected = bv.mul(cv);
    +          }
    +          acc = acc.add(selected.sub(av.mul(cv)));
    +      }
    +      return acc.reduceLanes(VectorOperators.ADD);
    +  }
    +
    +  @Run(test = {"if_else_phi_sub"}, mode = RunMode.STANDALONE)
    +  public void test_if_else_phi_sub() {
    +      a = new long[ARRLEN];
    +      b = new long[ARRLEN];
    +      c = new long[ARRLEN];
    +      long expected = 0L;
    +      for (int i = 0; i < ARRLEN; i++) {
    +          a[i] = i;
    +          b[i] = i;
    +          c[i] = i;
    +      }
    +      for (int i = 0; i < SPECIES_128.loopBound(ARRLEN); i += SPECIES_128.length()) {
    +          boolean first = (i & SPECIES_128.length()) == 0;
    +          for (int lane = 0; lane < SPECIES_128.length(); lane++) {
    +              int index = i + lane;
    +              long selected = first ? a[index] * b[index] : b[index] * c[index];
    +              expected += selected - a[index] * c[index];
    +          }
    +      }
    +      long result = 0L;
    +      for (int i = 0; i < ITERS; i++) {
    +          result = if_else_phi_sub();
    +      }
    +      Asserts.assertEQ(expected, result, "if_else_phi_sub");
    +  }
    +}
    diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/BasicLongOpTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/BasicLongOpTest.java
    index 5404d943bbc6..ed2fe758b2fd 100644
    --- a/test/hotspot/jtreg/compiler/vectorization/runner/BasicLongOpTest.java
    +++ b/test/hotspot/jtreg/compiler/vectorization/runner/BasicLongOpTest.java
    @@ -116,6 +116,7 @@ public long[] vectorMul() {
             counts = {IRNode.ADD_VL, ">0"})
         @IR(applyIfCPUFeatureOr = {"sve", "true", "sse4.1", "true", "rvv", "true"},
             counts = {IRNode.MUL_VL, ">0"})
    +    @IR(applyIfCPUFeature = {"sve", "true"}, counts = {IRNode.VMLA, ">0"})
         public long[] vectorMulAdd() {
             long[] res = new long[SIZE];
             for (int i = 0; i < SIZE; i++) {
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyCheckCast.java b/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyCheckCast.java
    index 8080346568f9..b560bff6dce7 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyCheckCast.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyCheckCast.java
    @@ -24,10 +24,10 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @requires vm.gc.Shenandoah
      *
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:TieredStopAtLevel=0 -Xmx16m ${test.main.class}
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:TieredStopAtLevel=0 -Xmx16m -XX:ShenandoahGCMode=satb ${test.main.class}
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyStress.java b/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyStress.java
    index fd6e14145e4d..3acf2a3e12bd 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyStress.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestArrayCopyStress.java
    @@ -27,12 +27,12 @@
     import jdk.test.lib.Utils;
     
     /*
    - * @test id=default
    + * @test id=satb
      * @key randomness
      * @requires vm.gc.Shenandoah
      * @library /test/lib
      *
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:TieredStopAtLevel=0 -Xmx16m TestArrayCopyStress
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:TieredStopAtLevel=0 -Xmx16m TestArrayCopyStress
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java b/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java
    index 891c03348473..5da02bfb72ad 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java
    @@ -24,13 +24,13 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Tests for crash/assert when attaching init thread during shutdown
      * @requires vm.gc.Shenandoah
      * @library /test/lib
      * @modules java.base/jdk.internal.misc
      *          java.management
    - * @run driver/timeout=480 TestEvilSyncBug -XX:ShenandoahGCHeuristics=aggressive
    + * @run driver/timeout=480 TestEvilSyncBug -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestGCThreadGroups.java b/test/hotspot/jtreg/gc/shenandoah/TestGCThreadGroups.java
    index e66c4e7dc873..44856d2ae6cd 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestGCThreadGroups.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestGCThreadGroups.java
    @@ -36,42 +36,42 @@
      */
     
     /**
    - * @test id=default
    + * @test id=satb
      * @summary Test Shenandoah GC uses concurrent/parallel threads correctly
      * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:ConcGCThreads=2 -XX:ParallelGCThreads=4
      *      -Dtarget=1000
      *      TestGCThreadGroups
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:-UseDynamicNumberOfGCThreads
      *      -Dtarget=1000
      *      TestGCThreadGroups
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      -XX:ConcGCThreads=2 -XX:ParallelGCThreads=4
      *      -Dtarget=1000
      *      TestGCThreadGroups
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=static
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=static
      *      -XX:ConcGCThreads=2 -XX:ParallelGCThreads=4
      *      -Dtarget=1000
      *      TestGCThreadGroups
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      -XX:ConcGCThreads=2 -XX:ParallelGCThreads=4
      *      -Dtarget=100
      *      TestGCThreadGroups
      *
      * @run main/othervm -Xmx16m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC  -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      -XX:ConcGCThreads=2 -XX:ParallelGCThreads=4
      *      -Dtarget=100
      *      TestGCThreadGroups
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestHeapUncommit.java b/test/hotspot/jtreg/gc/shenandoah/TestHeapUncommit.java
    index a0ce91c2ac97..e4c3966b3585 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestHeapUncommit.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestHeapUncommit.java
    @@ -41,36 +41,36 @@
      */
     
     /*
    - * @test id=adaptive
    + * @test id=satb
      * @summary Acceptance tests: collector can withstand allocation
      * @key randomness
      * @requires vm.gc.Shenandoah
      * @library /test/lib
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      -XX:+ShenandoahVerify
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:-UseTLAB -XX:+ShenandoahVerify
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=static
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=static
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      TestHeapUncommit
      */
     
    @@ -96,25 +96,46 @@
      *      TestHeapUncommit
      */
     
    + /*
    + * @test id=generational-lp
    + * @summary Acceptance tests: collector can withstand allocation
    + * @key randomness
    + * @requires vm.gc.Shenandoah
    + * @library /test/lib
    + * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
    + *      -XX:+ShenandoahVerify
    + *      TestHeapUncommit
    + *
    + * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
    + *      -XX:-UseTLAB -XX:+ShenandoahVerify
    + *      TestHeapUncommit
    + *
    + * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
    + *      TestHeapUncommit
    + */
    +
     /*
    - * @test id=default-lp
    + * @test id=satb-lp
      * @key randomness
      * @requires vm.gc.Shenandoah
      * @requires vm.bits == "64"
      * @library /test/lib
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:+ShenandoahVerify
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:-UseTLAB -XX:+ShenandoahVerify
      *      TestHeapUncommit
      *
      * @run main/othervm -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ShenandoahUncommit -XX:ShenandoahUncommitDelay=0 -XX:+UseLargePages
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      TestHeapUncommit
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestLargeObjectAlignment.java b/test/hotspot/jtreg/gc/shenandoah/TestLargeObjectAlignment.java
    index 6eb0f36f1ae1..e836c477c8bb 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestLargeObjectAlignment.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestLargeObjectAlignment.java
    @@ -24,7 +24,7 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Shenandoah crashes with -XX:ObjectAlignmentInBytes=16
      * @key randomness
      * @requires vm.gc.Shenandoah
    @@ -32,10 +32,10 @@
      * @requires os.maxMemory > 4G
      * @library /test/lib
      *
    - * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ObjectAlignmentInBytes=16 -Xint                   TestLargeObjectAlignment
    - * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ObjectAlignmentInBytes=16 -XX:-TieredCompilation  TestLargeObjectAlignment
    - * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ObjectAlignmentInBytes=16 -XX:TieredStopAtLevel=1 TestLargeObjectAlignment
    - * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ObjectAlignmentInBytes=16 -XX:TieredStopAtLevel=4 TestLargeObjectAlignment
    + * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ObjectAlignmentInBytes=16 -Xint                   TestLargeObjectAlignment
    + * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ObjectAlignmentInBytes=16 -XX:-TieredCompilation  TestLargeObjectAlignment
    + * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ObjectAlignmentInBytes=16 -XX:TieredStopAtLevel=1 TestLargeObjectAlignment
    + * @run main/othervm -Xmx3g -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ObjectAlignmentInBytes=16 -XX:TieredStopAtLevel=4 TestLargeObjectAlignment
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java b/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java
    index edafded07dc5..256766f63ef9 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java
    @@ -90,6 +90,7 @@ public static void main(String[] args) throws Exception {
                         "-XX:+UnlockDiagnosticVMOptions",
                         "-XX:+UnlockExperimentalVMOptions",
                         "-XX:+UseShenandoahGC",
    +                    "-XX:ShenandoahGCMode=satb",
                         "-XX:ShenandoahGCHeuristics=" + h,
                         "-XX:ShenandoahGuaranteedGCInterval=0"
                 );
    @@ -100,6 +101,7 @@ public static void main(String[] args) throws Exception {
                         "-XX:+UnlockDiagnosticVMOptions",
                         "-XX:+UnlockExperimentalVMOptions",
                         "-XX:+UseShenandoahGC",
    +                    "-XX:ShenandoahGCMode=satb",
                         "-XX:ShenandoahGCHeuristics=" + h,
                         "-XX:ShenandoahGuaranteedGCInterval=1000"
                 );
    @@ -110,6 +112,7 @@ public static void main(String[] args) throws Exception {
                         "-XX:+UnlockDiagnosticVMOptions",
                         "-XX:+UnlockExperimentalVMOptions",
                         "-XX:+UseShenandoahGC",
    +                    "-XX:ShenandoahGCMode=satb",
                         "-XX:ShenandoahGCHeuristics=" + h,
                         "-XX:ShenandoahGuaranteedGCInterval=100000" // deliberately too long
                 );
    @@ -121,6 +124,7 @@ public static void main(String[] args) throws Exception {
                      "-XX:+UnlockDiagnosticVMOptions",
                      "-XX:+UnlockExperimentalVMOptions",
                      "-XX:+UseShenandoahGC",
    +                 "-XX:ShenandoahGCMode=satb",
                      "-XX:ShenandoahGCHeuristics=aggressive",
                      "-XX:ShenandoahGuaranteedGCInterval=1000"
             );
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestRefprocSanity.java b/test/hotspot/jtreg/gc/shenandoah/TestRefprocSanity.java
    index 4f0734ad57d0..4d48018bcea2 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestRefprocSanity.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestRefprocSanity.java
    @@ -24,21 +24,21 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Test that null references/referents work fine
      * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx128m -Xms128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -XX:+ShenandoahVerify
      *      TestRefprocSanity
      *
      * @run main/othervm -Xmx128m -Xms128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      TestRefprocSanity
      *
      * @run main/othervm -Xmx128m -Xms128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      TestRefprocSanity
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestRegionSamplingLogging.java b/test/hotspot/jtreg/gc/shenandoah/TestRegionSamplingLogging.java
    index 5c9536223f31..2453bd3ad010 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestRegionSamplingLogging.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestRegionSamplingLogging.java
    @@ -23,13 +23,13 @@
      */
     
     /*
    - * @test id=default-rotation
    + * @test id=satb-rotation
      * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
      *      -XX:+ShenandoahRegionSampling -XX:+ShenandoahRegionSampling
      *      -Xlog:gc+region=trace:region-snapshots-%p.log::filesize=100,filecount=3
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      TestRegionSamplingLogging
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestSmallHeap.java b/test/hotspot/jtreg/gc/shenandoah/TestSmallHeap.java
    index 6642e5ec10fb..610b8898c0a4 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestSmallHeap.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestSmallHeap.java
    @@ -24,15 +24,15 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @requires vm.gc.Shenandoah
      *
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC         TestSmallHeap
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx64m TestSmallHeap
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx32m TestSmallHeap
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx16m TestSmallHeap
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx8m  TestSmallHeap
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx4m  TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb         TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xmx64m TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xmx32m TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xmx16m TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xmx8m  TestSmallHeap
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xmx4m  TestSmallHeap
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestStringDedup.java b/test/hotspot/jtreg/gc/shenandoah/TestStringDedup.java
    index 9c88b3df3407..10410079d8af 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestStringDedup.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestStringDedup.java
    @@ -40,7 +40,7 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Test Shenandoah string deduplication implementation
      * @key randomness
      * @requires vm.gc.Shenandoah
    @@ -49,15 +49,15 @@
      *          java.management
      *
      * @run main/othervm -Xmx256m -Xlog:stringdedup -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      TestStringDedup
      *
      * @run main/othervm -Xmx256m -Xlog:stringdedup -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      TestStringDedup
      *
      * @run main/othervm -Xmx256m -Xlog:stringdedup -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      TestStringDedup
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestStringDedupStress.java b/test/hotspot/jtreg/gc/shenandoah/TestStringDedupStress.java
    index 218ca16b846e..e45610a6bc4f 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestStringDedupStress.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestStringDedupStress.java
    @@ -53,7 +53,7 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Test Shenandoah string deduplication implementation
      * @key randomness
      * @requires vm.gc.Shenandoah
    @@ -62,23 +62,23 @@
      *          java.management
      *
      * @run main/othervm -Xmx1g -Xlog:stringdedup -Xlog:gc -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      -DtargetStrings=3000000
      *      TestStringDedupStress
      *
      * @run main/othervm -Xmx1g -Xlog:stringdedup -Xlog:gc -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      -DtargetStrings=2000000
      *      TestStringDedupStress
      *
      * @run main/othervm -Xmx1g -Xlog:stringdedup -Xlog:gc -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      -XX:+ShenandoahOOMDuringEvacALot
      *      -DtargetStrings=2000000
      *      TestStringDedupStress
      *
      * @run main/othervm -Xmx1g -Xlog:stringdedup -Xlog:gc -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      TestStringDedupStress
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestStringInternCleanup.java b/test/hotspot/jtreg/gc/shenandoah/TestStringInternCleanup.java
    index 0c5a26289040..dd4567e59b63 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestStringInternCleanup.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestStringInternCleanup.java
    @@ -39,29 +39,29 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Check that Shenandoah cleans up interned strings
      * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ClassUnloadingWithConcurrentMark
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      TestStringInternCleanup
      *
      * @run main/othervm -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ClassUnloadingWithConcurrentMark
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      -XX:+ShenandoahVerify
      *      TestStringInternCleanup
      *
      * @run main/othervm -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ClassUnloadingWithConcurrentMark
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      TestStringInternCleanup
      *
      * @run main/othervm -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+ClassUnloadingWithConcurrentMark
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      TestStringInternCleanup
      *
      * @run main/othervm -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:-ClassUnloadingWithConcurrentMark
    - *      -XX:+UseShenandoahGC
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *      TestStringInternCleanup
      */
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java b/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java
    index 4cb2176f0d93..0bab005a94a8 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java
    @@ -41,21 +41,29 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @summary Tests that we pass at least one jcstress-like test with all verification turned on
      * @requires vm.gc.Shenandoah
      * @modules java.base/jdk.internal.misc
      *          java.management
      *
      * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      -XX:+ShenandoahVerify
      *      TestVerifyJCStress
      *
      * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      -XX:+ShenandoahVerify
      *      TestVerifyJCStress
    + */
    +
    +/*
    + * @test id=generational
    + * @summary Tests that we pass at least one jcstress-like test with all verification turned on
    + * @requires vm.gc.Shenandoah
    + * @modules java.base/jdk.internal.misc
    + *          java.management
      *
      * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions
      *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive -XX:ShenandoahGCMode=generational
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestVerifyLevels.java b/test/hotspot/jtreg/gc/shenandoah/TestVerifyLevels.java
    index 11321eaa67fa..e76194d7341a 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestVerifyLevels.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestVerifyLevels.java
    @@ -24,14 +24,14 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @requires vm.gc.Shenandoah
      *
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=0 TestVerifyLevels
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=1 TestVerifyLevels
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=2 TestVerifyLevels
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=3 TestVerifyLevels
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=4 TestVerifyLevels
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=0 TestVerifyLevels
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=1 TestVerifyLevels
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=2 TestVerifyLevels
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=3 TestVerifyLevels
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+UnlockDiagnosticVMOptions -Xmx128m -XX:+ShenandoahVerify -XX:ShenandoahVerifyLevel=4 TestVerifyLevels
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/TestWithLogLevel.java b/test/hotspot/jtreg/gc/shenandoah/TestWithLogLevel.java
    index 9f0fa13d1826..450319ec83ef 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/TestWithLogLevel.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/TestWithLogLevel.java
    @@ -24,15 +24,15 @@
      */
     
      /*
    - * @test id=default
    + * @test id=satb
      * @summary Test Shenandoah with different log levels
      * @requires vm.gc.Shenandoah
      *
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms256M -Xmx1G -Xlog:gc*=error   TestWithLogLevel
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms256M -Xmx1G -Xlog:gc*=warning TestWithLogLevel
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms256M -Xmx1G -Xlog:gc*=info    TestWithLogLevel
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms256M -Xmx1G -Xlog:gc*=debug   TestWithLogLevel
    - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms256M -Xmx1G -Xlog:gc*=trace   TestWithLogLevel
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xms256M -Xmx1G -Xlog:gc*=error   TestWithLogLevel
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xms256M -Xmx1G -Xlog:gc*=warning TestWithLogLevel
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xms256M -Xmx1G -Xlog:gc*=info    TestWithLogLevel
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xms256M -Xmx1G -Xlog:gc*=debug   TestWithLogLevel
    + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xms256M -Xmx1G -Xlog:gc*=trace   TestWithLogLevel
      */
     
     /*
    diff --git a/test/hotspot/jtreg/gc/shenandoah/compiler/TestClone.java b/test/hotspot/jtreg/gc/shenandoah/compiler/TestClone.java
    index 45891e0bd40c..01b6bb49778e 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/compiler/TestClone.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/compiler/TestClone.java
    @@ -23,29 +23,29 @@
      */
     
     /*
    - * @test id=default
    + * @test id=satb
      * @key randomness
      * @summary Test clone barriers work correctly
      * @library /test/lib
      * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Xms1g -Xmx1g
    - *                   -XX:+UseShenandoahGC
    + *                   -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *                   TestClone
      * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Xms1g -Xmx1g
    - *                   -XX:+UseShenandoahGC
    + *                   -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *                   -Xint
      *                   TestClone
      * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Xms1g -Xmx1g
    - *                   -XX:+UseShenandoahGC
    + *                   -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *                   -XX:-TieredCompilation
      *                   TestClone
      * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Xms1g -Xmx1g
    - *                   -XX:+UseShenandoahGC
    + *                   -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *                   -XX:TieredStopAtLevel=1
      *                   TestClone
      * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Xms1g -Xmx1g
    - *                   -XX:+UseShenandoahGC
    + *                   -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb
      *                   -XX:TieredStopAtLevel=4
      *                   TestClone
      */
    diff --git a/test/hotspot/jtreg/gc/shenandoah/jni/TestJNICritical.java b/test/hotspot/jtreg/gc/shenandoah/jni/TestJNICritical.java
    index 62d9addeaa46..dcc3c6dd0ff1 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/jni/TestJNICritical.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/jni/TestJNICritical.java
    @@ -23,14 +23,14 @@
      *
      */
     
    -/* @test id=default
    +/* @test id=satb
      * @summary test JNI critical arrays support in Shenandoah
      * @key randomness
      * @requires vm.gc.Shenandoah
      * @library /test/lib
      *
    - * @run main/othervm/native -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:+ShenandoahVerify                 TestJNICritical
    - * @run main/othervm/native -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive TestJNICritical
    + * @run main/othervm/native -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:+ShenandoahVerify                 TestJNICritical
    + * @run main/othervm/native -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive TestJNICritical
      */
     
      /* @test id=generational
    diff --git a/test/hotspot/jtreg/gc/shenandoah/jvmti/libTestHeapDump.c b/test/hotspot/jtreg/gc/shenandoah/jvmti/libTestHeapDump.c
    index 368d4e541a00..c23dd813efd1 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/jvmti/libTestHeapDump.c
    +++ b/test/hotspot/jtreg/gc/shenandoah/jvmti/libTestHeapDump.c
    @@ -42,10 +42,7 @@ extern "C" {
     
     #endif
     
    -#define TranslateError(err) "JVMTI error"
    -
     #define PASSED 0
    -#define FAILED 2
     
     static const char *EXC_CNAME = "java/lang/Exception";
     
    diff --git a/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestChurnNotifications.java b/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestChurnNotifications.java
    index caeb0464feb2..7d42bb049cb5 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestChurnNotifications.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestChurnNotifications.java
    @@ -39,10 +39,10 @@
      * @test id=aggressive
      * @summary Check that MX notifications are reported for all cycles
      * @library /test/lib /
    - * @requires vm.gc.Shenandoah & vm.opt.ShenandoahGCMode != "generational"
    + * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=aggressive
      *      -Dprecise=false
      *      TestChurnNotifications
      */
    @@ -51,10 +51,10 @@
      * @test id=adaptive
      * @summary Check that MX notifications are reported for all cycles
      * @library /test/lib /
    - * @requires vm.gc.Shenandoah & vm.opt.ShenandoahGCMode != "generational"
    + * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=adaptive
      *      -Dprecise=false
      *      TestChurnNotifications
      */
    @@ -63,10 +63,10 @@
      * @test id=static
      * @summary Check that MX notifications are reported for all cycles
      * @library /test/lib /
    - * @requires vm.gc.Shenandoah & vm.opt.ShenandoahGCMode != "generational"
    + * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=static
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=static
      *      -Dprecise=false
      *      TestChurnNotifications
      */
    @@ -75,10 +75,10 @@
      * @test id=compact
      * @summary Check that MX notifications are reported for all cycles
      * @library /test/lib /
    - * @requires vm.gc.Shenandoah & vm.opt.ShenandoahGCMode != "generational"
    + * @requires vm.gc.Shenandoah
      *
      * @run main/othervm -Xmx128m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
    - *      -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact
    + *      -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -XX:ShenandoahGCHeuristics=compact
      *      -Dprecise=false
      *      TestChurnNotifications
      */
    diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java
    index 176e4a2ca7ae..fa1f1d7f713e 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java
    @@ -54,7 +54,6 @@ public static void main(String[] args) throws Exception {
             };
     
             String[] opts = new String[] {
    -                "",
                     "-XX:-ExplicitGCInvokesConcurrent",
                     "-XX:+ExplicitGCInvokesConcurrent"
             };
    @@ -67,11 +66,14 @@ public static void main(String[] args) throws Exception {
                         "-Xlog:gc",
                         "-XX:+UnlockDiagnosticVMOptions",
                         opt,
    +                    "-XX:ShenandoahGCMode=passive",
                         "-XX:ShenandoahGCHeuristics=passive",
                         TestExplicitGCNoConcurrent.class.getName(),
                         "test");
                 for (String p : concurrent) {
    +                output.shouldContain("Trigger");
                     output.shouldNotContain(p);
    +                output.shouldHaveExitValue(0);
                 }
             }
         }
    diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java b/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java
    index 9d0065fe8031..a308b30c840b 100644
    --- a/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java
    +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java
    @@ -48,66 +48,73 @@ public static void main(String[] args) throws Exception {
             testWith("-XX:ShenandoahGCHeuristics=static",     Mode.PRODUCT);
             testWith("-XX:ShenandoahGCHeuristics=compact",    Mode.PRODUCT);
             testWith("-XX:ShenandoahGCHeuristics=aggressive", Mode.DIAGNOSTIC);
    +        testWith("-XX:ShenandoahGCHeuristics=passive",    Mode.DIAGNOSTIC);
         }
     
         private static void testWith(String h, Mode mode) throws Exception {
    -        {
    -            OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    -                    "-Xmx128m",
    -                    "-XX:-UnlockDiagnosticVMOptions",
    -                    "-XX:-UnlockExperimentalVMOptions",
    -                    "-XX:+UseShenandoahGC",
    -                    h,
    -                    "-version"
    -            );
    -            switch (mode) {
    -                case PRODUCT:
    -                    output.shouldHaveExitValue(0);
    -                    break;
    -                case DIAGNOSTIC:
    -                case EXPERIMENTAL:
    -                    output.shouldNotHaveExitValue(0);
    -                    break;
    +        String[] shenandoahModes = {"satb", "generational"};
    +        for (var shenandoahMode : shenandoahModes) {
    +            {
    +                OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    +                        "-Xmx128m",
    +                        "-XX:-UnlockDiagnosticVMOptions",
    +                        "-XX:-UnlockExperimentalVMOptions",
    +                        "-XX:+UseShenandoahGC",
    +                        "-XX:ShenandoahGCMode=" + shenandoahMode,
    +                        h,
    +                        "-version"
    +                );
    +                switch (mode) {
    +                    case PRODUCT:
    +                        output.shouldHaveExitValue(0);
    +                        break;
    +                    case DIAGNOSTIC:
    +                    case EXPERIMENTAL:
    +                        output.shouldNotHaveExitValue(0);
    +                        break;
    +                }
                 }
    -        }
     
    -        {
    -            OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    -                    "-Xmx128m",
    -                    "-XX:+UnlockDiagnosticVMOptions",
    -                    "-XX:-UnlockExperimentalVMOptions",
    -                    "-XX:+UseShenandoahGC",
    -                    h,
    -                    "-version"
    -            );
    -            switch (mode) {
    -                case PRODUCT:
    -                case DIAGNOSTIC:
    -                    output.shouldHaveExitValue(0);
    -                    break;
    -                case EXPERIMENTAL:
    -                    output.shouldNotHaveExitValue(0);
    -                    break;
    +            {
    +                OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    +                        "-Xmx128m",
    +                        "-XX:+UnlockDiagnosticVMOptions",
    +                        "-XX:-UnlockExperimentalVMOptions",
    +                        "-XX:+UseShenandoahGC",
    +                        "-XX:ShenandoahGCMode=" + shenandoahMode,
    +                        h,
    +                        "-version"
    +                );
    +                switch (mode) {
    +                    case PRODUCT:
    +                    case DIAGNOSTIC:
    +                        output.shouldHaveExitValue(0);
    +                        break;
    +                    case EXPERIMENTAL:
    +                        output.shouldNotHaveExitValue(0);
    +                        break;
    +                }
                 }
    -        }
     
    -        {
    -            OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    -                    "-Xmx128m",
    -                    "-XX:-UnlockDiagnosticVMOptions",
    -                    "-XX:+UnlockExperimentalVMOptions",
    -                    "-XX:+UseShenandoahGC",
    -                    h,
    -                    "-version"
    -            );
    -            switch (mode) {
    -                case PRODUCT:
    -                case EXPERIMENTAL:
    -                    output.shouldHaveExitValue(0);
    -                    break;
    -                case DIAGNOSTIC:
    -                    output.shouldNotHaveExitValue(0);
    -                    break;
    +            {
    +                OutputAnalyzer output = ProcessTools.executeLimitedTestJava(
    +                        "-Xmx128m",
    +                        "-XX:-UnlockDiagnosticVMOptions",
    +                        "-XX:+UnlockExperimentalVMOptions",
    +                        "-XX:+UseShenandoahGC",
    +                        "-XX:ShenandoahGCMode=" + shenandoahMode,
    +                        h,
    +                        "-version"
    +                );
    +                switch (mode) {
    +                    case PRODUCT:
    +                    case EXPERIMENTAL:
    +                        output.shouldHaveExitValue(0);
    +                        break;
    +                    case DIAGNOSTIC:
    +                        output.shouldNotHaveExitValue(0);
    +                        break;
    +                }
                 }
             }
         }
    diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java
    index 6fc59f3b71e5..7c2cba9daec2 100644
    --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java
    +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java
    @@ -261,13 +261,6 @@ public static void main(String[] args) throws Exception {
              */
             excludeTestMaxRange("CompileThresholdScaling");
     
    -        /*
    -         * Do not test InitiatingHeapOccupancyPercent as it is an
    -         * alias that will answer with the string G1IHOP. Remove this
    -         * when the alias is removed.
    -         */
    -        excludeTestRange("InitiatingHeapOccupancyPercent");
    -
             List testSubset = getTestSubset(args);
     
             Asserts.assertGT(testSubset.size(), 0, "Options with ranges not found!");
    diff --git a/test/hotspot/jtreg/runtime/cds/CdsDifferentCompactStrings.java b/test/hotspot/jtreg/runtime/cds/CdsDifferentCompactStrings.java
    index c6d31678806d..0efdc2e5d6dd 100644
    --- a/test/hotspot/jtreg/runtime/cds/CdsDifferentCompactStrings.java
    +++ b/test/hotspot/jtreg/runtime/cds/CdsDifferentCompactStrings.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -52,7 +52,7 @@ private static void createAndLoadSharedArchive(String create, String load)
             CDSTestUtils.checkMappingFailure(out);
     
             out.shouldMatch("The shared archive file's CompactStrings " +
    -                        "setting .* does not equal the current CompactStrings setting")
    +                        "setting .* does not equal the current setting")
                 .shouldHaveExitValue(1);
         }
     }
    diff --git a/test/hotspot/jtreg/runtime/cds/CdsDifferentObjectAlignment.java b/test/hotspot/jtreg/runtime/cds/CdsDifferentObjectAlignment.java
    index 07a3b1698fbf..61ec96d4dcd8 100644
    --- a/test/hotspot/jtreg/runtime/cds/CdsDifferentObjectAlignment.java
    +++ b/test/hotspot/jtreg/runtime/cds/CdsDifferentObjectAlignment.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -56,8 +56,8 @@ public static void main(String[] args) throws Exception {
                 loadAlignment;
             String expectedErrorMsg =
                 String.format(
    -            "The shared archive file's ObjectAlignmentInBytes of %d " +
    -            "does not equal the current ObjectAlignmentInBytes of %d",
    +            "The shared archive file's ObjectAlignmentInBytes setting (%d) " +
    +            "does not equal the current setting (%d)",
                 createAlignment,
                 loadAlignment);
     
    diff --git a/test/hotspot/jtreg/runtime/cds/DeterministicDump.java b/test/hotspot/jtreg/runtime/cds/DeterministicDump.java
    index d26ca8cc7cf3..c777a55bfc71 100644
    --- a/test/hotspot/jtreg/runtime/cds/DeterministicDump.java
    +++ b/test/hotspot/jtreg/runtime/cds/DeterministicDump.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -46,12 +46,8 @@
     import java.util.ArrayList;
     
     public class DeterministicDump {
    -
    -    static long HEADER_SIZE;      // Size of header in bytes
    -    static int HEADER_LEN = 106;  // Number of lines in CDS map file header
    -    static int LINE_OFFSET = 22;  // Offset from address to first word of data
    -    static int NUM_LINES = 5;     // Number of lines to be printed
    -    static int WORD_LEN = 16 + 1; // Length of word in map file
    +    static int NUM_CONTEXT_LINES = 4; // Number of context lines to be printed in diffs
    +    static int MAX_DIFF_LINES = 40; // Maximum number of diffs to print (to avoid excessive output)
     
         public static void main(String[] args) throws Exception {
             doTest(false);
    @@ -78,7 +74,6 @@ public static void doTest(boolean compressed) throws Exception {
     
             String baseArchive = dump(baseArgs);
             File baseArchiveFile = new File(baseArchive + ".jsa");
    -        HEADER_SIZE = CDSArchiveUtils.fileHeaderSize(baseArchiveFile);
     
             // (1) Dump with the same args. Should produce the same archive.
             String baseArchive2 = dump(baseArgs);
    @@ -130,12 +125,8 @@ static void compare(String file0, String file1, File archiveFile) throws Excepti
                         byte b0 = buff0[i];
                         byte b1 = buff1[i];
                         if (b0 != b1) {
    -                        // The checksums are stored in the header so it should be skipped
    -                        // since we want to see the first meaningful diff between the archives
    -                        if (total + i > HEADER_SIZE) {
    -                            print_diff(file0 + ".map", file1 + ".map", archiveFile, total + i);
    -                            throw new RuntimeException("File content different at byte #" + (total + i) + ", b0 = " + b0 + ", b1 = " + b1);
    -                        }
    +                      print_diff(file0 + ".map", file1 + ".map");
    +                      throw new RuntimeException("File content different at byte #" + (total + i) + ", b0 = " + b0 + ", b1 = " + b1);
                         }
                     }
                     total += n0;
    @@ -156,114 +147,86 @@ static int read(FileInputStream in, byte[] buff) throws IOException {
             return total;
         }
     
    -    // CDS map file doesn't print the alignment bytes so they need to be considered
    -    // when mapping the byte number in the archive to the word in the map file
    -    static int archiveByteToMapWord(File archiveFile, int location) throws Exception {
    -        int totalSize = 0;
    -        int word = location;
    -
    -        long len = HEADER_SIZE;
    -        long aligned = CDSArchiveUtils.fileHeaderSizeAligned(archiveFile);
    -        for (int i = 0; i < CDSArchiveUtils.num_regions(); i++) {
    -            if (i != 0) {
    -                len = CDSArchiveUtils.usedRegionSize(archiveFile, i);
    -                aligned = CDSArchiveUtils.usedRegionSizeAligned(archiveFile, i);
    -            }
    -            totalSize += len;
    -            if (location > totalSize) {
    -                word -= (aligned - len - 16);
    -            }
    -        }
    -        return word/8;
    -    }
    -
    -    // Read the mapfile and print out the lines associated with the location
    -    static void print_diff(String mapName0, String mapName1, File archiveFile, int location) throws Exception {
    -        FileReader f0 = new FileReader(mapName0);
    -        BufferedReader b0 = new BufferedReader(f0);
    -
    -        FileReader f1 = new FileReader(mapName1);
    -        BufferedReader b1 = new BufferedReader(f1);
    -
    -        int word = archiveByteToMapWord(archiveFile, location);
    -        int wordOffset = word % 4; // Each line in the map file prints four words
    -        String region = "";
    -
    -        // Skip header text and go to first line
    -        for (int i = 0; i < HEADER_LEN; i++) {
    -            b0.readLine();
    -            b1.readLine();
    -        }
    -
    -        int line_num = HEADER_LEN;
    -        String s0 = "";
    -        String s1 = "";
    -        int count = 0;
    -
    -        // Store lines before and including the diff
    -        ArrayDeque prefix0 = new ArrayDeque();
    -        ArrayDeque prefix1 = new ArrayDeque();
    -
    -        // A line may contain 1-4 words so we iterate by word
    -        do {
    -            s0 = b0.readLine();
    -            s1 = b1.readLine();
    -            line_num++;
    -
    -            if (prefix0.size() >= NUM_LINES / 2 + 1) {
    -                prefix0.removeFirst();
    -                prefix1.removeFirst();
    -            }
    -            prefix0.addLast(s0);
    -            prefix1.addLast(s1);
    +    // Print a text diff of the map files
    +    static void print_diff(String mapName0, String mapName1) throws Exception {
    +        try (FileReader f0 = new FileReader(mapName0);
    +             BufferedReader b0 = new BufferedReader(f0);
    +             FileReader f1 = new FileReader(mapName1);
    +             BufferedReader b1 = new BufferedReader(f1)) {
    +
    +            ArrayDeque context = new ArrayDeque();
    +
    +            int numLines = 0;
    +            int trailContextNeeded = 0;
    +            int printedDiffs = 0;
    +            int totalDiffs = 0;
    +            boolean needLineNum = false;
    +
    +            // This is a simplified diff -- we just compare line X in mapName0 with line X in mapName1.
    +            // This catches the usual problems we've encountered in the past -- the two files
    +            // have identical structure, but some data values are different due to random values
    +            // in the gaps in C++ data structures.
    +            //
    +            // More drastic problem (e.g., the objects in the archives are sorted differently) will
    +            // show up as a large amount of random differences (limited by MAX_DIFF_LINES). A more
    +            // intellgent diff algorithm (such as /bin/diff) won't be useful anyway, so we will just
    +            // stick with this simplified version.
    +            while (true) {
    +                // Read one line from each file. Missing lines from either file is represented as ""
    +                String s0 = b0.readLine();
    +                String s1 = b1.readLine();
    +                if (s0 == null && s1 == null) {
    +                    break;
    +                }
     
    -            // Skip lines with headers when counting words e.g.
    -            // [rw region          0x0000000800000000 - 0x00000008005a1f88   5906312 bytes]
    -            // or
    -            // 0x0000000800000b28: @@ TypeArrayU1       16
    -            if (!s0.contains(": @@") && !s0.contains("bytes]")) {
    -                int words = (s0.length() - LINE_OFFSET - 70) / 8;
    -                count += words;
    -            } else if (s0.contains("bytes]")) {
    -                region = s0;
    +                boolean isEof = false;
    +                if (s0 == null) {
    +                    s0 = "";
    +                    isEof = true;
    +                }
    +                if (s1 == null) {
    +                    s1 = "";
    +                    isEof = true;
    +                }
    +                numLines ++;
    +
    +                if (!s0.equals(s1) || isEof) {
    +                    // Print the diff, prefixed by the context (if available)
    +                    if (printedDiffs < MAX_DIFF_LINES) {
    +                        if (needLineNum) {
    +                            System.out.println();
    +                            System.out.println((numLines - context.size()) + ":");
    +                            needLineNum = false;
    +                        }
    +                        for (String s : context) {
    +                            System.out.println("  " + s);
    +                        }
    +                        context.clear();
    +                        System.out.println("- " + s0);
    +                        System.out.println("+ " + s1);
    +                        trailContextNeeded = NUM_CONTEXT_LINES;
    +                        printedDiffs ++;
    +                    }
    +                    totalDiffs ++;
    +                } else {
    +                    if (trailContextNeeded > 0) {
    +                        // The lines are identical, but print it anyway to show the trailing context
    +                        System.out.println("  " + s0);
    +                        trailContextNeeded --;
    +                    } else {
    +                        while (context.size() >= NUM_CONTEXT_LINES) {
    +                            context.removeFirst();
    +                            // Print the line number on the next diff ONLY if we have
    +                            // omitted some identical lines.
    +                            needLineNum = true;
    +                        }
    +                        context.addLast(s0);
    +                    }
    +                }
                 }
    -        } while (count < word);
    -
    -        // Print the diff with the region name above it
    -        System.out.println("[First diff: map file #1 (" + mapName0 + ")]");
    -        System.out.println(region);
    -        String diff0 = print_diff_helper(b0, wordOffset, prefix0);
    -
    -        System.out.println("\n[First diff: map file #2 (" + mapName1 + ")]");
    -        System.out.println(region);
    -        String diff1 = print_diff_helper(b1, wordOffset, prefix1);
    -
    -        System.out.printf("\nByte #%d at line #%d word #%d:\n", location, line_num, wordOffset);
    -        System.out.printf("%s: %s\n%s: %s\n", mapName0, diff0, mapName1, diff1);
    -
    -        f0.close();
    -        f1.close();
    -    }
    -
    -    static String print_diff_helper(BufferedReader b, int wordOffset, ArrayDeque prefix) throws Exception {
    -        int start = LINE_OFFSET + WORD_LEN * wordOffset;
    -        int end = start + WORD_LEN;
    -        String line = prefix.getLast();
    -        String diff = line.substring(start, end);
    -
    -        // Print previous lines
    -        for (String s : prefix) {
    -            if (s.equals(line)) {
    -                System.out.println(">" + s);
    -            } else {
    -                System.out.println(" " + s);
    +            if (printedDiffs < totalDiffs) {
    +                System.out.println("... " + (totalDiffs - printedDiffs) + " more lines of diffs omitted");
                 }
             }
    -
    -        // Print extra lines
    -        for (int i = 0; i < NUM_LINES / 2; i++) {
    -            System.out.println(" " + b.readLine());
    -        }
    -        return diff;
         }
     }
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/CanonicalPath.java b/test/hotspot/jtreg/runtime/cds/appcds/CanonicalPath.java
    new file mode 100644
    index 000000000000..d2948d9858d6
    --- /dev/null
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/CanonicalPath.java
    @@ -0,0 +1,73 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + *
    + */
    +
    +
    +/*
    + * @test
    + * @summary AOTClassLocationConfig::dumptime_get_class_location_index() should return the correct index
    + *          even if non-canonical paths are used in -classpath
    + * @bug 8396093
    + * @requires vm.cds.supports.aot.class.linking
    + * @library /test/lib
    + * @build CanonicalPath
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar CanonicalPathApp
    + * @run driver CanonicalPath
    + */
    +
    +import java.io.File;
    +import jdk.test.lib.cds.SimpleCDSAppTester;
    +import jdk.test.lib.Platform;
    +import jdk.test.lib.process.OutputAnalyzer;
    +
    +public class CanonicalPath {
    +    public static void main(String... args) throws Exception {
    +        SimpleCDSAppTester.of("CanonicalPath")
    +            .addVmArgs("-Xlog:aot+class=debug")
    +            .classpath(nonCanonicalPath("app.jar"))
    +            .appCommandLine("CanonicalPathApp")
    +            .setTrainingChecker((OutputAnalyzer output) -> {
    +                // CanonicalPathApp should be archived, even if its classpath
    +                // location uses a non-canonical file name.
    +                output.shouldMatch("aot,class.* app * CanonicalPathApp");
    +            })
    +            .runAOTWorkflow();
    +    }
    +
    +
    +    static String nonCanonicalPath(String fileName) throws Exception {
    +        fileName = new File(fileName).getAbsolutePath();
    +        if (Platform.isWindows()) {
    +            // Use UNC file name
    +            return "\\\\?\\" + fileName;
    +        } else {
    +            return TestCommon.createSymLink(fileName).getPath();
    +        }
    +    }
    +}
    +
    +class CanonicalPathApp {
    +    public static void main(String[] args) {
    +        System.out.println("HelloWorld");
    +    }
    +}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java
    new file mode 100644
    index 000000000000..f3654b6dc24a
    --- /dev/null
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java
    @@ -0,0 +1,57 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + *
    + */
    +
    +
    +/*
    + * @test
    + * @summary Test AOT archive unmapping with diagnostic flag AOTStressArchiveUnmapping
    + * @bug 8397369
    + * @library /test/lib
    + * @build StressArchiveUnmapping
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar StressArchiveUnmappingApp
    + * @run driver StressArchiveUnmapping
    + */
    +
    +import java.io.File;
    +import jdk.test.lib.cds.SimpleCDSAppTester;
    +import jdk.test.lib.Platform;
    +import jdk.test.lib.process.OutputAnalyzer;
    +
    +public class StressArchiveUnmapping {
    +    public static void main(String... args) throws Exception {
    +        SimpleCDSAppTester.of("StressArchiveUnmapping")
    +            .classpath("app.jar")
    +            .addVmArgs("-XX:+UnlockDiagnosticVMOptions",
    +                       "-XX:+AOTStressArchiveUnmapping",
    +                       "-Xlog:aot,class+path")
    +            .appCommandLine("StressArchiveUnmappingApp")
    +            .runAOTWorkflow();
    +    }
    +}
    +
    +class StressArchiveUnmappingApp {
    +    public static void main(String[] args) {
    +        System.out.println("HelloWorld");
    +    }
    +}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTCompileEagerly.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTCompileEagerly.java
    index 76f7faf75f2e..df3741ab2636 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTCompileEagerly.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTCompileEagerly.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -35,7 +35,6 @@
      * @run driver AOTCompileEagerly
      */
     
    -import java.io.File;
     import jdk.test.lib.cds.CDSTestUtils;
     import jdk.test.lib.helpers.ClassFileInstaller;
     import jdk.test.lib.process.OutputAnalyzer;
    @@ -53,7 +52,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             System.out.println("Training Run");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-cp", appJar, helloClass);
    @@ -63,7 +62,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             System.out.println("Assembly Phase");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -73,7 +72,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             System.out.println("Production Run with AOTCache defaults");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-cp", appJar, helloClass);
             out = CDSTestUtils.executeAndLog(pb, "prod-default");
    @@ -81,7 +80,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             System.out.println("Production Run with AOTCache and eager compilation explicitly ON");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-XX:+UnlockDiagnosticVMOptions",
                 "-XX:+AOTCompileEagerly",
    @@ -91,7 +90,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             System.out.println("Production Run with AOTCache and eager compilation explicitly OFF");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-XX:+UnlockDiagnosticVMOptions",
                 "-XX:-AOTCompileEagerly",
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTLoggingTag.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTLoggingTag.java
    index 86c2b420f758..9ea3965363c7 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTLoggingTag.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AOTLoggingTag.java
    @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Training Run");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-Xlog:aot",
    @@ -63,7 +63,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Assembly Phase");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -75,7 +75,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Production Run with AOTCache");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-Xlog:aot",
                 "-cp", appJar, helloClass);
    @@ -85,7 +85,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Production Run: errors should be printed with [aot] decoration");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=nosuchfile.aot",
                 "-XX:AOTMode=required",
                 "-cp", appJar, helloClass);
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/InvalidModuleOptions.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/InvalidModuleOptions.java
    index 9e7e77a40c65..81714a618e73 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/InvalidModuleOptions.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/InvalidModuleOptions.java
    @@ -143,13 +143,13 @@ public static void main(String[] args) throws Exception {
                     assemblyCmds = concat(assemblyCmds, assemblyOpt);
                 }
     
    -            ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(trainCmds);
    +            ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(trainCmds);
                 OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "train" + i);
                 out.shouldContain("Hello World");
                 out.shouldContain("AOTConfiguration recorded: " + aotConfigFile);
                 out.shouldHaveExitValue(0);
     
    -            pb = ProcessTools.createLimitedTestJavaProcessBuilder(assemblyCmds);
    +            pb = ProcessTools.createTestJavaProcessBuilder(assemblyCmds);
                 out = CDSTestUtils.executeAndLog(pb, "asm" + i);
                 out.shouldContain("An error has occurred while writing the AOT cache");
                 for (int j = 2; j < testSpec.length; j++) {
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCalleeInTraining.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCalleeInTraining.java
    new file mode 100644
    index 000000000000..fce60027ab3c
    --- /dev/null
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCalleeInTraining.java
    @@ -0,0 +1,98 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @summary Compile a call to a redefined method while recording AOT training data
    + * @requires vm.cds.supports.aot.class.linking & vm.compiler2.enabled & vm.jvmti
    + * @library /test/lib
    + * @run driver RedefineClassHelper
    + * @build RedefineCalleeInTraining jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar WhiteBox.jar jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar
    + *             RedefineCalleeInTrainingApp RedefineCalleeInTrainingTarget
    + * @run driver RedefineCalleeInTraining
    + */
    +
    +import java.io.InputStream;
    +import java.lang.reflect.Method;
    +
    +import jdk.test.lib.cds.SimpleCDSAppTester;
    +import jdk.test.whitebox.WhiteBox;
    +
    +public class RedefineCalleeInTraining {
    +    public static void main(String[] args) throws Exception {
    +        SimpleCDSAppTester.of("RedefineCalleeInTraining")
    +            .addVmArgs("-javaagent:redefineagent.jar",
    +                       "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI",
    +                       "-Xbootclasspath/a:WhiteBox.jar", "-Xbatch", "-XX:-TieredCompilation",
    +                       "-XX:CompileCommand=compileonly,RedefineCalleeInTrainingApp::caller",
    +                       "-Xlog:aot")
    +            .classpath("app.jar")
    +            .appCommandLine("RedefineCalleeInTrainingApp")
    +            .setTrainingChecker(out -> {
    +                out.shouldContain("Compiled caller after redefinition");
    +                out.shouldContain("Skipping RedefineCalleeInTrainingTarget: Has been redefined");
    +            })
    +            .setProductionChecker(out -> out.shouldContain("Compiled caller after redefinition"))
    +            .runAOTWorkflow();
    +    }
    +}
    +
    +class RedefineCalleeInTrainingApp {
    +    static int caller(int x) {
    +        return RedefineCalleeInTrainingTarget.callee(x);
    +    }
    +
    +    public static void main(String[] args) throws Exception {
    +        // Resolve the call and initialize the callee's holder before compilation.
    +        if (caller(1) != 2) {
    +            throw new RuntimeException("Unexpected result before redefinition");
    +        }
    +        try (InputStream in = RedefineCalleeInTrainingTarget.class.getResourceAsStream(
    +                 "RedefineCalleeInTrainingTarget.class")) {
    +            // Even an identical redefinition excludes the holder from training data.
    +            RedefineClassHelper.redefineClass(RedefineCalleeInTrainingTarget.class, in.readAllBytes());
    +        }
    +
    +        // The caller is not redefined, so its C2 compilation has training data.
    +        // Inlining the callee queries ciMethod::inline_instructions_size(), but
    +        // MethodTrainingData::make() returns null for the redefined callee.
    +        WhiteBox wb = WhiteBox.getWhiteBox();
    +        Method method = RedefineCalleeInTrainingApp.class.getDeclaredMethod("caller", int.class);
    +        wb.deoptimizeMethod(method);
    +        if (!wb.enqueueMethodForCompilation(method, 4) || wb.getMethodCompilationLevel(method) != 4) {
    +            throw new RuntimeException("Caller was not compiled by C2");
    +        }
    +        if (caller(2) != 3) {
    +            throw new RuntimeException("Unexpected result after redefinition");
    +        }
    +        System.out.println("Compiled caller after redefinition");
    +    }
    +}
    +
    +class RedefineCalleeInTrainingTarget {
    +    static int callee(int x) {
    +        return x + 1;
    +    }
    +}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCriticalClasses.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCriticalClasses.java
    index c4753ee38785..adfcef4eacb2 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCriticalClasses.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/RedefineCriticalClasses.java
    @@ -27,6 +27,7 @@
      * @test
      * @summary AOT training run should fail if critical classes have been redefined by JVMTI
      * @bug 8380409
    + * @requires vm.flagless
      * @requires vm.cds.supports.aot.class.linking
      * @library /test/lib
      * @run driver RedefineClassHelper
    @@ -56,7 +57,7 @@ public static void main(String... args) throws Exception {
             processArgs.add("app.jar");
             processArgs.add("RedefineCriticalClassesApp");
     
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(processArgs);
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(processArgs);
             CDSTestUtils.executeAndLog(pb, "train")
                 .shouldContain("Redefined: class java.lang.Class")
                 .shouldContain("Skipping java/lang/Class: Has been redefined")
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TrainingDataCleanup.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TrainingDataCleanup.java
    new file mode 100644
    index 000000000000..dd3c7937de81
    --- /dev/null
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TrainingDataCleanup.java
    @@ -0,0 +1,170 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/*
    + * @test
    + * @summary Excluded training data must not remain reachable through dependencies or CI records
    + * @requires vm.cds.supports.aot.class.linking & vm.compiler2.enabled & vm.jvmti
    + * @library /test/lib
    + * @run driver RedefineClassHelper
    + * @build TrainingDataCleanup jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar WhiteBox.jar jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar
    + *             TrainingDataCleanupApp TrainingDataCleanupTarget
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar custom.jar TrainingDataCleanupCustom
    + * @run driver TrainingDataCleanup
    + */
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.UncheckedIOException;
    +import java.lang.invoke.MethodHandle;
    +import java.lang.invoke.MethodHandles;
    +import java.lang.invoke.MethodType;
    +import java.lang.reflect.Method;
    +import java.net.URL;
    +import java.net.URLClassLoader;
    +import java.nio.charset.StandardCharsets;
    +import java.nio.file.Files;
    +import java.nio.file.Path;
    +import java.util.stream.Collectors;
    +
    +import jdk.test.lib.cds.SimpleCDSAppTester;
    +import jdk.test.lib.process.OutputAnalyzer;
    +import jdk.test.whitebox.WhiteBox;
    +
    +public class TrainingDataCleanup {
    +    public static void main(String[] args) throws Exception {
    +        SimpleCDSAppTester.of("TrainingDataCleanup")
    +            .addVmArgs("-javaagent:redefineagent.jar",
    +                       "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI",
    +                       "-Xbootclasspath/a:WhiteBox.jar", "-Xbatch", "-XX:-TieredCompilation",
    +                       "-XX:CompileCommand=compileonly,TrainingDataCleanup*::callee",
    +                       "-XX:CompileCommand=compileonly,TrainingDataCleanupApp::*Caller",
    +                       "-Xlog:aot+training=debug",
    +                       "-Xlog:aot+map=debug:file=training-data-cleanup.map:tags:filesize=0")
    +            .classpath("app.jar")
    +            .appCommandLine("TrainingDataCleanupApp")
    +            .setTrainingChecker(out -> {
    +                out.shouldContain("Cleanup KTD TrainingDataCleanupTarget");
    +                out.shouldContain("Cleanup KTD TrainingDataCleanupCustom");
    +                checkArchive();
    +            })
    +            .setAssemblyChecker(out -> checkArchive())
    +            .setProductionChecker(out -> out.shouldContain("Training data cleanup test passed"))
    +            .runAOTWorkflow();
    +    }
    +
    +    private static void checkArchive() {
    +        String entry = ".*@@\\s+(Klass|Method|Compile)TrainingData\\s+\\d+";
    +        String trainingData;
    +        try {
    +            // Heap-string details can contain non-UTF-8 bytes; these checks use ASCII entries.
    +            trainingData = Files.readString(Path.of("training-data-cleanup.map"), StandardCharsets.ISO_8859_1)
    +                                .lines()
    +                                .filter(line -> line.contains("TrainingData"))
    +                                .filter(line -> line.matches(entry + ".*"))
    +                                .collect(Collectors.joining("\n"));
    +        } catch (IOException e) {
    +            throw new UncheckedIOException(e);
    +        }
    +        OutputAnalyzer out = new OutputAnalyzer(trainingData, "");
    +        for (String kind : new String[] { "Klass", "Method", "Compile" }) {
    +            out.shouldMatch(".*@@\\s+" + kind + "TrainingData\\s+\\d+.*TrainingDataCleanupApp");
    +        }
    +        // A holderless entry has no class or method name after its size.
    +        out.shouldNotMatch(entry + "\\s*$");
    +        out.shouldNotMatch(entry + ".*TrainingDataCleanup(Target|Custom)");
    +    }
    +}
    +
    +class TrainingDataCleanupApp {
    +    static final MethodHandle CUSTOM = customTarget();
    +
    +    static MethodHandle customTarget() {
    +        try {
    +            URL jar = new File("custom.jar").toURI().toURL();
    +            URLClassLoader loader = new URLClassLoader(new URL[] { jar }, null);
    +            Class target = Class.forName("TrainingDataCleanupCustom", true, loader);
    +            return MethodHandles.privateLookupIn(target, MethodHandles.lookup())
    +                                .findStatic(target, "callee", MethodType.methodType(int.class, int.class));
    +        } catch (Exception e) {
    +            throw new RuntimeException(e);
    +        }
    +    }
    +
    +    static int redefinedCaller(int x) {
    +        return TrainingDataCleanupTarget.callee(x);
    +    }
    +
    +    static int customCaller(int x) throws Throwable {
    +        return (int) CUSTOM.invokeExact(x);
    +    }
    +
    +    static void compile(Class holder, String name) throws Exception {
    +        Method method = holder.getDeclaredMethod(name, int.class);
    +        WhiteBox wb = WhiteBox.getWhiteBox();
    +        if (!wb.enqueueMethodForCompilation(method, 4) || wb.getMethodCompilationLevel(method) != 4) {
    +            throw new RuntimeException("C2 did not compile " + method);
    +        }
    +    }
    +
    +    public static void main(String[] args) throws Throwable {
    +        if (redefinedCaller(1) != 2 || customCaller(1) != 2) {
    +            throw new RuntimeException("Unexpected result");
    +        }
    +        // Compile the callee first so that compiling its caller records a CI
    +        // query about the callee's inline instruction size.
    +        compile(TrainingDataCleanupTarget.class, "callee");
    +        compile(TrainingDataCleanupApp.class, "redefinedCaller");
    +        compile(MethodHandles.reflectAs(Method.class, CUSTOM).getDeclaringClass(), "callee");
    +        compile(TrainingDataCleanupApp.class, "customCaller");
    +
    +        // Redefinition invalidates training data while dependency lists and CI
    +        // records are still backed by growable arrays.
    +        try (InputStream in = TrainingDataCleanupTarget.class.getResourceAsStream(
    +                 "TrainingDataCleanupTarget.class")) {
    +            RedefineClassHelper.redefineClass(TrainingDataCleanupTarget.class, in.readAllBytes());
    +        }
    +
    +        // The custom target is excluded at dump time, before dependency lists
    +        // and CI records are materialized into archiveable arrays.
    +        if (redefinedCaller(2) != 3 || customCaller(2) != 3) {
    +            throw new RuntimeException("Unexpected result after redefinition");
    +        }
    +        System.out.println("Training data cleanup test passed");
    +    }
    +}
    +
    +class TrainingDataCleanupTarget {
    +    static int callee(int x) {
    +        return Math.abs(x) + 1;
    +    }
    +}
    +
    +class TrainingDataCleanupCustom {
    +    public static int callee(int x) {
    +        return Math.abs(x) + 1;
    +    }
    +}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TransformCriticalClasses.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TransformCriticalClasses.java
    index 9f25d58e01f8..262a109e5990 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TransformCriticalClasses.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/TransformCriticalClasses.java
    @@ -28,6 +28,7 @@
      * @summary AOT training run should fail if critical classes have been transformed by JVMTI
      *          with ClassFileLoadHook
      * @bug 8380409
    + * @requires vm.flagless
      * @requires vm.cds.supports.aot.class.linking
      * @library /test/lib
      * @build TransformCriticalClasses
    @@ -57,7 +58,7 @@ public static void main(String... args) throws Exception {
             processArgs.add("app.jar");
             processArgs.add("TransformCriticalClassesApp");
     
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(processArgs);
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(processArgs);
             CDSTestUtils.executeAndLog(pb, "train")
                 .shouldContain("Skipping java/lang/Class: From ClassFileLoadHook")
                 .shouldContain("Critical class java.lang.Class has been excluded. AOT configuration file cannot be written")
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AOTFlags.java b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AOTFlags.java
    index 35b08925ab7e..1c57de370f60 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AOTFlags.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AOTFlags.java
    @@ -28,6 +28,7 @@
      * @summary General use of AOT flags
      * @requires vm.cds.supports.aot.code.caching
      * @requires vm.flagless
    + * @modules java.base/jdk.internal.misc
      * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds/test-classes
      * @build Hello
      * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar hello.jar Hello
    @@ -35,6 +36,8 @@
      */
     
     import java.io.File;
    +
    +import jdk.internal.misc.PreviewFeatures;
     import jdk.test.lib.cds.CDSTestUtils;
     import jdk.test.lib.helpers.ClassFileInstaller;
     import jdk.test.lib.process.OutputAnalyzer;
    @@ -60,7 +63,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Training Run");
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-Xlog:aot=debug",
    @@ -75,7 +78,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Assembly Phase (AOTClassLinking unspecified -> should be enabled by default)");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -92,7 +95,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Production Run with AOTCache");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-Xlog:aot",
                 "-Xlog:aot+codecache*",
    @@ -106,7 +109,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Production Run with PrintSharedArchiveAndExit");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-XX:AOTMode=required",
                 "-XX:+PrintSharedArchiveAndExit",
    @@ -122,7 +125,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("AOTMode=off");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "--show-version",
                 "-Xlog:aot",
    @@ -136,7 +139,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("AOTMode=auto");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "--show-version",
                 "-Xlog:aot",
    @@ -151,7 +154,7 @@ static void positiveTests() throws Exception {
             //----------------------------------------------------------------------
             for (String mode : onOrRequired) {
                 printTestCase("AOTMode=" + mode);
    -            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +            pb = ProcessTools.createTestJavaProcessBuilder(
                     "-XX:AOTCache=" + aotCacheFile,
                     "--show-version",
                     "-Xlog:aot",
    @@ -166,7 +169,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Assembly Phase with -XX:-AOTClassLinking");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:-AOTClassLinking",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -185,7 +188,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Production Run with AOTCache created from the last step");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=" + aotCacheFile,
                 "-Xlog:aot",
                 "-Xlog:aot+codecache*",
    @@ -199,7 +202,7 @@ static void positiveTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Training run with -XX:-AOTClassLinking, but assembly run with -XX:+AOTClassLinking");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:-AOTClassLinking",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -210,7 +213,7 @@ static void positiveTests() throws Exception {
             out.shouldContain("AOTConfiguration recorded: " + aotConfigFile);
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:+AOTClassLinking",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -228,7 +231,7 @@ static void positiveTests() throws Exception {
             printTestCase("One step training run (JEP-514");
     
             // Set all AOTMode/AOTCacheOutput/AOTConfiguration
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -241,7 +244,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // Set AOTCacheOutput/AOTConfiguration only; Ergo for: AOTMode=record
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-Xlog:aot=debug",
    @@ -253,7 +256,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // Set AOTCacheOutput/AOTConfiguration/AOTMode=auto; Ergo changes: AOTMode=record
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=auto",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -266,7 +269,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // Set AOTCacheOutput only; Ergo for: AOTMode=record, AOTConfiguration=
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-Xlog:aot=debug",
                 "-cp", appJar, helloClass);
    @@ -277,7 +280,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // Set AOTCacheOutput/AOTMode=auto only; Ergo for: AOTMode=record, AOTConfiguration=
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=auto",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-Xlog:aot=debug",
    @@ -289,7 +292,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // Quoating of space characters in child JVM process
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-Dmy.prop=My string -Xshare:off here", // -Xshare:off should not be treated as a single VM opt for the child JVM
                 "-Xlog:aot=debug",
    @@ -302,7 +305,7 @@ static void positiveTests() throws Exception {
     
             // Training run with -XX:+PrintTieredEvents (see JDK-8362530).
             printTestCase("Training run with -XX:+PrintTieredEvents");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:+PrintTieredEvents",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -318,7 +321,7 @@ static void negativeTests() throws Exception {
                 + "-Xshare:off, -Xshare:dump, DumpLoadedClassList, SharedClassListFile, "
                 + "or SharedArchiveFile";
     
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xshare:off",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-cp", appJar, helloClass);
    @@ -327,7 +330,7 @@ static void negativeTests() throws Exception {
             out.shouldContain("Option AOTConfiguration" + mixOldNewErrSuffix);
             out.shouldNotHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:SharedArchiveFile=" + aotCacheFile,
                 "-XX:AOTCache=" + aotCacheFile,
                 "-cp", appJar, helloClass);
    @@ -337,7 +340,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Use AOTConfiguration without AOTMode/AOTCacheOutput");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-cp", appJar, helloClass);
     
    @@ -348,7 +351,7 @@ static void negativeTests() throws Exception {
             //----------------------------------------------------------------------
             for (String mode : onOrRequired) {
                 printTestCase("Use AOTConfiguration with AOTMode=" + mode);
    -            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +            pb = ProcessTools.createTestJavaProcessBuilder(
                     "-XX:AOTMode=" + mode,
                     "-XX:AOTConfiguration=" + aotConfigFile,
                     "-cp", appJar, helloClass);
    @@ -360,14 +363,14 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Use AOTMode without AOTCacheOutput or AOTConfiguration");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-cp", appJar, helloClass);
     
             out = CDSTestUtils.executeAndLog(pb, "neg");
             out.shouldContain("At least one of AOTCacheOutput and AOTConfiguration must be specified when using -XX:AOTMode=record");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-cp", appJar, helloClass);
     
    @@ -377,7 +380,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Bad AOTMode");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=foo",
                 "-cp", appJar, helloClass);
     
    @@ -387,7 +390,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Iterative: Non-existent AOTCache specified with -XX:AOTMode=record");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile + "-no-such-file",
    @@ -399,14 +402,14 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Iterative: cannot use AOTCache created with -XX:-AOTClassLinking");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCacheOutput=hello-noaotlink.aot",
                 "-XX:-AOTClassLinking",
                 "-cp", appJar, helloClass);
             out = CDSTestUtils.executeAndLog(pb, "re-train-neg");
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=hello-noaotlink.aot",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-cp", appJar, helloClass);
    @@ -414,7 +417,7 @@ static void negativeTests() throws Exception {
             out.shouldContain("AOT cache was created with AOTClassLinking disabled. It cannot be used when AOTClassLinking is enabled");
             out.shouldNotHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=hello-noaotlink.aot",
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -424,7 +427,7 @@ static void negativeTests() throws Exception {
             out.shouldContain("AOTClassLinking cannot be disabled when both AOTCache and AOTConfiguration are specified");
             out.shouldNotHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTCache=hello-noaotlink.aot",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-XX:-AOTClassLinking",
    @@ -435,7 +438,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("AOTCache/AOTCacheOutput not specified with -XX:AOTMode=create");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-cp", appJar, helloClass);
    @@ -446,7 +449,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("AOTCache and AOTCacheOutput have different values");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=aaa",
    @@ -459,7 +462,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("No such config file");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=no-such-file",
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -473,7 +476,7 @@ static void negativeTests() throws Exception {
             printTestCase("AOTConfiguration file cannot be used as a CDS archive");
     
             // first make sure we have a valid aotConfigFile
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-cp", appJar, helloClass);
    @@ -483,7 +486,7 @@ static void negativeTests() throws Exception {
     
             // Cannot use this config file as a AOT cache
             for (String mode : onOrRequired) {
    -            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +            pb = ProcessTools.createTestJavaProcessBuilder(
                     "-XX:AOTMode=" + mode,
                     "-XX:AOTCache=" + aotConfigFile,
                     "-cp", appJar, helloClass);
    @@ -494,7 +497,7 @@ static void negativeTests() throws Exception {
             }
     
             // Cannot use this config file as a CDS archive
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xshare:on",
                 "-XX:SharedArchiveFile=" + aotConfigFile,
                 "-cp", appJar, helloClass);
    @@ -506,7 +509,7 @@ static void negativeTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("Classpath mismatch when creating archive");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -521,7 +524,7 @@ static void negativeTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("Cannot use multiple paths in AOTConfiguration");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile + File.pathSeparator + "dummy",
                 "-cp", "noSuchJar.jar");
    @@ -533,7 +536,7 @@ static void negativeTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("Cannot use multiple paths in AOTCache");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile + File.pathSeparator + "dummy",
    @@ -547,7 +550,7 @@ static void negativeTests() throws Exception {
             printTestCase("Cannot use a classic CDS archive with -XX:+AOTClassLinking");
             String staticArchive = "static.jsa";
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xshare:dump",
                 "-XX:SharedArchiveFile=" + staticArchive,
                 "-XX:+AOTClassLinking");
    @@ -560,13 +563,13 @@ static void negativeTests() throws Exception {
             staticArchive = "static.jsa";
             String dynamicArchive = "dynamic.jsa";
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xshare:dump",
                 "-XX:SharedArchiveFile=" + staticArchive);
             out = CDSTestUtils.executeAndLog(pb, "static");
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:SharedArchiveFile=" + staticArchive,
                 "-XX:ArchiveClassesAtExit=" + dynamicArchive,
                 "--version");
    @@ -574,7 +577,7 @@ static void negativeTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             for (String mode : onOrRequired) {
    -            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +            pb = ProcessTools.createTestJavaProcessBuilder(
                     "-Xlog:aot",
                     "-XX:AOTMode=" + mode,
                     "-XX:AOTCache=" + dynamicArchive,
    @@ -586,6 +589,179 @@ static void negativeTests() throws Exception {
                 out.shouldHaveExitValue(1);
             }
     
    +        // Valhalla Flags
    +        // Note that createLimitedTestJavaProcessBuilder is used so the use of
    +        // --enable-preview can be controlled.
    +
    +        //----------------------------------------------------------------------
    +        if (PreviewFeatures.isEnabled()) {
    +            printTestCase("Training-Assembly Preview mismatch");
    +            // Disable individual Valhalla flags to check just preview mode
    +            pb = ProcessTools.createTestJavaProcessBuilder(
    +                "--enable-preview",
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:-UseArrayFlattening",
    +                "-XX:-UseFieldFlattening",
    +                "-XX:-ValueTypePassFieldsAsArgs",
    +                "-XX:-ValueTypeReturnedAsFields",
    +                "-XX:-UseNullFreeNonAtomicValueFlattening",
    +                "-XX:-UseNullFreeAtomicValueFlattening",
    +                "-XX:-UseNullableAtomicValueFlattening",
    +                "-XX:-UseNullableNonAtomicValueFlattening",
    +                "-XX:AOTMode=record",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldHaveExitValue(0);
    +
    +            // Assembly run without preview specified
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:AOTMode=create",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldContain("This AOT configuration file was created with --enable-preview. It is incompatible with the current JVM setting");
    +            out.shouldNotHaveExitValue(0);
    +
    +            printTestCase("Assembly-Production Preview mismatch");
    +            // Disable individual Valhalla flags to check just preview mode
    +            pb = ProcessTools.createTestJavaProcessBuilder(
    +                "--enable-preview",
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:-UseArrayFlattening",
    +                "-XX:-UseFieldFlattening",
    +                "-XX:-ValueTypePassFieldsAsArgs",
    +                "-XX:-ValueTypeReturnedAsFields",
    +                "-XX:-UseNullFreeNonAtomicValueFlattening",
    +                "-XX:-UseNullFreeAtomicValueFlattening",
    +                "-XX:-UseNullableAtomicValueFlattening",
    +                "-XX:-UseNullableNonAtomicValueFlattening",
    +                "-XX:AOTMode=create",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldHaveExitValue(0);
    +
    +            // Production run without preview specified
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:AOTMode=required",
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldContain("This AOT cache was created with --enable-preview. It is incompatible with the current JVM setting");
    +            out.shouldNotHaveExitValue(0);
    +
    +            printTestCase("Training-Assembly Preview mismatch 2");
    +            // Train without preview
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:AOTMode=record",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldHaveExitValue(0);
    +
    +            // Assembly run with preview but individual flags disabled
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "--enable-preview",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:-UseArrayFlattening",
    +                "-XX:-UseFieldFlattening",
    +                "-XX:-ValueTypePassFieldsAsArgs",
    +                "-XX:-ValueTypeReturnedAsFields",
    +                "-XX:-UseNullFreeNonAtomicValueFlattening",
    +                "-XX:-UseNullFreeAtomicValueFlattening",
    +                "-XX:-UseNullableAtomicValueFlattening",
    +                "-XX:-UseNullableNonAtomicValueFlattening",
    +                "-XX:AOTMode=create",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldContain("This AOT configuration file was not created with --enable-preview. It is incompatible with the current JVM setting");
    +            out.shouldNotHaveExitValue(0);
    +
    +            printTestCase("Assembly-Production Preview mismatch 2");
    +            // Assembly run without preview
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:AOTMode=create",
    +                "-XX:AOTConfiguration=" + aotConfigFile,
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldHaveExitValue(0);
    +
    +            // Production run with preview but individual flags disabled
    +            pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +                "--enable-preview",
    +                "-XX:+UnlockDiagnosticVMOptions",
    +                "-XX:+UnlockExperimentalVMOptions",
    +                "-XX:-UseArrayFlattening",
    +                "-XX:-UseFieldFlattening",
    +                "-XX:-ValueTypePassFieldsAsArgs",
    +                "-XX:-ValueTypeReturnedAsFields",
    +                "-XX:-UseNullFreeNonAtomicValueFlattening",
    +                "-XX:-UseNullFreeAtomicValueFlattening",
    +                "-XX:-UseNullableAtomicValueFlattening",
    +                "-XX:-UseNullableNonAtomicValueFlattening",
    +                "-XX:AOTMode=required",
    +                "-XX:AOTCache=" + aotCacheFile,
    +                "-Xlog:aot=debug",
    +                "-cp", appJar, helloClass);
    +            out = CDSTestUtils.executeAndLog(pb, "neg");
    +            out.shouldContain("This AOT cache was not created with --enable-preview. It is incompatible with the current JVM setting");
    +            out.shouldNotHaveExitValue(0);
    +
    +            String[] valhallaFlags = {
    +                "UseArrayFlattening",
    +                "UseFieldFlattening",
    +                "ValueTypePassFieldsAsArgs",
    +                "ValueTypeReturnedAsFields",
    +                "UseNullFreeNonAtomicValueFlattening",
    +                "UseNullFreeAtomicValueFlattening",
    +                "UseNullableAtomicValueFlattening",
    +                "UseNullableNonAtomicValueFlattening",
    +                "RestrictReservedStack"
    +            };
    +
    +            String[] valhallaNumericFlags = {
    +                "FlatteningBudget",
    +                "DiagnoseSyncOnValueBasedClasses",
    +                "FlatArrayElementMaxOops"
    +            };
    +
    +            for (String flag : valhallaFlags) {
    +                testMismatch(flag, false);
    +            }
    +
    +            for (String flag : valhallaNumericFlags) {
    +                testMismatch(flag, true);
    +            }
    +        }
    +
             //----------------------------------------------------------------------
             testEmptyValue("AOTCache");
             testEmptyValue("AOTConfiguration");
    @@ -593,9 +769,117 @@ static void negativeTests() throws Exception {
             testEmptyValue("AOTCacheOutput");
         }
     
    +    // Test mismatch in both directions
    +    static void testMismatch(String flag, boolean numericFlag) throws Exception {
    +        testTrainingAssemblyMismatchHelper(flag, numericFlag, true);
    +        testTrainingAssemblyMismatchHelper(flag, numericFlag, false);
    +
    +        testAssemblyProductionMismatchHelper(flag, numericFlag, true);
    +        testAssemblyProductionMismatchHelper(flag, numericFlag, false);
    +    }
    +
    +    static String mismatchFlagPattern(String flag) {
    +        return "The.*'s " + flag + " setting [(].*[)] does not equal the current setting [(].*[)]";
    +    }
    +
    +    // Run training run with flag enabled and assembly run with the flag disabled
    +    static void testTrainingAssemblyMismatchHelper(String flag, boolean numericFlag, boolean reverse) throws Exception {
    +        String flagMode0;
    +        String flagMode1;
    +        if (numericFlag) {
    +            flagMode0 = "-XX:" + flag + "=0";
    +            flagMode1 = "-XX:" + flag + "=1";
    +        } else {
    +            flagMode0 = "-XX:+" + flag;
    +            flagMode1 = "-XX:-" + flag;
    +        }
    +
    +        // Training
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
    +            "-XX:+UnlockDiagnosticVMOptions",
    +            "-XX:+UnlockExperimentalVMOptions",
    +            "-XX:AOTMode=record",
    +            "-XX:AOTConfiguration=" + aotConfigFile,
    +            reverse ? flagMode0 : flagMode1,
    +            "-Xlog:cds=debug,aot=debug",
    +            "-cp", appJar, helloClass);
    +
    +        OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "neg");
    +        out.shouldHaveExitValue(0);
    +
    +        // Assembly
    +        pb = ProcessTools.createTestJavaProcessBuilder(
    +            "-XX:+UnlockDiagnosticVMOptions",
    +            "-XX:+UnlockExperimentalVMOptions",
    +            "-XX:AOTMode=create",
    +            "-XX:AOTConfiguration=" + aotConfigFile,
    +            "-XX:AOTCache=" + aotCacheFile,
    +            reverse ? flagMode1 : flagMode0,
    +            "-Xlog:cds=debug,aot=debug",
    +            "-cp", appJar, helloClass);
    +
    +        out = CDSTestUtils.executeAndLog(pb, "neg");
    +        out.shouldMatch(mismatchFlagPattern(flag));
    +        out.shouldNotHaveExitValue(0);
    +    }
    +
    +    // Run assembly run with flag enabled and production run with the flag disabled
    +    static void testAssemblyProductionMismatchHelper(String flag, boolean numericFlag, boolean reverse) throws Exception {
    +        String flagMode0;
    +        String flagMode1;
    +        if (numericFlag) {
    +            flagMode0 = "-XX:" + flag + "=0";
    +            flagMode1 = "-XX:" + flag + "=1";
    +        } else {
    +            flagMode0 = "-XX:+" + flag;
    +            flagMode1 = "-XX:-" + flag;
    +        }
    +
    +        // Training must have same configuration as assembly
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
    +            "-XX:+UnlockDiagnosticVMOptions",
    +            "-XX:+UnlockExperimentalVMOptions",
    +            "-XX:AOTMode=record",
    +            "-XX:AOTConfiguration=" + aotConfigFile,
    +            reverse ? flagMode0 : flagMode1,
    +            "-Xlog:cds=debug,aot=debug",
    +            "-cp", appJar, helloClass);
    +
    +        OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "neg");
    +        out.shouldHaveExitValue(0);
    +
    +        // Assembly
    +        pb = ProcessTools.createTestJavaProcessBuilder(
    +            "-XX:+UnlockDiagnosticVMOptions",
    +            "-XX:+UnlockExperimentalVMOptions",
    +            "-XX:AOTMode=create",
    +            "-XX:AOTConfiguration=" + aotConfigFile,
    +            "-XX:AOTCache=" + aotCacheFile,
    +            reverse ? flagMode0 : flagMode1,
    +            "-Xlog:cds=debug,aot=debug",
    +            "-cp", appJar, helloClass);
    +
    +        out = CDSTestUtils.executeAndLog(pb, "neg");
    +        out.shouldHaveExitValue(0);
    +
    +        // Production
    +        pb = ProcessTools.createTestJavaProcessBuilder(
    +            "-XX:+UnlockDiagnosticVMOptions",
    +            "-XX:+UnlockExperimentalVMOptions",
    +            "-XX:AOTMode=required",
    +            "-XX:AOTCache=" + aotCacheFile,
    +            reverse ? flagMode1 : flagMode0,
    +            "-Xlog:cds=debug,aot=debug",
    +            "-cp", appJar, helloClass);
    +
    +        out = CDSTestUtils.executeAndLog(pb, "neg");
    +        out.shouldMatch(mismatchFlagPattern(flag));
    +        out.shouldNotHaveExitValue(0);
    +    }
    +
         static void testEmptyValue(String option) throws Exception {
             printTestCase("Empty values for " + option);
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:" + option + "=", "--version");
             OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "neg");
             out.shouldContain("Improperly specified VM option '" + option + "='");
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AssemblySubProcessFailure.java b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AssemblySubProcessFailure.java
    index a4ad79e4bfb9..8cf575d46063 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AssemblySubProcessFailure.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/AssemblySubProcessFailure.java
    @@ -52,7 +52,7 @@ public static void main(String[] args) throws Exception {
             //
             // The easiest way to trigger a failure is to pass a bad VM option, only to the
             // sub-process using JDK_AOT_VM_OPTIONS.
    -        ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-cp", appJar, helloClass);
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/FileNameSubstitution.java b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/FileNameSubstitution.java
    index 23b82b124d91..14095d7b42ab 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/FileNameSubstitution.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/FileNameSubstitution.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -34,10 +34,9 @@
      */
     
     import java.io.File;
    -import java.nio.file.Files;
    -import java.nio.file.Path;
     import java.util.regex.Matcher;
     import java.util.regex.Pattern;
    +
     import jdk.test.lib.cds.CDSTestUtils;
     import jdk.test.lib.helpers.ClassFileInstaller;
     import jdk.test.lib.process.OutputAnalyzer;
    @@ -61,7 +60,7 @@ static void positiveTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("AOTConfiguration (two-command training)");
             removeOutputFiles();
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=test-%p.aotconfig",
                 "-Xlog:os",
    @@ -74,7 +73,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // "create" with AOTCache
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=test-%p.aot",
    @@ -87,7 +86,7 @@ static void positiveTests() throws Exception {
             out.shouldHaveExitValue(0);
     
             // "create" with AOTCacheOutput
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCacheOutput=test-%p.aot",
    @@ -102,7 +101,7 @@ static void positiveTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("AOTConfiguration/AOTCache (single-command training)");
             removeOutputFiles();
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=test-%p.aotconfig",
                 "-XX:AOTCacheOutput=test-%p.aot",
    @@ -122,7 +121,7 @@ static void positiveTests() throws Exception {
             //----------------------------------------------------------------------
             printTestCase("AOTConfiguration (two-command training) -- %t");
             removeOutputFiles();
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=test-%t.aotconfig",
                 "-Xlog:os",
    @@ -140,7 +139,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Cannot use %p twice");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=test-%p%p.aotconfig",
                 "-Xlog:os",
    @@ -152,7 +151,7 @@ static void negativeTests() throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("Cannot use %t twice");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=test-%t%t.aotconfig",
                 "-Xlog:os",
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/JDK_AOT_VM_OPTIONS.java b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/JDK_AOT_VM_OPTIONS.java
    index e8f98bf720cd..dbb559b8951c 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/JDK_AOT_VM_OPTIONS.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotFlags/JDK_AOT_VM_OPTIONS.java
    @@ -54,7 +54,7 @@ public static void main(String[] args) throws Exception {
             //----------------------------------------------------------------------
             printTestCase("JDK_AOT_VM_OPTIONS (single-command training)");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTCacheOutput=" + aotCacheFile,
                 "-Xlog:aot=debug",
    @@ -70,7 +70,7 @@ public static void main(String[] args) throws Exception {
     
             //----------------------------------------------------------------------
             printTestCase("JDK_AOT_VM_OPTIONS (two-command training)");
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-Xlog:aot=debug",
    @@ -82,7 +82,7 @@ public static void main(String[] args) throws Exception {
             out.shouldHaveExitValue(0);
     
             //----------------------------------------------------------------------
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -98,7 +98,7 @@ public static void main(String[] args) throws Exception {
             String optionsFile = "opts.txt";
             Files.writeString(Path.of(optionsFile), "-XX:AOTMode=create");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:VMOptionsFile=" + optionsFile,
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    @@ -113,7 +113,7 @@ public static void main(String[] args) throws Exception {
             printTestCase("Using -XX:VMOptionsFile inside JDK_AOT_VM_OPTIONS)");
             Files.writeString(Path.of(optionsFile), "-XX:+PrintFlagsFinal");
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
                 "-XX:AOTCache=" + aotCacheFile,
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotProfile/AOTProfileFlags.java b/test/hotspot/jtreg/runtime/cds/appcds/aotProfile/AOTProfileFlags.java
    index 446b73ef9d5b..3c583aec8a70 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/aotProfile/AOTProfileFlags.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotProfile/AOTProfileFlags.java
    @@ -74,7 +74,7 @@ static void trainAndRun(String testName, String trainingFlags, String production
             OutputAnalyzer out;
     
             // first make sure we have a valid aotConfigFile with default value of TypeProfileLevel
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xlog:aot",
                 "-XX:AOTMode=record",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -85,7 +85,7 @@ static void trainAndRun(String testName, String trainingFlags, String production
             out = CDSTestUtils.executeAndLog(pb, "train");
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xlog:aot",
                 "-XX:AOTMode=create",
                 "-XX:AOTConfiguration=" + aotConfigFile,
    @@ -97,7 +97,7 @@ static void trainAndRun(String testName, String trainingFlags, String production
             out = CDSTestUtils.executeAndLog(pb, "assemble");
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xlog:aot",
                 "-XX:AOTCache=" + aotCacheFile,
                 "-XX:+UnlockExperimentalVMOptions",
    @@ -108,7 +108,7 @@ static void trainAndRun(String testName, String trainingFlags, String production
             out.shouldNotMatch(errorPattern);
             out.shouldHaveExitValue(0);
     
    -        pb = ProcessTools.createLimitedTestJavaProcessBuilder(
    +        pb = ProcessTools.createTestJavaProcessBuilder(
                 "-Xlog:aot",
                 "-XX:AOTCache=" + aotCacheFile,
                 "-XX:+UnlockExperimentalVMOptions",
    @@ -121,19 +121,19 @@ static void trainAndRun(String testName, String trainingFlags, String production
         }
     
         public static void testFlagsMismatch() throws Exception {
    -        String errorPattern = ".*Profile.* setting .* does not equal the current .*Profile.* setting.*";
    +        String errorPattern = ".*Profile.* setting .* does not equal the current setting.*";
             trainAndRun("TypeProfileLevel", "-XX:TypeProfileLevel=222", "-XX:TypeProfileLevel=111", errorPattern);
             trainAndRun("TypeProfileArgsLimit", "-XX:TypeProfileArgsLimit=2", "-XX:TypeProfileArgsLimit=3",
    -                    "TypeProfileArgsLimit setting \\(2\\) does not equal the current TypeProfileArgsLimit setting \\(3\\)");
    +                    "TypeProfileArgsLimit setting \\(2\\) does not equal the current setting \\(3\\)");
             trainAndRun("TypeProfileParmsLimit", "-XX:TypeProfileParmsLimit=2", "-XX:TypeProfileParmsLimit=3",
    -                    "TypeProfileParmsLimit setting \\(2\\) does not equal the current TypeProfileParmsLimit setting \\(3\\)");
    +                    "TypeProfileParmsLimit setting \\(2\\) does not equal the current setting \\(3\\)");
             trainAndRun("TypeProfileWidth", "-XX:TypeProfileWidth=2", "-XX:TypeProfileWidth=3", errorPattern);
             trainAndRun("ProfileExceptionHandlers", "-XX:+ProfileExceptionHandlers", "-XX:-ProfileExceptionHandlers", errorPattern);
             if (Platform.isDebugBuild()) {
               trainAndRun("ProfileTraps", "-XX:+ProfileTraps", "-XX:-ProfileTraps", errorPattern);
               trainAndRun("TypeProfileCasts", "-XX:+TypeProfileCasts", "-XX:-TypeProfileCasts", errorPattern);
             }
    -        errorPattern = "SpecTrapLimitExtraEntries setting .* does not equal the current SpecTrapLimitExtraEntries setting";
    +        errorPattern = "SpecTrapLimitExtraEntries setting .* does not equal the current setting";
             trainAndRun("SpecTrapLimitExtraEntries", "-XX:SpecTrapLimitExtraEntries=2", "-XX:SpecTrapLimitExtraEntries=3", errorPattern);
         }
     
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchivedArrayLayoutsApp.java b/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchivedArrayLayoutsApp.java
    deleted file mode 100644
    index c19ad521dc82..000000000000
    --- a/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchivedArrayLayoutsApp.java
    +++ /dev/null
    @@ -1,129 +0,0 @@
    -/*
    - * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    - *
    - * This code is free software; you can redistribute it and/or modify it
    - * under the terms of the GNU General Public License version 2 only, as
    - * published by the Free Software Foundation.
    - *
    - * This code is distributed in the hope that it will be useful, but WITHOUT
    - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    - * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    - * version 2 for more details (a copy is included in the LICENSE file that
    - * accompanied this code).
    - *
    - * You should have received a copy of the GNU General Public License version
    - * 2 along with this work; if not, write to the Free Software Foundation,
    - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    - *
    - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    - * or visit www.oracle.com if you need additional information or have any
    - * questions.
    - *
    - */
    -
    -import java.util.Arrays;
    -import jdk.internal.value.ValueClass;
    -
    -public class ArchivedArrayLayoutsApp {
    -
    -    public static class ArchivedData {
    -        Point[] pointArray;
    -        Point[] nullRestrictedArray;
    -        Point[] nullableAtomicArray;
    -    }
    -
    -    public static value class Point implements Comparable {
    -        int x, y;
    -
    -        public int compareTo(Point p) {
    -            return (x - p.x) - (y - p.y);
    -        }
    -
    -        public String toString() {
    -            return "(" + x + ", " + y + ")";
    -        }
    -
    -        public Point(int x, int y) {
    -            this.x = x;
    -            this.y = y;
    -        }
    -    }
    -
    -    static ArchivedData archivedObjects;
    -    static boolean restored;
    -    static {
    -        if (archivedObjects == null) {
    -            restored = false;
    -            System.out.println("Not archived");
    -            archivedObjects = new ArchivedData();
    -
    -            // Point cannot be flattened and so will create a RefArrayKlass
    -            archivedObjects.pointArray = new Point[3];
    -            archivedObjects.pointArray[0] = new Point(0, 1);
    -            archivedObjects.pointArray[1] = new Point(1, 0);
    -            archivedObjects.pointArray[2] = new Point(1, 1);
    -
    -
    -            // An array of null-restricted Point can be flattened
    -            archivedObjects.nullRestrictedArray = (Point[])ValueClass.newNullRestrictedAtomicArray(Point.class, 3, new Point(0, 0));
    -            archivedObjects.nullRestrictedArray[0] = new Point(0, 1);
    -            archivedObjects.nullRestrictedArray[1] = new Point(1, 0);
    -            archivedObjects.nullRestrictedArray[2] = new Point(1, 1);
    -
    -            // A nullable array of Point cannot be flattened so it will a RefArrayKlass with a different layout
    -            archivedObjects.nullableAtomicArray = (Point[])ValueClass.newNullableAtomicArray(Point.class, 3);
    -            archivedObjects.nullableAtomicArray[0] = new Point(0, 1);
    -            archivedObjects.nullableAtomicArray[1] = new Point(1, 0);
    -            archivedObjects.nullableAtomicArray[2] = new Point(1, 1);
    -        } else {
    -            restored = true;
    -            System.out.println("Initialized from CDS");
    -        }
    -    }
    -
    -
    -    public static void checkFlat(Point[] p, boolean shouldBe) throws Exception {
    -        boolean isFlat = ValueClass.isFlatArray(p);
    -        if (isFlat && !shouldBe) {
    -            throw new RuntimeException("Should not be flat");
    -        }
    -        if (!isFlat && shouldBe) {
    -            throw new RuntimeException("Should be flat");
    -        }
    -    }
    -
    -    public static void checkArray(Point[] p0, Point[] p1) {
    -        if (Arrays.compare(p0, p1) != 0) {
    -            for (Point i : p0) {
    -                System.out.println(i);
    -            }
    -            System.out.println("vs");
    -            for (Point i : p1) {
    -                System.out.println(i);
    -            }
    -            System.out.println();
    -            throw new RuntimeException("Array not restored correctly");
    -        }
    -    }
    -
    -    public static void main(String[] args) throws Exception {
    -
    -        checkFlat(archivedObjects.pointArray, false);
    -        checkFlat(archivedObjects.nullRestrictedArray, true);
    -        checkFlat(archivedObjects.nullableAtomicArray, false);
    -
    -        if (restored) {
    -            Point[] runtimeArray = new Point[3];
    -            runtimeArray[0] = new Point(0, 1);
    -            runtimeArray[1] = new Point(1, 0);
    -            runtimeArray[2] = new Point(1, 1);
    -
    -            checkArray(archivedObjects.pointArray, runtimeArray);
    -            checkArray(archivedObjects.nullRestrictedArray, runtimeArray);
    -            checkArray(archivedObjects.nullableAtomicArray, runtimeArray);
    -        }
    -
    -        System.out.println("PASSED");
    -    }
    -}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/IncompatibleOptions.java b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/IncompatibleOptions.java
    index 5a193bf2ce29..c5a0157d22c3 100644
    --- a/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/IncompatibleOptions.java
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/IncompatibleOptions.java
    @@ -82,9 +82,9 @@
     
     public class IncompatibleOptions {
         static final String OBJ_ALIGNMENT_MISMATCH =
    -        "The shared archive file's ObjectAlignmentInBytes of .* does not equal the current ObjectAlignmentInBytes of";
    +        "The shared archive file's ObjectAlignmentInBytes setting .* does not equal the current setting";
         static final String COMPACT_STRING_MISMATCH =
    -        "The shared archive file's CompactStrings setting .* does not equal the current CompactStrings setting";
    +        "The shared archive file's CompactStrings setting .* does not equal the current setting";
         static final String COMPRESSED_OOPS_NOT_CONSISTENT =
             "The saved state of UseCompressedOops \\(%d\\) is different from runtime \\(%d\\), CDS will be disabled.";
         static final String COMPRESSED_OOPS_NOT_CONSISTENT_10 = COMPRESSED_OOPS_NOT_CONSISTENT.formatted(1, 0);
    diff --git a/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java b/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java
    index 1171efa12e39..bd0b0688cc6f 100644
    --- a/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java
    +++ b/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/MyPackage/ASGCTBaseTest.java
    @@ -25,13 +25,23 @@
     package MyPackage;
     
     /**
    - * @test
    + * @test id=platform
      * @summary Verifies that AsyncGetCallTrace is call-able and provides sane information.
    - * @compile ASGCTBaseTest.java
      * @requires os.family == "linux"
      * @requires os.arch=="x86" | os.arch=="i386" | os.arch=="amd64" | os.arch=="x86_64" | os.arch=="arm" | os.arch=="aarch64" | os.arch=="ppc64" | os.arch=="ppc64le" | os.arch=="s390x" | os.arch=="riscv64"
      * @requires vm.jvmti
    - * @run main/othervm/native -agentlib:AsyncGetCallTraceTest MyPackage.ASGCTBaseTest
    + * @requires test.thread.factory == null
    + * @run main/othervm/native -agentlib:AsyncGetCallTraceTest MyPackage.ASGCTBaseTest platform
    + */
    +
    +/**
    + * @test id=virtual
    + * @requires os.family == "linux"
    + * @requires os.arch=="x86" | os.arch=="i386" | os.arch=="amd64" | os.arch=="x86_64" | os.arch=="arm" | os.arch=="aarch64" | os.arch=="ppc64" | os.arch=="ppc64le" | os.arch=="s390x" | os.arch=="riscv64"
    + * @requires vm.jvmti
    + * @requires vm.continuations
    + * @requires test.thread.factory == null
    + * @run main/othervm/native -agentlib:AsyncGetCallTraceTest MyPackage.ASGCTBaseTest virtual
      */
     
     public class ASGCTBaseTest {
    @@ -47,8 +57,17 @@ public class ASGCTBaseTest {
     
       private static native boolean checkAsyncGetCallTraceCall();
     
    -  public static void main(String[] args) {
    -    if (!checkAsyncGetCallTraceCall()) {
    +  private static boolean check(boolean virtual) throws InterruptedException {
    +    boolean[] result = new boolean[1];
    +    Thread.Builder builder = virtual ? Thread.ofVirtual() : Thread.ofPlatform();
    +    Thread thread = builder.start(() -> result[0] = checkAsyncGetCallTraceCall());
    +    thread.join();
    +    return result[0];
    +  }
    +
    +  public static void main(String[] args) throws InterruptedException {
    +    boolean virtual = args.length > 0 && args[0].equals("virtual");
    +    if (!check(virtual)) {
           throw new RuntimeException("AsyncGetCallTrace call failed.");
         }
       }
    diff --git a/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/libAsyncGetCallTraceTest.cpp b/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/libAsyncGetCallTraceTest.cpp
    index ccdaf985d579..64ad9f9aa1de 100644
    --- a/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/libAsyncGetCallTraceTest.cpp
    +++ b/test/hotspot/jtreg/serviceability/AsyncGetCallTrace/libAsyncGetCallTraceTest.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
      * Copyright (c) 2019, Google and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
    @@ -95,6 +95,26 @@ static void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) {
       }
     }
     
    +// The first AsyncGetCallTrace frame below the GetStackTrace frames of a virtual thread is the continuation entry.
    +static bool isContinuationEnterSpecial(jmethodID method) {
    +  JvmtiDeallocator name;
    +  jvmtiError err = jvmti->GetMethodName(method, name.get_addr(), nullptr, nullptr);
    +  if (err != JVMTI_ERROR_NONE || name.get() == nullptr || strcmp(name.get(), "enterSpecial") != 0) {
    +    return false;
    +  }
    +  jclass klass;
    +  err = jvmti->GetMethodDeclaringClass(method, &klass);
    +  if (err != JVMTI_ERROR_NONE) {
    +    return false;
    +  }
    +  JvmtiDeallocator signature;
    +  err = jvmti->GetClassSignature(klass, signature.get_addr(), nullptr);
    +  if (err != JVMTI_ERROR_NONE || signature.get() == nullptr) {
    +    return false;
    +  }
    +  return strcmp(signature.get(), "Ljdk/internal/vm/Continuation;") == 0;
    +}
    +
     extern "C" {
     
     static
    @@ -245,12 +265,15 @@ Java_MyPackage_ASGCTBaseTest_checkAsyncGetCallTraceCall(JNIEnv* env, jclass cls)
     
       jvmti->GetStackTrace(thread, 0, MAX_DEPTH, gstFrames, &gstCount);
     
    -  if (gstCount != trace.num_frames) {
    +  // On a virtual thread AsyncGetCallTrace walks on into the carrier where GetStackTrace
    +  // stops at the continuation entry.
    +  bool carrier_frames = trace.num_frames > gstCount;
    +  if (!carrier_frames && gstCount != trace.num_frames) {
         fprintf(stderr, "GetStackTrace and AsyncGetCallTrace return different number of frames: %d vs %d)", gstCount, trace.num_frames);
         return false;
       }
     
    -  for (int i = 0; i < trace.num_frames; ++i) {
    +  for (int i = 0; i < gstCount; ++i) {
         if (trace.frames[i].lineno == -3) {
           if (gstFrames[i].location != -1) {
             fprintf(stderr, "%d: ASGCT found native frame but GST did not\n", i);
    @@ -263,6 +286,11 @@ Java_MyPackage_ASGCTBaseTest_checkAsyncGetCallTraceCall(JNIEnv* env, jclass cls)
           }
         }
       }
    +
    +  if (carrier_frames && !isContinuationEnterSpecial(trace.frames[gstCount].method_id)) {
    +    fprintf(stderr, "%d: frame below the GetStackTrace frames is not Continuation.enterSpecial\n", gstCount);
    +    return false;
    +  }
       return true;
     }
     
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorMultiArrayTest.java b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorMultiArrayTest.java
    index 19903f1e7bf6..08cbcbb90106 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorMultiArrayTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorMultiArrayTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
      * Copyright (c) 2018, Google and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
    @@ -26,13 +26,46 @@
     
     import java.util.List;
     
    -/**
    - * @test
    +/*
    + * @test id=expand
    + * @summary Verifies the JVMTI Heap Monitor API when allocating a multi-array.
    + * @requires vm.jvmti
    + * @build Frame HeapMonitor
    + * @compile HeapMonitorMultiArrayTest.java
    + * @run main/othervm/native -XX:+IgnoreUnrecognizedVMOptions -XX:-DeoptimizeALot
    + *      -agentlib:HeapMonitorTest MyPackage.HeapMonitorMultiArrayTest
    + */
    +
    +/*
    + * @test id=expand-deopt
    + * @summary Verifies the JVMTI Heap Monitor API when allocating a multi-array.
    + * @requires vm.jvmti & vm.debug
    + * @build Frame HeapMonitor
    + * @compile HeapMonitorMultiArrayTest.java
    + * @run main/othervm/native -XX:+DeoptimizeALot
    + *      -agentlib:HeapMonitorTest MyPackage.HeapMonitorMultiArrayTest mayRepeat
    + */
    +
    +/*
    + * @test id=noexpand
      * @summary Verifies the JVMTI Heap Monitor API when allocating a multi-array.
      * @requires vm.jvmti
      * @build Frame HeapMonitor
      * @compile HeapMonitorMultiArrayTest.java
    - * @run main/othervm/native -agentlib:HeapMonitorTest MyPackage.HeapMonitorMultiArrayTest
    + * @run main/othervm/native -XX:+IgnoreUnrecognizedVMOptions -XX:-DeoptimizeALot
    + *      -XX:MultiArrayExpandLimit=0
    + *      -agentlib:HeapMonitorTest MyPackage.HeapMonitorMultiArrayTest
    + */
    +
    +/*
    + * @test id=noexpand-deopt
    + * @summary Verifies the JVMTI Heap Monitor API when allocating a multi-array.
    + * @requires vm.jvmti & vm.debug
    + * @build Frame HeapMonitor
    + * @compile HeapMonitorMultiArrayTest.java
    + * @run main/othervm/native -XX:+IgnoreUnrecognizedVMOptions -XX:+DeoptimizeALot
    + *      -XX:MultiArrayExpandLimit=0
    + *      -agentlib:HeapMonitorTest MyPackage.HeapMonitorMultiArrayTest
      */
     public class HeapMonitorMultiArrayTest {
     
    @@ -52,9 +85,14 @@ public static void main(String[] args) throws Exception {
         int sampledEvents = HeapMonitor.sampledEvents();
         int expectedNumber = iterations * allocationsPerIteration;
     
    -    if (sampledEvents != expectedNumber) {
    +    // A deopt between the six allocations C2 expands inline redoes all six,
    +    // at most six extra samples per iteration.
    +    boolean mayRepeat = args.length > 0 && args[0].equals("mayRepeat");
    +    int maxNumber = mayRepeat ? 2 * expectedNumber : expectedNumber;
    +    System.out.println("Number of samples: " + sampledEvents);
    +    if (sampledEvents < expectedNumber || sampledEvents > maxNumber) {
           throw new RuntimeException("Number of samples (" + sampledEvents + ") not the expected ("
    -          + expectedNumber + ")");
    +          + expectedNumber + (mayRepeat ? " to " + maxNumber : "") + ")");
         }
       }
     }
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/ValueHeapwalkingTest.java b/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/ValueHeapwalkingTest.java
    index 8a37814bec9d..679c60a1a270 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/ValueHeapwalkingTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/ValueHeapwalkingTest.java
    @@ -23,9 +23,10 @@
     
     /*
      * @test
    + * @bug 8389219 8389220 8396201
      * @summary Tests heapwalking API (FollowReferences, IterateThroughHeap, GetObjectsWithTags) for value objects.
      * @requires vm.jvmti
    - * @modules java.base/jdk.internal.vm.annotation java.base/jdk.internal.value
    + * @modules java.base/jdk.internal.misc java.base/jdk.internal.vm.annotation java.base/jdk.internal.value
      * @enablePreview
      * @run main/othervm/native -agentlib:ValueHeapwalkingTest
      *                          -XX:+UnlockDiagnosticVMOptions
    @@ -44,6 +45,7 @@
     import java.util.ArrayList;
     import java.util.Arrays;
     import java.util.List;
    +import jdk.internal.misc.Unsafe;
     import jdk.internal.value.ValueClass;
     import jdk.internal.vm.annotation.NullRestricted;
     
    @@ -77,6 +79,22 @@ static value class Value2 {
             }
         }
     
    +    static class Loader extends ClassLoader {
    +        @NullRestricted
    +        public Value2 v2_0;
    +
    +        Loader() {
    +            v2_0 = new Value2(200);
    +            super();
    +        }
    +
    +        void defineEmptyClass() {
    +            byte[] bytes = java.lang.classfile.ClassFile.of().build(
    +                    java.lang.constant.ClassDesc.of("EmptyClass"), builder -> {});
    +            defineClass(null, bytes, 0, bytes.length);
    +        }
    +    }
    +
         static value class ValueHolder {
             public Value v1;
             @NullRestricted
    @@ -250,7 +268,12 @@ static void printObject(String prefix, Object obj) {
         public static void main(String[] args) throws Exception {
             System.loadLibrary("ValueHeapwalkingTest");
             ValueHolder holder = new ValueHolder(10);
    +        Loader loader = new Loader();
    +        loader.defineEmptyClass();
     
    +        if (!Unsafe.getUnsafe().isFlatField(Loader.class.getDeclaredField("v2_0"))) {
    +            throw new RuntimeException("loader.v2_0 expected to be flattened");
    +        }
             setTag(Value.class, TAG_VALUE_CLASS);
             setTag(Value2.class, TAG_VALUE2_CLASS);
             setTag(ValueHolder.class, TAG_HOLDER_CLASS);
    @@ -268,8 +291,8 @@ public static void main(String[] args) throws Exception {
                 System.out.println(tagStr(i) + " count: " + count(i));
             }
             int reachableValueHolderCount = 1;
    -        // v2_1, v2_2, v2_arr
    -        int reachableValue2Count = reachableValueHolderCount * (2 + nonNullCount(holder.v2_arr));
    +        // v2_0, v2_1, v2_2, v2_arr
    +        int reachableValue2Count = 1 + reachableValueHolderCount * (2 + nonNullCount(holder.v2_arr));
             // ValueHolder: v1, v2, v_arr
             // Value2: v1, v2
             int reachableValueCount = reachableValueHolderCount * (2 + nonNullCount(holder.v_arr))
    @@ -335,13 +358,15 @@ public static void main(String[] args) throws Exception {
                     throw new RuntimeException("unexpected object");
                 }
             }
    +        // loader.v2_0 is untagged because its loader referrer is untagged
             int expectedTaggedCount = 5 // TAG_VALUE_CLASS/TAG_VALUE2_CLASS/TAG_HOLDER_CLASS/TAG_VALUE_ARRAY/TAG_VALUE2_ARRAY
    -                + reachableValue2Count + reachableValueCount;
    +                + reachableValue2Count - 1 + reachableValueCount;
             if (count !=  expectedTaggedCount) {
                 throw new RuntimeException("unexpected getObjectWithTags result: " + count
                                          + ", expected " + expectedTaggedCount);
             }
     
    +        Reference.reachabilityFence(loader);
             Reference.reachabilityFence(holder);
         }
     }
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/libValueHeapwalkingTest.cpp b/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/libValueHeapwalkingTest.cpp
    index eb0f08165dda..ed48500eaf3b 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/libValueHeapwalkingTest.cpp
    +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/Heapwalking/libValueHeapwalkingTest.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -130,6 +130,12 @@ heap_reference_callback(jvmtiHeapReferenceKind reference_kind,
                             void* user_data) {
       Callback_Data* data = (Callback_Data*)user_data;
     
    +  // FollowReferences should not report a class loader's references to loaded classes originated from flattened value objects.
    +  if (reference_kind == JVMTI_HEAP_REFERENCE_OTHER &&
    +      (referrer_class_tag == TAG_VALUE_CLASS || referrer_class_tag == TAG_VALUE2_CLASS)) {
    +    fatal("FollowReferences reported a class loader reference from a value object");
    +  }
    +
       jlong tag = class_tag;
       if (tag == 0 && *tag_ptr != 0 && *tag_ptr <= MAX_TAG) {
         tag = *tag_ptr;
    diff --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups
    index d4577196db71..aa6d13ad58f3 100644
    --- a/test/jdk/TEST.groups
    +++ b/test/jdk/TEST.groups
    @@ -648,7 +648,8 @@ jdk_core_manual_no_input = \
         com/sun/net/httpserver/simpleserver/jwebserver/CommandLinePortNotSpecifiedTest.java \
         com/sun/net/httpserver/simpleserver/DocRootDirPermissionsWinTest.java \
         javax/xml/jaxp/datatype/8033980/GregorianCalAndDurSerDataUtil.java \
    -    java/util/zip/ZipFile/CenSizeMaximum.java
    +    java/util/zip/ZipFile/CenSizeMaximum.java \
    +    java/lang/ProcessBuilder/ConcNativeForkTest/ConcNativeForkTest.java
     
     jdk_security_manual_no_input = \
         :jdk_security_infra \
    diff --git a/test/jdk/java/awt/font/FontNames/FCCompositeTest.java b/test/jdk/java/awt/font/FontNames/FCCompositeTest.java
    index 63ac9872da8b..a7247b06500d 100644
    --- a/test/jdk/java/awt/font/FontNames/FCCompositeTest.java
    +++ b/test/jdk/java/awt/font/FontNames/FCCompositeTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -53,6 +53,38 @@ public static void main(String args[]) {
             }
         }
     
    +    private static boolean usesVariableFont(String name) {
    +        try {
    +            String[] filecmd = {"fc-match", name, "file"};
    +            Runtime runtime = Runtime.getRuntime();
    +            Process p = runtime.exec(filecmd, null, null);
    +            p.waitFor();
    +            InputStream is = p.getInputStream();
    +            BufferedReader br = new BufferedReader(new InputStreamReader(is));
    +            String fileline = br.readLine();
    +            br.close();
    +            String[] list = fileline.split("=|,", 0);
    +            String filename = list[1];
    +            System.out.println("found filename = " + filename);
    +            String[] querycmd = {"fc-query", "-f", "%{variable}\n", filename};
    +            p = runtime.exec(querycmd, null, null);
    +            p.waitFor();
    +            is = p.getInputStream();
    +            br = new BufferedReader(new InputStreamReader(is));
    +            String line;
    +            while ((line = br.readLine()) != null) {
    +                System.out.println("read line " + line);
    +                if (line.equalsIgnoreCase("True")) {
    +                     return true;
    +                }
    +            }
    +            br.close();
    +        } catch (Exception e) {
    +             return true;
    +        }
    +        return false;
    +    }
    +
         private static void test(int index) {
             boolean matched = false;
             String fullName = "";
    @@ -68,6 +100,9 @@ private static void test(int index) {
                 fullName = pf.getFontName(Locale.ENGLISH);
                 System.out.println("PF="+fullName);
     
    +            if (usesVariableFont(fcnames[index])) {
    +                return;
    +            }
                 String[] command = {"fc-match",
                                     fcnames[index],
                                     "fullname"};
    @@ -106,6 +141,7 @@ private static void test(int index) {
                     }
                 }
                 br.close();
    +            errorBr.close();
             } catch (Exception e) {
                 e.printStackTrace();
                 throw new RuntimeException("Method invocation exception");
    diff --git a/test/jdk/java/awt/image/BufferedImage/CreateBufferedImageTest.java b/test/jdk/java/awt/image/BufferedImage/CreateBufferedImageTest.java
    new file mode 100644
    index 000000000000..6f7923e03e44
    --- /dev/null
    +++ b/test/jdk/java/awt/image/BufferedImage/CreateBufferedImageTest.java
    @@ -0,0 +1,114 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +import java.awt.image.BufferedImage;
    +import java.awt.image.IndexColorModel;
    +import java.awt.image.WritableRaster;
    +import static java.awt.image.BufferedImage.*;
    +
    +/**
    + * @test
    + * @bug 4617681
    + * @summary Verify BufferedImage Constructor behaviour with
    + *          invalid image size and type parameters.
    + */
    +
    +public class CreateBufferedImageTest {
    +
    +    static byte[] s = new byte[16];
    +    static IndexColorModel icm = new IndexColorModel(8, 16, s, s, s);
    +
    +    public static void main(String args[]) {
    +
    +        test(TYPE_CUSTOM, 10); // TYPE_CUSTOM is not a valid parameter.
    +        test(-1, 10);
    +        test(10001, 10);
    +
    +        for (int t = TYPE_INT_RGB; t <= TYPE_BYTE_INDEXED; t++) {
    +           test(t, 50_000); // 50_000 ^ 2 will overflow int.
    +        }
    +        test(TYPE_3BYTE_BGR, 30_000); // 3 * (30_000 ^ 2) will overflow int
    +        test(TYPE_4BYTE_ABGR, 25_000); // 4 * (25_000 ^ 2) will overflow int
    +        test(TYPE_4BYTE_ABGR_PRE, 25_000);
    +
    +        testIndexed(TYPE_INT_RGB, 10);
    +        testIndexed(TYPE_CUSTOM, 10);
    +        testIndexed(-1, 10);
    +        testIndexed(10001, 10);
    +        testIndexed(TYPE_BYTE_BINARY, 50_000);
    +        testIndexed(TYPE_BYTE_INDEXED, 50_000);
    +
    +        // Verify that IAE is thrown if constructing using a raster with x/y != 0
    +        BufferedImage bi = new BufferedImage(TYPE_INT_RGB, 10, 10);
    +        WritableRaster raster = bi.getRaster().createCompatibleWritableRaster(20, 20, 1, 1);
    +        try {
    +            bi = new BufferedImage(bi.getColorModel(), raster, true, null);
    +            throw new RuntimeException("No expected exception for invalid min x/y");
    +        } catch (IllegalArgumentException e) {
    +           System.out.println("Expected exception thrown for invalid raster min x/y");
    +           System.out.println(e);
    +        }
    +    }
    +
    +    static void test(int t, int sz) {
    +        try {
    +            new BufferedImage(sz, sz, t);
    +            throw new RuntimeException("No expected exception for type = " + t);
    +        } catch (IllegalArgumentException e) {
    +            System.out.println("Expected exception thrown");
    +            System.out.println(e);
    +        } catch (NegativeArraySizeException n) {
    +            checkIsOldVersion(26, n);
    +        }
    +    }
    +
    +    static void testIndexed(int t, int sz) {
    +        try {
    +            new BufferedImage(sz, sz, t, icm);
    +            throw new RuntimeException("No expected exception for type = " + t);
    +        } catch (IllegalArgumentException e) {
    +            System.out.println("Expected exception thrown");
    +            System.out.println(e);
    +        }
    +    }
    +
    +    /**
    +      * If running on a JDK of the targetVersion or later, throw
    +      * a RuntimeException becuase the exception argument
    +      * should not have occured. However it is expected on
    +      * prior versions because that was the previous behaviour.
    +      * @param targetVersion to check
    +      * @param t the thrown exception to print
    +      */
    +    static void checkIsOldVersion(int targetVersion, Throwable t) {
    +        String version = System.getProperty("java.version");
    +        version = version.split("\\D")[0];
    +        int v = Integer.parseInt(version);
    +        if (v >= targetVersion) {
    +            t.printStackTrace();
    +            throw new RuntimeException(
    +                           "Unexpected exception for version " + v);
    +        }
    +    }
    +
    +}
    diff --git a/test/jdk/java/net/httpclient/http2/MalformedPriorityFrameTest.java b/test/jdk/java/net/httpclient/http2/MalformedPriorityFrameTest.java
    new file mode 100644
    index 000000000000..d360b269a99f
    --- /dev/null
    +++ b/test/jdk/java/net/httpclient/http2/MalformedPriorityFrameTest.java
    @@ -0,0 +1,203 @@
    +/*
    + * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + */
    +
    +/*
    + * @test
    + * @bug 8396170
    + * @summary A PRIORITY frame with a length other than 5 is a stream error
    + *          (RFC 9113, 6.3). RST_STREAM is sent only if the stream is open or
    + *          half-closed, never on idle or closed streams (RFC 9113, 5.1, 6.4).
    + *          The connection must survive in all cases.
    + * @library /test/lib
    + * @build jdk.test.lib.net.URIBuilder
    + * @run junit/othervm -Djdk.internal.httpclient.debug=true ${test.main.class}
    + */
    +
    +import java.io.DataInputStream;
    +import java.io.IOException;
    +import java.io.OutputStream;
    +import java.net.InetAddress;
    +import java.net.ServerSocket;
    +import java.net.Socket;
    +import java.net.URI;
    +import java.net.http.HttpClient;
    +import java.net.http.HttpRequest;
    +import java.net.http.HttpResponse;
    +import java.nio.ByteBuffer;
    +import java.nio.charset.StandardCharsets;
    +import java.util.concurrent.CompletableFuture;
    +import java.util.concurrent.TimeUnit;
    +
    +import jdk.test.lib.net.URIBuilder;
    +import org.junit.jupiter.api.Test;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import static java.net.http.HttpClient.Builder.NO_PROXY;
    +import static java.net.http.HttpClient.Version.HTTP_2;
    +import static org.junit.jupiter.api.Assertions.assertEquals;
    +import static org.junit.jupiter.api.Assertions.assertFalse;
    +import static org.junit.jupiter.api.Assertions.assertThrows;
    +
    +class MalformedPriorityFrameTest {
    +
    +    static final int HEADERS = 0x1, PRIORITY = 0x2, RST_STREAM = 0x3,
    +            SETTINGS = 0x4, PING = 0x6, GOAWAY = 0x7;
    +    static final int FRAME_SIZE_ERROR = 0x6;
    +
    +    // RST_STREAM(FRAME_SIZE_ERROR) is sent and the connection survives.
    +    @Test
    +    void activeStream() throws Exception {
    +        try (TestServer server = new TestServer(1, true);
    +             HttpClient client = newClient()) {
    +            assertThrows(IOException.class, () -> get(client, server.uri()));
    +            int[] rst = server.rst.get(30, TimeUnit.SECONDS);
    +            assertEquals(1, rst[0], "RST_STREAM stream id");
    +            assertEquals(FRAME_SIZE_ERROR, rst[1], "RST_STREAM error code");
    +            server.pingAck.get(30, TimeUnit.SECONDS);
    +            assertEquals(200, get(client, server.uri()).statusCode());
    +            assertFalse(server.goAway.isDone(), "unexpected GOAWAY");
    +        }
    +    }
    +
    +    // END_STREAM sent and received and the frame is ignored.
    +    @Test
    +    void closedStream() throws Exception {
    +        checkIgnored(1);
    +    }
    +
    +    // Idle client-initiated (101) and server-initiated (2) streams
    +    // and the frame is ignored.
    +    @ParameterizedTest
    +    @ValueSource(ints = {101, 2})
    +    void idleStream(int streamId) throws Exception {
    +        checkIgnored(streamId);
    +    }
    +
    +    static void checkIgnored(int badStreamId) throws Exception {
    +        try (TestServer server = new TestServer(badStreamId, false);
    +             HttpClient client = newClient()) {
    +            assertEquals(200, get(client, server.uri()).statusCode());
    +            server.pingAck.get(30, TimeUnit.SECONDS);
    +            assertEquals(200, get(client, server.uri()).statusCode());
    +            assertFalse(server.rst.isDone(), "unexpected RST_STREAM");
    +            assertFalse(server.goAway.isDone(), "unexpected GOAWAY");
    +        }
    +    }
    +
    +    static HttpClient newClient() {
    +        return HttpClient.newBuilder().version(HTTP_2).proxy(NO_PROXY).build();
    +    }
    +
    +    static HttpResponse get(HttpClient client, URI uri) throws Exception {
    +        return client.send(HttpRequest.newBuilder(uri).build(),
    +                HttpResponse.BodyHandlers.ofString());
    +    }
    +
    +    static byte[] frame(int type, int flags, int streamId, byte[] payload) {
    +        int len = payload.length;
    +        ByteBuffer buffer = ByteBuffer.allocate(9 + len);
    +        buffer.put((byte) (len >> 16));
    +        buffer.put((byte) (len >> 8));
    +        buffer.put((byte) len);
    +        buffer.put((byte) type);
    +        buffer.put((byte) flags);
    +        buffer.putInt(streamId);
    +        buffer.put(payload);
    +        return buffer.array();
    +    }
    +
    +    static final class TestServer implements AutoCloseable {
    +        final ServerSocket ss;
    +        final CompletableFuture rst = new CompletableFuture<>();
    +        final CompletableFuture goAway = new CompletableFuture<>();
    +        final CompletableFuture pingAck = new CompletableFuture<>();
    +
    +        TestServer(int badStreamId, boolean badBeforeResponse) throws IOException {
    +            ss = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
    +            byte[] bad = frame(PRIORITY, 0, badStreamId, new byte[4]);
    +            Thread.ofPlatform().daemon().start(() -> {
    +                serve(bad, badBeforeResponse);
    +            });
    +        }
    +
    +        URI uri() {
    +            return URIBuilder.newBuilder().scheme("http").loopback()
    +                    .port(ss.getLocalPort()).path("/").buildUnchecked();
    +        }
    +
    +        void serve(byte[] bad, boolean badBeforeResponse) {
    +            try (Socket s = ss.accept()) {
    +                DataInputStream in = new DataInputStream(s.getInputStream());
    +                OutputStream out = s.getOutputStream();
    +                StringBuilder request = new StringBuilder();
    +                while (!request.toString().endsWith("\r\n\r\n")) {
    +                    int c = in.read();
    +                    if (c < 0) throw new IOException("EOF in HTTP/1.1 request");
    +                    request.append((char) c);
    +                }
    +                write(out, new byte[][]{("HTTP/1.1 101 Switching Protocols\r\n"
    +                        + "Connection: Upgrade\r\nUpgrade: h2c\r\n\r\n")
    +                        .getBytes(StandardCharsets.US_ASCII)});
    +                write(out, new byte[][]{frame(SETTINGS, 0, 0, new byte[0])});
    +                in.readFully(new byte[24]);
    +                byte[] response = frame(HEADERS, 0x5, 1, new byte[] {(byte) 0x88});
    +                byte[] ping = frame(PING, 0, 0, new byte[8]);
    +                if (badBeforeResponse) {
    +                    write(out, new byte[][]{bad, response, ping});
    +                } else {
    +                    write(out, new byte[][]{response, bad, ping});
    +                }
    +                while (true) {
    +                    byte[] hdr = new byte[9];
    +                    in.readFully(hdr);
    +                    int len = ((hdr[0] & 0xff) << 16) | ((hdr[1] & 0xff) << 8) | (hdr[2] & 0xff);
    +                    int type = hdr[3] & 0xff;
    +                    int flags = hdr[4] & 0xff;
    +                    int sid = ByteBuffer.wrap(hdr, 5, 4).getInt() & 0x7fffffff;
    +                    byte[] payload = new byte[len];
    +                    in.readFully(payload);
    +                    switch (type) {
    +                        case SETTINGS:
    +                            if ((flags & 0x1) == 0) {
    +                                write(out, new byte[][]{frame(SETTINGS, 0x1, 0, new byte[0])});
    +                            }
    +                            break;
    +                        case PING:
    +                            if ((flags & 0x1) != 0) {
    +                                pingAck.complete(null);
    +                            }
    +                            break;
    +                        case HEADERS:
    +                            write(out, new byte[][]{frame(HEADERS, 0x5, sid, new byte[]{(byte) 0x88})});
    +                            break;
    +                        case RST_STREAM:
    +                            rst.complete(new int[]{sid, ByteBuffer.wrap(payload).getInt()});
    +                            break;
    +                        case GOAWAY:
    +                            goAway.complete(null);
    +                            break;
    +                        default:
    +                            break;
    +                    }
    +                }
    +            } catch (IOException e) {
    +                pingAck.completeExceptionally(e);
    +            }
    +        }
    +
    +        static void write(OutputStream out, byte[][] frames) throws IOException {
    +            for (byte[] frame : frames) {
    +                out.write(frame);
    +            }
    +            out.flush();
    +        }
    +
    +        @Override
    +        public void close() throws IOException {
    +            ss.close();
    +        }
    +    }
    +}
    \ No newline at end of file
    diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/DynamicKeyStoreUtil.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/DynamicKeyStoreUtil.java
    index 5b96d4c0b76a..fbf2ff0f7a40 100644
    --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/DynamicKeyStoreUtil.java
    +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/DynamicKeyStoreUtil.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -32,7 +32,8 @@
     import java.security.SecureRandom;
     import java.security.cert.Certificate;
     import java.security.cert.X509Certificate;
    -import java.util.Date;
    +import java.time.Instant;
    +import java.time.temporal.ChronoUnit;
     import java.util.Objects;
     
     import javax.net.ssl.KeyManager;
    @@ -231,11 +232,9 @@ private static X509Certificate generateCert(final KeyPair keyPair, final SecureR
     
         private static CertificateValidity certDuration() {
             // create a cert with 1 day validity, starting from 1 minute back
    -        final long currentTime = System.currentTimeMillis();
    -        final long oneMinuteInThePast = currentTime - (60 * 1000);
    -        final long oneDayInTheFuture = currentTime + (24 * 60 * 60 * 1000);
    -        final Date startDate = new Date(oneMinuteInThePast);
    -        final Date expiryDate = new Date(oneDayInTheFuture);
    +        final Instant currentTime = Instant.now();
    +        final Instant startDate = currentTime.minusSeconds(60);
    +        final Instant expiryDate = currentTime.plus(1, ChronoUnit.DAYS);
             return new CertificateValidity(startDate, expiryDate);
         }
     
    diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/frame/FramesDecoderTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/frame/FramesDecoderTest.java
    index e8acc95c1d27..7125352b0ee5 100644
    --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/frame/FramesDecoderTest.java
    +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/frame/FramesDecoderTest.java
    @@ -1,5 +1,6 @@
     /*
      * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2026, Amazon.com Inc. or its affiliates. All Rights Reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -137,4 +138,76 @@ public void processFrame(Http2Frame frame) throws IOException {
             decoder.decode(combined);
             assertEquals(1, testFrameProcessor.numberOfFramesDecoded());
         }
    +
    +    private static byte[] frame(int type, int streamId, byte[] payload) {
    +        ByteBuffer buffer = ByteBuffer.allocate(Http2Frame.FRAME_HEADER_SIZE
    +                + payload.length);
    +        int len = payload.length;
    +        buffer.put((byte) (len >> 16));
    +        buffer.put((byte) (len >> 8));
    +        buffer.put((byte) len);
    +        buffer.put((byte) type);
    +        buffer.put((byte) 0);
    +        buffer.putInt(streamId);
    +        buffer.put(payload);
    +        return buffer.array();
    +    }
    +
    +    private static final byte[] PING = frame(PingFrame.TYPE, 0, new byte[8]);
    +
    +    private static List decode(byte[][] frames) throws IOException {
    +        int len = 0;
    +        for (byte[] frame : frames) {
    +            len += frame.length;
    +        }
    +        ByteBuffer input = ByteBuffer.allocate(len);
    +        for (byte[] frame : frames) {
    +            input.put(frame);
    +        }
    +        input.flip();
    +        List decoded = new ArrayList<>();
    +        new FramesDecoder(decoded::add).decode(input);
    +        return decoded;
    +    }
    +
    +    /**
    +     * A PRIORITY frame with a length other than 5
    +     */
    +    @Test
    +    public void decodeBadLengthPriorityFrame() throws Exception {
    +        List frames = decode(new byte[][]{frame(PriorityFrame.TYPE, 3, new byte[4]), PING});
    +        assertEquals(2, frames.size(), frames.toString());
    +        MalformedFrame malformedFrame = assertInstanceOf(MalformedFrame.class, frames.get(0));
    +        assertEquals(ErrorFrame.FRAME_SIZE_ERROR, malformedFrame.getErrorCode());
    +        assertEquals(3, malformedFrame.streamid());
    +        assertFalse(malformedFrame.isConnectionError());
    +        assertInstanceOf(PingFrame.class, frames.get(1));
    +    }
    +
    +    /**
    +     * ALTSVC frames with non-ASCII origin or value.
    +     */
    +    @Test
    +    public void decodeNonAsciiAltSvcFrame() throws Exception {
    +        byte[] badOrigin = {0, 2, (byte) 0xC3, (byte) 0xA9, 'h', '2', '=', '"', ':', '1', '"'};
    +        byte[] badValue = {0, 1, 'x', 'h', '2', '=', (byte) 0xC3, (byte) 0xA9};
    +        List frames = decode(new byte[][]{frame(AltSvcFrame.TYPE, 0, badOrigin),
    +                frame(AltSvcFrame.TYPE, 0, badValue), PING});
    +        assertEquals(1, frames.size(), frames.toString());
    +        assertInstanceOf(PingFrame.class, frames.get(0));
    +    }
    +
    +    /**
    +     * ALTSVC frames too small.
    +     */
    +    @Test
    +    public void decodeTooSmallAltSvcFrame() throws Exception {
    +        for (byte[] payload : List.of(new byte[] {0}, new byte[] {0, 10, 'a', 'b'})) {
    +            List frames = decode(new byte[][]{frame(AltSvcFrame.TYPE, 0, payload)});
    +            assertEquals(1, frames.size(), frames.toString());
    +            MalformedFrame malformedFrame = assertInstanceOf(MalformedFrame.class, frames.get(0));
    +            assertEquals(ErrorFrame.FRAME_SIZE_ERROR, malformedFrame.getErrorCode());
    +            assertTrue(malformedFrame.isConnectionError());
    +        }
    +    }
     }
    diff --git a/test/jdk/java/net/vthread/BlockingSocketOps.java b/test/jdk/java/net/vthread/BlockingSocketOps.java
    index 711092539092..58c07a1a21c8 100644
    --- a/test/jdk/java/net/vthread/BlockingSocketOps.java
    +++ b/test/jdk/java/net/vthread/BlockingSocketOps.java
    @@ -65,7 +65,8 @@
     import java.net.SocketAddress;
     import java.net.SocketException;
     import java.net.SocketTimeoutException;
    -import java.util.concurrent.atomic.AtomicReference;
    +import java.util.concurrent.CompletableFuture;
    +import java.util.concurrent.Future;
     import java.util.concurrent.locks.LockSupport;
     
     import jdk.test.lib.thread.VThreadRunner;
    @@ -110,21 +111,21 @@ void testSocketRead(int timeout) throws Exception {
                     Socket s1 = connection.socket1();
                     Socket s2 = connection.socket2();
     
    -                // delayed write from sc1
    +                // write to s1 when current thread parks
                     byte[] ba1 = "XXX".getBytes("UTF-8");
    -                var unparker = runAfterParkedAsync(() -> s1.getOutputStream().write(ba1));
    -
    -                // read from sc2 should block
    -                if (timeout > 0) {
    -                    s2.setSoTimeout(timeout);
    +                Future writer = runAfterParkedAsync(() -> s1.getOutputStream().write(ba1));
    +                try {
    +                    // read from s2 should block
    +                    if (timeout > 0) {
    +                        s2.setSoTimeout(timeout);
    +                    }
    +                    byte[] ba2 = new byte[10];
    +                    int n = s2.getInputStream().read(ba2);
    +                    assertTrue(n > 0);
    +                    assertTrue(ba2[0] == 'X');
    +                } finally {
    +                    writer.get();
                     }
    -                byte[] ba2 = new byte[10];
    -                int n = s2.getInputStream().read(ba2);
    -                assertTrue(n > 0);
    -                assertTrue(ba2[0] == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
                 }
             });
         }
    @@ -139,24 +140,21 @@ void testSocketWrite1() throws Exception {
                     Socket s1 = connection.socket1();
                     Socket s2 = connection.socket2();
     
    -                // delayed read from s2 to EOF
    +                // reads s2 to EOF when current thread parks
                     InputStream in = s2.getInputStream();
    -                var unparker = runAfterParkedAsync(() ->
    -                        in.transferTo(OutputStream.nullOutputStream()), true);
    -
    -                // write should block
    -                byte[] ba = new byte[100*1024];
    -                try (OutputStream out = s1.getOutputStream()) {
    -                    for (int i = 0; i < 1000; i++) {
    -                        out.write(ba);
    +                Future reader = runAfterParkedAsync(() ->
    +                        in.transferTo(OutputStream.nullOutputStream()));
    +                try {
    +                    // write should block
    +                    byte[] ba = new byte[100 * 1024];
    +                    try (OutputStream out = s1.getOutputStream()) {
    +                        for (int i = 0; i < 1000; i++) {
    +                            out.write(ba);
    +                        }
                         }
    +                } finally {
    +                    reader.get();
                     }
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
    -
    -                // wait for reader to finish
    -                unparker.join();
                 }
             });
         }
    @@ -171,12 +169,15 @@ void testSocketReadPeerClose1() throws Exception {
                     Socket s1 = connection.socket1();
                     Socket s2 = connection.socket2();
     
    -                // delayed close of s2
    -                runAfterParkedAsync(s2::close);
    -
    -                // read from s1 should block, then read -1
    -                int n = s1.getInputStream().read();
    -                assertTrue(n == -1);
    +                // close s2 when current thread parks
    +                Future closer = runAfterParkedAsync(s2::close);
    +                try {
    +                    // read from s1 should block, then read -1
    +                    int n = s1.getInputStream().read();
    +                    assertTrue(n == -1);
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -191,16 +192,17 @@ void testSocketReadPeerClose2() throws Exception {
                     Socket s1 = connection.socket1();
                     Socket s2 = connection.socket2();
     
    -                // delayed abrupt close of s2
    +                // close s2 when current thread parks
                     s2.setSoLinger(true, 0);
    -                runAfterParkedAsync(s2::close);
    -
    -                // read from s1 should block, then throw
    +                Future closer = runAfterParkedAsync(s2::close);
                     try {
    +                    // read from s1 should block, then throw
                         int n = s1.getInputStream().read();
                         fail("read " + n);
                     } catch (IOException ioe) {
                         // expected
    +                } finally {
    +                    closer.get();
                     }
                 }
             });
    @@ -216,18 +218,21 @@ void testSocketReadAsyncClose(int timeout) throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -                // delayed close of s
    -                runAfterParkedAsync(s::close);
    -
    -                // read from s should block, then throw
    -                if (timeout > 0) {
    -                    s.setSoTimeout(timeout);
    -                }
    +                // close s when current thread parks
    +                Future closer = runAfterParkedAsync(s::close);
                     try {
    -                    int n = s.getInputStream().read();
    -                    fail("read " + n);
    -                } catch (SocketException expected) {
    -                    log(expected);
    +                    // read from s should block, then throw
    +                    if (timeout > 0) {
    +                        s.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        int n = s.getInputStream().read();
    +                        fail("read " + n);
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                    }
    +                } finally {
    +                    closer.get();
                     }
                 }
             });
    @@ -243,17 +248,20 @@ void testSocketReadAsyncShutdownInput(int timeout) throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -                // delayed shutdown of input stream
    +                // shutdown input when current thread parks
                     InputStream in = s.getInputStream();
    -                runAfterParkedAsync(s::shutdownInput);
    -
    -                // read should return -1
    -                if (timeout > 0) {
    -                    s.setSoTimeout(timeout);
    +                Future shutdownInput = runAfterParkedAsync(s::shutdownInput);
    +                try {
    +                    // read should return -1
    +                    if (timeout > 0) {
    +                        s.setSoTimeout(timeout);
    +                    }
    +                    assertEquals(-1, in.read());
    +                    assertEquals(0, in.available());
    +                    assertFalse(s.isClosed());
    +                } finally {
    +                    shutdownInput.get();
                     }
    -                assertEquals(-1, in.read());
    -                assertEquals(0, in.available());
    -                assertFalse(s.isClosed());
                 }
             });
         }
    @@ -268,22 +276,24 @@ void testSocketReadInterrupt(int timeout) throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -
    -                // delayed interrupt of current thread
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    -                // read from s should block, then throw
    -                if (timeout > 0) {
    -                    s.setSoTimeout(timeout);
    -                }
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
    -                    int n = s.getInputStream().read();
    -                    fail("read " + n);
    -                } catch (SocketException expected) {
    -                    log(expected);
    -                    assertTrue(Thread.interrupted());
    -                    assertTrue(s.isClosed());
    +                    // read from s should block, then throw
    +                    if (timeout > 0) {
    +                        s.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        int n = s.getInputStream().read();
    +                        fail("read " + n);
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                        assertTrue(Thread.interrupted());
    +                        assertTrue(s.isClosed());
    +                    }
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -298,11 +308,10 @@ void testSocketWriteAsyncClose() throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -                // delayed close of s
    -                runAfterParkedAsync(s::close);
    -
    -                // write to s should block, then throw
    +                // close s when current thread parks
    +                Future closer = runAfterParkedAsync(s::close);
                     try {
    +                    // write to s should block, then throw
                         byte[] ba = new byte[100*1024];
                         OutputStream out = s.getOutputStream();
                         for (;;) {
    @@ -310,6 +319,8 @@ void testSocketWriteAsyncClose() throws Exception {
                         }
                     } catch (SocketException expected) {
                         log(expected);
    +                } finally {
    +                    closer.get();
                     }
                 }
             });
    @@ -324,18 +335,21 @@ void testSocketWriteAsyncShutdownOutput() throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -                // delayed shutdown of output stream
    +                // shutdown output when current thread parks
                     OutputStream out = s.getOutputStream();
    -                runAfterParkedAsync(s::shutdownOutput);
    -
    -                // write to s should block, then throw
    +                Future shutdownOutput = runAfterParkedAsync(s::shutdownOutput);
                     try {
    -                    byte[] ba = new byte[100*1024];
    -                    for (;;) {
    -                        out.write(ba);
    +                    // write to s should block, then throw
    +                    try {
    +                        byte[] ba = new byte[100 * 1024];
    +                        for (; ; ) {
    +                            out.write(ba);
    +                        }
    +                    } catch (SocketException expected) {
    +                        log(expected);
                         }
    -                } catch (SocketException expected) {
    -                    log(expected);
    +                } finally {
    +                    shutdownOutput.get();
                     }
                     assertFalse(s.isClosed());
                 }
    @@ -351,21 +365,24 @@ void testSocketWriteInterrupt() throws Exception {
                 try (var connection = new Connection()) {
                     Socket s = connection.socket1();
     
    -                // delayed interrupt of current thread
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    -                // write to s should block, then throw
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
    -                    byte[] ba = new byte[100*1024];
    -                    OutputStream out = s.getOutputStream();
    -                    for (;;) {
    -                        out.write(ba);
    +                    // write to s should block, then throw
    +                    try {
    +                        byte[] ba = new byte[100 * 1024];
    +                        OutputStream out = s.getOutputStream();
    +                        for (; ; ) {
    +                            out.write(ba);
    +                        }
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                        assertTrue(Thread.interrupted());
    +                        assertTrue(s.isClosed());
                         }
    -                } catch (SocketException expected) {
    -                    log(expected);
    -                    assertTrue(Thread.interrupted());
    -                    assertTrue(s.isClosed());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -381,25 +398,28 @@ void testSocketReadUrgentData() throws Exception {
                     Socket s1 = connection.socket1();
                     Socket s2 = connection.socket2();
     
    -                // urgent data should be received
    -                runAfterParkedAsync(() -> s2.sendUrgentData('X'));
    -
    -                // read should block, then read the OOB byte
    -                s1.setOOBInline(true);
    -                byte[] ba = new byte[10];
    -                int n = s1.getInputStream().read(ba);
    -                assertTrue(n == 1);
    -                assertTrue(ba[0] == 'X');
    -
    -                // urgent data should not be received
    -                s1.setOOBInline(false);
    -                s1.setSoTimeout(500);
    -                s2.sendUrgentData('X');
    +                // send urgent data when current thread parks
    +                Future sender = runAfterParkedAsync(() -> s2.sendUrgentData('X'));
                     try {
    -                    s1.getInputStream().read(ba);
    -                    fail();
    -                } catch (SocketTimeoutException expected) {
    -                    log(expected);
    +                    // read should block, then read the OOB byte
    +                    s1.setOOBInline(true);
    +                    byte[] ba = new byte[10];
    +                    int n = s1.getInputStream().read(ba);
    +                    assertTrue(n == 1);
    +                    assertTrue(ba[0] == 'X');
    +
    +                    // urgent data should not be received
    +                    s1.setOOBInline(false);
    +                    s1.setSoTimeout(500);
    +                    s2.sendUrgentData('X');
    +                    try {
    +                        s1.getInputStream().read(ba);
    +                        fail();
    +                    } catch (SocketTimeoutException expected) {
    +                        log(expected);
    +                    }
    +                } finally {
    +                    sender.get();
                     }
                 }
             });
    @@ -437,21 +457,24 @@ void testServerSocketAccept(int timeout) throws Exception {
                     InetAddress loopback = InetAddress.getLoopbackAddress();
                     listener.bind(new InetSocketAddress(loopback, 0));
     
    -                // schedule connect
    +                // connect socket when current thread parks
                     var socket1 = new Socket();
                     SocketAddress remote = listener.getLocalSocketAddress();
    -                var unparker = runAfterParkedAsync(() -> socket1.connect(remote));
    -
    -                // accept should block
    -                if (timeout > 0) {
    -                    listener.setSoTimeout(timeout);
    +                Future connector = runAfterParkedAsync(() -> socket1.connect(remote));
    +                try {
    +                    // accept should block
    +                    if (timeout > 0) {
    +                        listener.setSoTimeout(timeout);
    +                    }
    +                    Socket socket2 = listener.accept();
    +                    socket2.close();
    +                } finally {
    +                    try {
    +                        connector.get();
    +                    } finally {
    +                        socket1.close();
    +                    }
                     }
    -                var socket2 = listener.accept();
    -                socket1.close();
    -                socket2.close();
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
                 }
             });
         }
    @@ -467,18 +490,21 @@ void testServerSocketAcceptAsyncClose(int timeout) throws Exception {
                     InetAddress loopback = InetAddress.getLoopbackAddress();
                     listener.bind(new InetSocketAddress(loopback, 0));
     
    -                // delayed close of listener
    -                runAfterParkedAsync(listener::close);
    -
    -                // accept should block, then throw
    -                if (timeout > 0) {
    -                    listener.setSoTimeout(timeout);
    -                }
    +                // close listener when current thread parks
    +                Future closer = runAfterParkedAsync(listener::close);
                     try {
    -                    listener.accept().close();
    -                    fail("connection accepted???");
    -                } catch (SocketException expected) {
    -                    log(expected);
    +                    // accept should block, then throw
    +                    if (timeout > 0) {
    +                        listener.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        listener.accept().close();
    +                        fail("connection accepted???");
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                    }
    +                } finally {
    +                    closer.get();
                     }
                 }
             });
    @@ -495,21 +521,25 @@ void testServerSocketAcceptInterrupt(int timeout) throws Exception {
                     InetAddress loopback = InetAddress.getLoopbackAddress();
                     listener.bind(new InetSocketAddress(loopback, 0));
     
    -                // delayed interrupt of current thread
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    -                // accept should block, then throw
    -                if (timeout > 0) {
    -                    listener.setSoTimeout(timeout);
    -                }
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
    -                    listener.accept().close();
    -                    fail("connection accepted???");
    -                } catch (SocketException expected) {
    -                    log(expected);
    -                    assertTrue(Thread.interrupted());
    -                    assertTrue(listener.isClosed());
    +
    +                    // accept should block, then throw
    +                    if (timeout > 0) {
    +                        listener.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        listener.accept().close();
    +                        fail("connection accepted???");
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                        assertTrue(Thread.interrupted());
    +                        assertTrue(listener.isClosed());
    +                    }
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -558,24 +588,24 @@ void testDatagramSocketSendReceive(int timeout) throws Exception {
                     s1.bind(new InetSocketAddress(lh, 0));
                     s2.bind(new InetSocketAddress(lh, 0));
     
    -                // delayed send
    +                // send datagram when current thread parks
                     byte[] bytes = "XXX".getBytes("UTF-8");
                     DatagramPacket p1 = new DatagramPacket(bytes, bytes.length);
                     p1.setSocketAddress(s2.getLocalSocketAddress());
    -                var unparker = runAfterParkedAsync(() -> s1.send(p1));
    -
    -                // receive should block
    -                if (timeout > 0) {
    -                    s2.setSoTimeout(timeout);
    +                Future sender = runAfterParkedAsync(() -> s1.send(p1));
    +                try {
    +                    // receive should block
    +                    if (timeout > 0) {
    +                        s2.setSoTimeout(timeout);
    +                    }
    +                    byte[] ba = new byte[100];
    +                    DatagramPacket p2 = new DatagramPacket(ba, ba.length);
    +                    s2.receive(p2);
    +                    assertEquals(s1.getLocalSocketAddress(), p2.getSocketAddress());
    +                    assertTrue(ba[0] == 'X');
    +                } finally {
    +                    sender.get();
                     }
    -                byte[] ba = new byte[100];
    -                DatagramPacket p2 = new DatagramPacket(ba, ba.length);
    -                s2.receive(p2);
    -                assertEquals(s1.getLocalSocketAddress(), p2.getSocketAddress());
    -                assertTrue(ba[0] == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
                 }
             });
         }
    @@ -613,20 +643,23 @@ void testDatagramSocketReceiveAsyncClose(int timeout) throws Exception {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     s.bind(new InetSocketAddress(lh, 0));
     
    -                // delayed close of s
    -                runAfterParkedAsync(s::close);
    -
    -                // receive should block, then throw
    -                if (timeout > 0) {
    -                    s.setSoTimeout(timeout);
    -                }
    +                // close s when current thread parks
    +                Future closer = runAfterParkedAsync(s::close);
                     try {
    -                    byte[] ba = new byte[100];
    -                    DatagramPacket p = new DatagramPacket(ba, ba.length);
    -                    s.receive(p);
    -                    fail();
    -                } catch (SocketException expected) {
    -                    log(expected);
    +                    // receive should block, then throw
    +                    if (timeout > 0) {
    +                        s.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        byte[] ba = new byte[100];
    +                        DatagramPacket p = new DatagramPacket(ba, ba.length);
    +                        s.receive(p);
    +                        fail();
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                    }
    +                } finally {
    +                    closer.get();
                     }
                 }
             });
    @@ -643,23 +676,26 @@ void testDatagramSocketReceiveInterrupt(int timeout) throws Exception {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     s.bind(new InetSocketAddress(lh, 0));
     
    -                // delayed interrupt of current thread
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    -                // receive should block, then throw
    -                if (timeout > 0) {
    -                    s.setSoTimeout(timeout);
    -                }
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
    -                    byte[] ba = new byte[100];
    -                    DatagramPacket p = new DatagramPacket(ba, ba.length);
    -                    s.receive(p);
    -                    fail();
    -                } catch (SocketException expected) {
    -                    log(expected);
    -                    assertTrue(Thread.interrupted());
    -                    assertTrue(s.isClosed());
    +                    // receive should block, then throw
    +                    if (timeout > 0) {
    +                        s.setSoTimeout(timeout);
    +                    }
    +                    try {
    +                        byte[] ba = new byte[100];
    +                        DatagramPacket p = new DatagramPacket(ba, ba.length);
    +                        s.receive(p);
    +                        fail();
    +                    } catch (SocketException expected) {
    +                        log(expected);
    +                        assertTrue(Thread.interrupted());
    +                        assertTrue(s.isClosed());
    +                    }
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -708,74 +744,36 @@ interface ThrowingRunnable {
         }
     
         /**
    -     * The unparker returned by runAfterParkedAsync.
    +     * Runs the given task asynchronously after the current virtual thread parks
    +     * with its parkBlocker set.
    +     * @return future to wait for completion
          */
    -    private static class Unparker {
    -        final Thread thread;
    -        final AtomicReference parkBlockerRef;
    -
    -        Unparker(Thread thread, AtomicReference parkBlockerRef) {
    -            this.thread = thread;
    -            this.parkBlockerRef = parkBlockerRef;
    -        }
    -
    -        Object parkBlocker() {
    -            return parkBlockerRef.get();
    -        }
    -
    -        void join() throws InterruptedException {
    -            thread.join();
    -        }
    -    }
    -
    -    /**
    -     * Runs the given task asynchronously after the current virtual thread parks.
    -     * @param writing if the thread will block in write
    -     * @return the unparker object
    -     */
    -    private static Unparker runAfterParkedAsync(ThrowingRunnable task, boolean writing) {
    +    private static Future runAfterParkedAsync(ThrowingRunnable task) {
             Thread target = Thread.currentThread();
             if (!target.isVirtual())
                 throw new WrongThreadException();
    -        var parkBlockerRef = new AtomicReference();
    -        Thread unparkerThread = Thread.ofPlatform().daemon().start(() -> {
    +        var future = new CompletableFuture();
    +        Thread.ofPlatform().daemon().start(() -> {
                 try {
    -                // wait for target thread to park
    -                while (!isWaiting(target)) {
    -                    Thread.sleep(20);
    +                // wait for target thread to park with its parkBlocker set
    +                while (!isParked(target) || LockSupport.getBlocker(target) == null) {
    +                    Thread.sleep(10);
                     }
     
    -                // if the target thread is parked in write then we nudge it a few times
    -                // to avoid wakeup with some bytes written
    -                if (writing) {
    -                    for (int i = 0; i < 3; i++) {
    -                        LockSupport.unpark(target);
    -                        while (!isWaiting(target)) {
    -                            Thread.sleep(20);
    -                        }
    -                    }
    -                }
    -
    -                // capture the blocker object
    -                parkBlockerRef.set(LockSupport.getBlocker(target));
    -
                     task.run();
    -
    -            } catch (Exception e) {
    -                e.printStackTrace();
    +                future.complete(null);
    +            } catch (Throwable ex) {
    +                ex.printStackTrace();
    +                future.completeExceptionally(ex);
                 }
             });
    -        return new Unparker(unparkerThread, parkBlockerRef);
    -    }
    -
    -    private static Unparker runAfterParkedAsync(ThrowingRunnable task) {
    -        return runAfterParkedAsync(task, false);
    +        return future;
         }
     
         /**
          * Return true if the given Thread is parked.
          */
    -    private static boolean isWaiting(Thread target) {
    +    private static boolean isParked(Thread target) {
             Thread.State state = target.getState();
             assertNotEquals(Thread.State.TERMINATED, state);
             return (state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING);
    diff --git a/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java b/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java
    index 87b7011ff57b..04cdf4a9b064 100644
    --- a/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java
    +++ b/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java
    @@ -68,7 +68,8 @@
     import java.nio.channels.ReadableByteChannel;
     import java.nio.channels.ServerSocketChannel;
     import java.nio.channels.SocketChannel;
    -import java.util.concurrent.atomic.AtomicReference;
    +import java.util.concurrent.CompletableFuture;
    +import java.util.concurrent.Future;
     import java.util.concurrent.locks.LockSupport;
     
     import jdk.test.lib.thread.VThreadRunner;
    @@ -113,18 +114,18 @@ void testSocketChannelRead() throws Exception {
                     SocketChannel sc1 = connection.channel1();
                     SocketChannel sc2 = connection.channel2();
     
    -                // write to sc1 when current thread blocks in sc2.read
    +                // write to sc1 when current thread parks
                     ByteBuffer bb1 = ByteBuffer.wrap("XXX".getBytes("UTF-8"));
    -                var unparker = runAfterParkedAsync(() -> sc1.write(bb1));
    -
    -                // read from sc2 should block
    -                ByteBuffer bb2 = ByteBuffer.allocate(10);
    -                int n = sc2.read(bb2);
    -                assertTrue(n > 0);
    -                assertTrue(bb2.get(0) == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertSame(sc2, unparker.parkBlocker());
    +                Future writer = runAfterParkedAsync(sc2, () -> sc1.write(bb1));
    +                try {
    +                    // read from sc2 should block
    +                    ByteBuffer bb2 = ByteBuffer.allocate(10);
    +                    int n = sc2.read(bb2);
    +                    assertTrue(n > 0);
    +                    assertTrue(bb2.get(0) == 'X');
    +                } finally {
    +                    writer.get();
    +                }
                 }
             });
         }
    @@ -139,23 +140,20 @@ void testSocketChannelWrite() throws Exception {
                     SocketChannel sc1 = connection.channel1();
                     SocketChannel sc2 = connection.channel2();
     
    -                // read from sc2 to EOF when current thread blocks in sc1.write
    -                var unparker = runAfterParkedAsync(() -> readToEOF(sc2));
    -
    -                // write to sc1 should block
    -                ByteBuffer bb = ByteBuffer.allocate(100*1024);
    -                for (int i=0; i<1000; i++) {
    -                    int n = sc1.write(bb);
    -                    assertTrue(n > 0);
    -                    bb.clear();
    +                // read from sc2 to EOF when current thread parks
    +                var reader = runAfterParkedAsync(sc1, () -> readToEOF(sc2));
    +                try {
    +                    // write to sc1 should block
    +                    ByteBuffer bb = ByteBuffer.allocate(100 * 1024);
    +                    for (int i = 0; i < 1000; i++) {
    +                        int n = sc1.write(bb);
    +                        assertTrue(n > 0);
    +                        bb.clear();
    +                    }
    +                } finally {
    +                    sc1.close();    // task will read EOF
    +                    reader.get();
                     }
    -                sc1.close();
    -
    -                // check blocker object was set when thread parked
    -                assertSame(sc1, unparker.parkBlocker());
    -
    -                // wait for reader to finish
    -                unparker.join();
                 }
             });
         }
    @@ -168,11 +166,15 @@ void testSocketChannelReadAsyncClose() throws Exception {
             VThreadRunner.run(() -> {
                 try (var connection = new Connection()) {
                     SocketChannel sc = connection.channel1();
    -                runAfterParkedAsync(sc::close);
    +                Future closer = runAfterParkedAsync(sc::close);
                     try {
                         int n = sc.read(ByteBuffer.allocate(100));
                         fail("read returned " + n);
    -                } catch (AsynchronousCloseException expected) { }
    +                } catch (AsynchronousCloseException _) {
    +                    // expected
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -185,10 +187,14 @@ void testSocketChannelReadAsyncShutdownInput() throws Exception {
             VThreadRunner.run(() -> {
                 try (var connection = new Connection()) {
                     SocketChannel sc = connection.channel1();
    -                runAfterParkedAsync(sc::shutdownInput);
    -                int n = sc.read(ByteBuffer.allocate(100));
    -                assertEquals(-1, n);
    -                assertTrue(sc.isOpen());
    +                Future shutdownInput = runAfterParkedAsync(sc::shutdownInput);
    +                try {
    +                    int n = sc.read(ByteBuffer.allocate(100));
    +                    assertEquals(-1, n);
    +                    assertTrue(sc.isOpen());
    +                } finally {
    +                    shutdownInput.get();
    +                }
                 }
             });
         }
    @@ -202,15 +208,16 @@ void testSocketChannelReadInterrupt() throws Exception {
                 try (var connection = new Connection()) {
                     SocketChannel sc = connection.channel1();
     
    -                // interrupt current thread when it blocks in read
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
                         int n = sc.read(ByteBuffer.allocate(100));
                         fail("read returned " + n);
    -                } catch (ClosedByInterruptException expected) {
    +                } catch (ClosedByInterruptException _) {
                         assertTrue(Thread.interrupted());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -227,30 +234,30 @@ void testSocketChannelWriteAsyncClose() throws Exception {
                     try (var connection = new Connection()) {
                         SocketChannel sc = connection.channel1();
     
    -                    // close sc when current thread blocks in write
    -                    runAfterParkedAsync(sc::close, true);
    -
    -                    // write until channel is closed
    +                    // close sc when current thread parks
    +                    Future closer = runAfterParkedAsync(sc, sc::close);
                         try {
    +                        // write until channel is closed
                             ByteBuffer bb = ByteBuffer.allocate(100*1024);
                             for (;;) {
                                 int n = sc.write(bb);
                                 assertTrue(n > 0);
                                 bb.clear();
                             }
    -                    } catch (AsynchronousCloseException expected) {
    +                    } catch (AsynchronousCloseException _) {
                             // closed when blocked in write
                             done = true;
                         } catch (ClosedChannelException e) {
                             // closed but not blocked in write, need to retry test
                             System.err.format("%s, need to retry!%n", e);
    +                    } finally {
    +                        closer.get();
                         }
                     }
                 }
             });
         }
     
    -
         /**
          * SocketChannel shutdownOutput while virtual thread blocked in write.
          */
    @@ -260,8 +267,8 @@ void testSocketChannelWriteAsyncShutdownOutput() throws Exception {
                 try (var connection = new Connection()) {
                     SocketChannel sc = connection.channel1();
     
    -                // shutdown output when current thread blocks in write
    -                runAfterParkedAsync(sc::shutdownOutput);
    +                // shutdown output when current thread parks
    +                Future shutdownOutput = runAfterParkedAsync(sc::shutdownOutput);
                     try {
                         ByteBuffer bb = ByteBuffer.allocate(100*1024);
                         for (;;) {
    @@ -269,8 +276,10 @@ void testSocketChannelWriteAsyncShutdownOutput() throws Exception {
                             assertTrue(n > 0);
                             bb.clear();
                         }
    -                } catch (ClosedChannelException e) {
    +                } catch (ClosedChannelException _) {
                         // expected
    +                } finally {
    +                    shutdownOutput.get();
                     }
                     assertTrue(sc.isOpen());
                 }
    @@ -288,12 +297,11 @@ void testSocketChannelWriteInterrupt() throws Exception {
                     try (var connection = new Connection()) {
                         SocketChannel sc = connection.channel1();
     
    -                    // interrupt current thread when it blocks in write
    +                    // interrupt current thread when it parks on sc
                         Thread thisThread = Thread.currentThread();
    -                    runAfterParkedAsync(thisThread::interrupt, true);
    -
    -                    // write until channel is closed
    +                    Future interrupter = runAfterParkedAsync(sc, thisThread::interrupt);
                         try {
    +                        // write until channel is closed
                             ByteBuffer bb = ByteBuffer.allocate(100*1024);
                             for (;;) {
                                 int n = sc.write(bb);
    @@ -307,6 +315,8 @@ void testSocketChannelWriteInterrupt() throws Exception {
                         } catch (ClosedChannelException e) {
                             // closed but not blocked in write, need to retry test
                             System.err.format("%s, need to retry!%n", e);
    +                    } finally {
    +                        interrupter.get();
                         }
                     }
                 }
    @@ -324,20 +334,20 @@ void testSocketAdaptorRead(int timeout) throws Exception {
                     SocketChannel sc1 = connection.channel1();
                     SocketChannel sc2 = connection.channel2();
     
    -                // write to sc1 when currnet thread blocks reading from sc2
    +                // write to sc1 when current thread parks on sc2
                     ByteBuffer bb = ByteBuffer.wrap("XXX".getBytes("UTF-8"));
    -                var unparker = runAfterParkedAsync(() -> sc1.write(bb));
    -
    -                // read from sc2 should block
    -                byte[] array = new byte[100];
    -                if (timeout > 0)
    -                    sc2.socket().setSoTimeout(timeout);
    -                int n = sc2.socket().getInputStream().read(array);
    -                assertTrue(n > 0);
    -                assertTrue(array[0] == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertSame(sc2, unparker.parkBlocker());
    +                Future writer = runAfterParkedAsync(sc2, () -> sc1.write(bb));
    +                try {
    +                    // read from sc2 should block
    +                    byte[] array = new byte[100];
    +                    if (timeout > 0)
    +                        sc2.socket().setSoTimeout(timeout);
    +                    int n = sc2.socket().getInputStream().read(array);
    +                    assertTrue(n > 0);
    +                    assertTrue(array[0] == 'X');
    +                } finally {
    +                    writer.get();
    +                }
                 }
             });
         }
    @@ -369,22 +379,25 @@ void testServerSocketChannelAccept2() throws Exception {
                     ssc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
                     var sc1 = SocketChannel.open();
     
    -                // connect when current thread when it blocks in accept
    -                var unparker = runAfterParkedAsync(() -> sc1.connect(ssc.getLocalAddress()));
    -
    -                // accept should block
    -                var sc2 = ssc.accept();
    -                sc1.close();
    -                sc2.close();
    -
    -                // check blocker object was set when thread parked
    -                assertSame(ssc, unparker.parkBlocker());
    +                // connect when current thread blocks in ssc.accept
    +                Future connector = runAfterParkedAsync(ssc, () -> sc1.connect(ssc.getLocalAddress()));
    +                try {
    +                    // accept should block
    +                    SocketChannel sc2 = ssc.accept();
    +                    sc2.close();
    +                } finally {
    +                    try {
    +                        connector.get();
    +                    } finally {
    +                        sc1.close();
    +                    }
    +                }
                 }
             });
         }
     
         /**
    -     * SeverSocketChannel close while virtual thread blocked in accept.
    +     * ServerSocketChannel close while virtual thread blocked in accept.
          */
         @Test
         void testServerSocketChannelAcceptAsyncClose() throws Exception {
    @@ -392,12 +405,16 @@ void testServerSocketChannelAcceptAsyncClose() throws Exception {
                 try (var ssc = ServerSocketChannel.open()) {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     ssc.bind(new InetSocketAddress(lh, 0));
    -                runAfterParkedAsync(ssc::close);
    +                Future closer = runAfterParkedAsync(ssc::close);
                     try {
                         SocketChannel sc = ssc.accept();
                         sc.close();
                         fail("connection accepted???");
    -                } catch (AsynchronousCloseException expected) { }
    +                } catch (AsynchronousCloseException _) {
    +                    // expected
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -412,16 +429,17 @@ void testServerSocketChannelAcceptInterrupt() throws Exception {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     ssc.bind(new InetSocketAddress(lh, 0));
     
    -                // interrupt current thread when it blocks in accept
    +                // interrupt current thread when it parks
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
                         SocketChannel sc = ssc.accept();
                         sc.close();
                         fail("connection accepted???");
    -                } catch (ClosedByInterruptException expected) {
    +                } catch (ClosedByInterruptException _) {
                         assertTrue(Thread.interrupted());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -438,18 +456,21 @@ void testSocketChannelAdaptorAccept(int timeout) throws Exception {
                     ssc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
                     var sc = SocketChannel.open();
     
    -                // interrupt current thread when it blocks in accept
    -                var unparker = runAfterParkedAsync(() -> sc.connect(ssc.getLocalAddress()));
    -
    -                // accept should block
    -                if (timeout > 0)
    -                    ssc.socket().setSoTimeout(timeout);
    -                Socket s = ssc.socket().accept();
    -                sc.close();
    -                s.close();
    -
    -                // check blocker object was set when thread parked
    -                assertSame(ssc, unparker.parkBlocker());
    +                // connect when current thread blocks in ssc.accept
    +                Future connector = runAfterParkedAsync(ssc, () -> sc.connect(ssc.getLocalAddress()));
    +                try {
    +                    // accept should block
    +                    if (timeout > 0)
    +                        ssc.socket().setSoTimeout(timeout);
    +                    Socket s = ssc.socket().accept();
    +                    s.close();
    +                } finally {
    +                    try {
    +                        connector.get();
    +                    } finally {
    +                        sc.close();
    +                    }
    +                }
                 }
             });
         }
    @@ -491,17 +512,17 @@ void testDatagramChannelSendReceive2() throws Exception {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     dc2.bind(new InetSocketAddress(lh, 0));
     
    -                // send from dc1 when current thread blocked in dc2.receive
    +                // send from dc1 when current thread blocks in dc2.receive
                     ByteBuffer bb1 = ByteBuffer.wrap("XXX".getBytes("UTF-8"));
    -                var unparker = runAfterParkedAsync(() -> dc1.send(bb1, dc2.getLocalAddress()));
    -
    -                // read from dc2 should block
    -                ByteBuffer bb2 = ByteBuffer.allocate(10);
    -                dc2.receive(bb2);
    -                assertTrue(bb2.get(0) == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertSame(dc2, unparker.parkBlocker());
    +                Future sender = runAfterParkedAsync(dc2, () -> dc1.send(bb1, dc2.getLocalAddress()));
    +                try {
    +                    // read from dc2 should block
    +                    ByteBuffer bb2 = ByteBuffer.allocate(10);
    +                    dc2.receive(bb2);
    +                    assertTrue(bb2.get(0) == 'X');
    +                } finally {
    +                    sender.get();
    +                }
                 }
             });
         }
    @@ -515,11 +536,15 @@ void testDatagramChannelReceiveAsyncClose() throws Exception {
                 try (DatagramChannel dc = DatagramChannel.open()) {
                     InetAddress lh = InetAddress.getLoopbackAddress();
                     dc.bind(new InetSocketAddress(lh, 0));
    -                runAfterParkedAsync(dc::close);
    +                Future closer = runAfterParkedAsync(dc::close);
                     try {
                         dc.receive(ByteBuffer.allocate(100));
                         fail("receive returned");
    -                } catch (AsynchronousCloseException expected) { }
    +                } catch (AsynchronousCloseException _) {
    +                    // expected
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -536,13 +561,14 @@ void testDatagramChannelReceiveInterrupt() throws Exception {
     
                     // interrupt current thread when it blocks in receive
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
                         dc.receive(ByteBuffer.allocate(100));
                         fail("receive returned");
    -                } catch (ClosedByInterruptException expected) {
    +                } catch (ClosedByInterruptException _) {
                         assertTrue(Thread.interrupted());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -563,18 +589,18 @@ void testDatagramSocketAdaptorReceive(int timeout) throws Exception {
     
                     // send from dc1 when current thread blocks in dc2 receive
                     ByteBuffer bb = ByteBuffer.wrap("XXX".getBytes("UTF-8"));
    -                var unparker = runAfterParkedAsync(() -> dc1.send(bb, dc2.getLocalAddress()));
    -
    -                // receive should block
    -                byte[] array = new byte[100];
    -                DatagramPacket p = new DatagramPacket(array, 0, array.length);
    -                if (timeout > 0)
    -                    dc2.socket().setSoTimeout(timeout);
    -                dc2.socket().receive(p);
    -                assertTrue(p.getLength() == 3 && array[0] == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertSame(dc2, unparker.parkBlocker());
    +                Future sender = runAfterParkedAsync(dc2, () -> dc1.send(bb, dc2.getLocalAddress()));
    +                try {
    +                    // receive should block
    +                    byte[] array = new byte[100];
    +                    DatagramPacket p = new DatagramPacket(array, 0, array.length);
    +                    if (timeout > 0)
    +                        dc2.socket().setSoTimeout(timeout);
    +                    dc2.socket().receive(p);
    +                    assertTrue(p.getLength() == 3 && array[0] == 'X');
    +                } finally {
    +                    sender.get();
    +                }
                 }
             });
         }
    @@ -596,9 +622,12 @@ void testDatagramSocketAdaptorReceiveAsyncClose(int timeout) throws Exception {
                         dc.socket().setSoTimeout(timeout);
     
                     // close channel/socket when current thread blocks in receive
    -                runAfterParkedAsync(dc::close);
    -
    -                assertThrows(SocketException.class, () -> dc.socket().receive(p));
    +                Future closer = runAfterParkedAsync(dc::close);
    +                try {
    +                    assertThrows(SocketException.class, () -> dc.socket().receive(p));
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -621,13 +650,14 @@ void testDatagramSocketAdaptorReceiveInterrupt(int timeout) throws Exception {
     
                     // interrupt current thread when it blocks in receive
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
                         dc.socket().receive(p);
                         fail();
    -                } catch (ClosedByInterruptException expected) {
    +                } catch (ClosedByInterruptException _) {
                         assertTrue(Thread.interrupted());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -669,16 +699,16 @@ void testPipeReadWrite2() throws Exception {
     
                     // write from sink when current thread blocks reading from source
                     ByteBuffer bb1 = ByteBuffer.wrap("XXX".getBytes("UTF-8"));
    -                var unparker = runAfterParkedAsync(() -> sink.write(bb1));
    -
    -                // read should block
    -                ByteBuffer bb2 = ByteBuffer.allocate(10);
    -                int n = source.read(bb2);
    -                assertTrue(n > 0);
    -                assertTrue(bb2.get(0) == 'X');
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
    +                Future writer = runAfterParkedAsync(() -> sink.write(bb1));
    +                try {
    +                    // read should block
    +                    ByteBuffer bb2 = ByteBuffer.allocate(10);
    +                    int n = source.read(bb2);
    +                    assertTrue(n > 0);
    +                    assertTrue(bb2.get(0) == 'X');
    +                } finally {
    +                    writer.get();
    +                }
                 }
             });
         }
    @@ -693,23 +723,21 @@ void testPipeReadWrite3() throws Exception {
                 try (Pipe.SinkChannel sink = p.sink();
                      Pipe.SourceChannel source = p.source()) {
     
    -                // read from source to EOF when current thread blocking in write
    -                var unparker = runAfterParkedAsync(() -> readToEOF(source));
    +                // read from source to EOF when current thread blocks in write
    +                Future reader = runAfterParkedAsync(() -> readToEOF(source));
    +                try {
    +                    // write to sink should block
    +                    ByteBuffer bb = ByteBuffer.allocate(100 * 1024);
    +                    for (int i = 0; i < 1000; i++) {
    +                        int n = sink.write(bb);
    +                        assertTrue(n > 0);
    +                        bb.clear();
    +                    }
     
    -                // write to sink should block
    -                ByteBuffer bb = ByteBuffer.allocate(100*1024);
    -                for (int i=0; i<1000; i++) {
    -                    int n = sink.write(bb);
    -                    assertTrue(n > 0);
    -                    bb.clear();
    +                } finally {
    +                    sink.close();    // task will read EOF
    +                    reader.get();
                     }
    -                sink.close();
    -
    -                // check blocker object was set when thread parked
    -                assertNotNull(unparker.parkBlocker());
    -
    -                // wait for reader to finish
    -                unparker.join();
                 }
             });
         }
    @@ -723,11 +751,15 @@ void testPipeReadAsyncClose() throws Exception {
                 Pipe p = Pipe.open();
                 try (Pipe.SinkChannel sink = p.sink();
                      Pipe.SourceChannel source = p.source()) {
    -                runAfterParkedAsync(source::close);
    +                Future closer = runAfterParkedAsync(source::close);
                     try {
                         int n = source.read(ByteBuffer.allocate(100));
                         fail("read returned " + n);
    -                } catch (AsynchronousCloseException expected) { }
    +                } catch (AsynchronousCloseException _) {
    +                    // expected
    +                } finally {
    +                    closer.get();
    +                }
                 }
             });
         }
    @@ -744,13 +776,14 @@ void testPipeReadInterrupt() throws Exception {
     
                     // interrupt current thread when it blocks reading from source
                     Thread thisThread = Thread.currentThread();
    -                runAfterParkedAsync(thisThread::interrupt);
    -
    +                Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                     try {
                         int n = source.read(ByteBuffer.allocate(100));
                         fail("read returned " + n);
    -                } catch (ClosedByInterruptException expected) {
    +                } catch (ClosedByInterruptException _) {
                         assertTrue(Thread.interrupted());
    +                } finally {
    +                    interrupter.get();
                     }
                 }
             });
    @@ -769,10 +802,9 @@ void testPipeWriteAsyncClose() throws Exception {
                          Pipe.SourceChannel source = p.source()) {
     
                         // close sink when current thread blocks in write
    -                    runAfterParkedAsync(sink::close, true);
    -
    -                    // write until channel is closed
    +                    Future closer = runAfterParkedAsync(sink::close);
                         try {
    +                        // write until channel is closed
                             ByteBuffer bb = ByteBuffer.allocate(100*1024);
                             for (;;) {
                                 int n = sink.write(bb);
    @@ -785,6 +817,8 @@ void testPipeWriteAsyncClose() throws Exception {
                         } catch (ClosedChannelException e) {
                             // closed but not blocked in write, need to retry test
                             System.err.format("%s, need to retry!%n", e);
    +                    } finally {
    +                        closer.get();
                         }
                     }
                 }
    @@ -805,23 +839,24 @@ void testPipeWriteInterrupt() throws Exception {
     
                         // interrupt current thread when it blocks in write
                         Thread thisThread = Thread.currentThread();
    -                    runAfterParkedAsync(thisThread::interrupt, true);
    -
    -                    // write until channel is closed
    +                    Future interrupter = runAfterParkedAsync(thisThread::interrupt);
                         try {
    +                        // write until channel is closed
                             ByteBuffer bb = ByteBuffer.allocate(100*1024);
                             for (;;) {
                                 int n = sink.write(bb);
                                 assertTrue(n > 0);
                                 bb.clear();
                             }
    -                    } catch (ClosedByInterruptException expected) {
    +                    } catch (ClosedByInterruptException _) {
                             // closed when blocked in write
                             assertTrue(Thread.interrupted());
                             done = true;
                         } catch (ClosedChannelException e) {
                             // closed but not blocked in write, need to retry test
                             System.err.format("%s, need to retry!%n", e);
    +                    } finally {
    +                        interrupter.get();
                         }
                     }
                 }
    @@ -881,74 +916,45 @@ interface ThrowingRunnable {
         }
     
         /**
    -     * The unparker returned by runAfterParkedAsync.
    -     */
    -    private static class Unparker {
    -        final Thread thread;
    -        final AtomicReference parkBlockerRef;
    -
    -        Unparker(Thread thread, AtomicReference parkBlockerRef) {
    -            this.thread = thread;
    -            this.parkBlockerRef = parkBlockerRef;
    -        }
    -
    -        Object parkBlocker() {
    -            return parkBlockerRef.get();
    -        }
    -
    -        void join() throws InterruptedException {
    -            thread.join();
    -        }
    -    }
    -
    -    /**
    -     * Runs the given task asynchronously after the current virtual thread parks.
    -     * @param writing if the thread will block in write
    -     * @return the unparker object
    +     * Runs the given task asynchronously after the current virtual thread parks with
    +     * its parkBlocker set.
    +     * @param parkBlocker non-null if the expected parkBlocker is known
    +     * @param task the task to run when the thread parks
    +     * @return future to wait for completion
          */
    -    private static Unparker runAfterParkedAsync(ThrowingRunnable task, boolean writing) {
    +    private static Future runAfterParkedAsync(Object parkBlocker, ThrowingRunnable task) {
             Thread target = Thread.currentThread();
             if (!target.isVirtual())
                 throw new WrongThreadException();
    -        var parkBlockerRef = new AtomicReference();
    -        Thread unparkerThread = Thread.ofPlatform().daemon().start(() -> {
    +        var future = new CompletableFuture();
    +        Thread.ofPlatform().daemon().start(() -> {
                 try {
    -                // wait for target thread to park
    -                while (!isWaiting(target)) {
    -                    Thread.sleep(20);
    +                // wait for target thread to park with its parkBlocker set
    +                Object b;
    +                while (!isParked(target)
    +                        || (b = LockSupport.getBlocker(target)) == null
    +                        || (parkBlocker != null && b != parkBlocker)) {
    +                    Thread.sleep(10);
                     }
     
    -                // if the target thread is parked in write then we nudge it a few times
    -                // to avoid wakeup with some bytes written
    -                if (writing) {
    -                    for (int i = 0; i < 3; i++) {
    -                        LockSupport.unpark(target);
    -                        while (!isWaiting(target)) {
    -                            Thread.sleep(20);
    -                        }
    -                    }
    -                }
    -
    -                // capture the blocker object
    -                parkBlockerRef.set(LockSupport.getBlocker(target));
    -
                     task.run();
    -
    -            } catch (Exception e) {
    -                e.printStackTrace();
    +                future.complete(null);
    +            } catch (Throwable ex) {
    +                ex.printStackTrace();
    +                future.completeExceptionally(ex);
                 }
             });
    -        return new Unparker(unparkerThread, parkBlockerRef);
    +        return future;
         }
     
    -    private static Unparker runAfterParkedAsync(ThrowingRunnable task) {
    -        return runAfterParkedAsync(task, false);
    +    private static Future runAfterParkedAsync(ThrowingRunnable task) {
    +        return runAfterParkedAsync(null, task);
         }
     
         /**
          * Return true if the given Thread is parked.
          */
    -    private static boolean isWaiting(Thread target) {
    +    private static boolean isParked(Thread target) {
             Thread.State state = target.getState();
             assertNotEquals(Thread.State.TERMINATED, state);
             return (state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING);
    diff --git a/test/jdk/java/security/cert/X509Certificate/VerifyDefault.java b/test/jdk/java/security/cert/X509Certificate/VerifyDefault.java
    index 78dfc5a44134..328d3e807a4f 100644
    --- a/test/jdk/java/security/cert/X509Certificate/VerifyDefault.java
    +++ b/test/jdk/java/security/cert/X509Certificate/VerifyDefault.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -23,11 +23,11 @@
     
     /**
      * @test
    - * @bug 8175029
    + * @bug 8175029 8377979
      * @library /test/lib
      * @summary check that default implementation of
      *          X509Certificate.verify(PublicKey, Provider) works on custom
    - *          X509Certificate impl.
    + *          X509Certificate impl. and verify certificate validity
      */
     
     import java.math.BigInteger;
    @@ -43,10 +43,11 @@
     import java.security.cert.CertificateExpiredException;
     import java.security.cert.CertificateNotYetValidException;
     import java.security.cert.X509Certificate;
    -import java.util.Collection;
    +import java.time.Instant;
     import java.util.Date;
    -import java.util.List;
     import java.util.Set;
    +
    +import jdk.test.lib.Asserts;
     import jdk.test.lib.security.CertUtils;
     
     public class VerifyDefault {
    @@ -134,7 +135,65 @@ public void verify(PublicKey key, String sigProvider) throws
     
         public static void main(String[] args) throws Exception {
             X509Certificate cert = CertUtils.getCertFromString(TEST_CERT);
    +
    +        // verify the certs
    +        new TestX509Certificate(cert).verify(cert.getPublicKey());
             new TestX509Certificate(cert).verify(cert.getPublicKey(),
                                                  (Provider)null);
    +
    +        // verify the validity dates
    +        verifyValidityTimes(cert);
    +    }
    +
    +    private static void verifyValidityTimes(final X509Certificate cert)
    +            throws CertificateNotYetValidException,
    +            CertificateExpiredException {
    +
    +        final Date notBeforeDate = cert.getNotBefore();
    +        final Instant notBeforeInstant = cert.getNotBeforeInstant();
    +        final Date notAfterDate = cert.getNotAfter();
    +        final Instant notAfterInstant = cert.getNotAfterInstant();
    +
    +        // checking dates returned by the cert
    +        Asserts.assertNotNull(notBeforeDate);
    +        Asserts.assertNotNull(notBeforeInstant);
    +        Asserts.assertNotNull(notAfterDate);
    +        Asserts.assertNotNull(notAfterInstant);
    +        Asserts.assertEquals(notBeforeInstant.toString(),
    +                "2017-03-28T16:47:26Z");
    +        Asserts.assertEquals(notAfterInstant.toString(),
    +                "2017-06-26T16:47:26Z");
    +        Asserts.assertEquals(notBeforeDate.getTime(),
    +                notBeforeInstant.toEpochMilli());
    +        Asserts.assertEquals(notAfterDate.getTime(),
    +                notAfterInstant.toEpochMilli());
    +
    +        // checking validity of the cert
    +        final Instant validInstant = Instant.parse("2017-05-26T16:47:26Z");
    +        final Instant expiredInstant = Instant.parse("2018-05-26T16:47:26Z");
    +        final Instant notYetValidInstant =
    +                Instant.parse("2012-05-26T16:47:26Z");
    +
    +        cert.checkValidity(validInstant);
    +        Asserts.assertThrows(CertificateExpiredException.class,
    +                () -> cert.checkValidity(expiredInstant));
    +        Asserts.assertThrows(CertificateNotYetValidException.class,
    +                () -> cert.checkValidity(notYetValidInstant));
    +
    +        // checking the default checkValidity(Instant) implementation:
    +        // instants outside the range representable by Date must not throw
    +        // IllegalArgumentException; they are clamped to the nearest Date
    +        X509Certificate defaultImplCert = new TestX509Certificate(cert);
    +        Asserts.assertThrows(CertificateExpiredException.class,
    +                () -> defaultImplCert.checkValidity(Instant.MAX));
    +        Asserts.assertThrows(CertificateNotYetValidException.class,
    +                () -> defaultImplCert.checkValidity(Instant.MIN));
    +
    +        cert.checkValidity(Date.from(validInstant));
    +        Asserts.assertThrows(CertificateExpiredException.class,
    +                () -> cert.checkValidity(Date.from(expiredInstant)));
    +        Asserts.assertThrows(CertificateNotYetValidException.class,
    +                () -> cert.checkValidity(Date.from(notYetValidInstant)));
    +
         }
     }
    diff --git a/test/jdk/java/util/zip/ZipOutputStream/ZipOutputStreamMaxCenHdrTest.java b/test/jdk/java/util/zip/ZipOutputStream/ZipOutputStreamMaxCenHdrTest.java
    new file mode 100644
    index 000000000000..b1958c39dd34
    --- /dev/null
    +++ b/test/jdk/java/util/zip/ZipOutputStream/ZipOutputStreamMaxCenHdrTest.java
    @@ -0,0 +1,200 @@
    +/*
    + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/* @test
    + * @bug 8396845
    + * @summary Verify that ZipOutputStream throws a ZipException when the
    + * CEN header size + name length + comment length + extra length exceeds
    + * 65,535 bytes
    + * @run junit ZipOutputStreamMaxCenHdrTest
    + */
    +import org.junit.jupiter.api.BeforeEach;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.Arguments;
    +import org.junit.jupiter.params.provider.MethodSource;
    +
    +import java.io.BufferedOutputStream;
    +import java.io.IOException;
    +import java.nio.ByteBuffer;
    +import java.nio.ByteOrder;
    +import java.nio.file.Files;
    +import java.nio.file.Path;
    +import java.nio.file.attribute.FileTime;
    +import java.util.Arrays;
    +import java.util.stream.Stream;
    +import java.util.zip.ZipEntry;
    +import java.util.zip.ZipException;
    +import java.util.zip.ZipFile;
    +import java.util.zip.ZipOutputStream;
    +
    +import static org.junit.jupiter.api.Assertions.*;
    +
    +public class ZipOutputStreamMaxCenHdrTest {
    +
    +    // CEN header size + name length + comment length + extra length
    +    // should not exceed 65,535 bytes per the PKWare APP.NOTE
    +    // 4.4.10, 4.4.11, & 4.4.12.
    +    static final int MAX_COMBINED_CEN_HEADER_SIZE = 0xFFFF;
    +    // Tag for the 'unknown' field type, specified in APPNOTE.txt 'Third party mappings'
    +    static final short UNKNOWN_ZIP_TAG = (short) 0x9902;
    +    // ZIP file to be used by the tests
    +    static final Path ZIP_FILE = Path.of("maxCENHdrTest.zip");
    +    // Zip Entry name used by tests
    +    static final String ENTRY_NAME = "EntryName";
    +    // CEN Extra field info-zip extended timestamp MTIME size
    +    static final int MTIME_EXTRA_SIZE = 9;
    +
    +    /**
    +     * Clean up prior to test run
    +     *
    +     * @throws IOException if an error occurs
    +     */
    +    @BeforeEach
    +    public void startUp() throws IOException {
    +        Files.deleteIfExists(ZIP_FILE);
    +    }
    +
    +    /**
    +     * Validate an ZipException is thrown when the combined CEN Header, name
    +     * length, comment length, and extra data length exceeds 65,535 bytes when
    +     * the ZipOutputStream is closed.
    +     * @param  cenSize size of the combined CEN header to test
    +     * @param  setLastModifiedTime true if ZipEntry::setLastModifiedTime called;false otherwise
    +     */
    +    @ParameterizedTest
    +    @MethodSource("CEN_header_test_params")
    +    void setNameExtraSizeTest(int cenSize, boolean setLastModifiedTime) {
    +        int timestampSize = setLastModifiedTime ? MTIME_EXTRA_SIZE : 0;
    +        int length = cenSize - ZipEntry.CENHDR - timestampSize;
    +        boolean expectException = cenSize > MAX_COMBINED_CEN_HEADER_SIZE;
    +        ZipEntry zipEntry = new ZipEntry("a".repeat(length));
    +        if (setLastModifiedTime) {
    +            zipEntry.setLastModifiedTime(FileTime.fromMillis(0));
    +        }
    +        writeZipEntry(zipEntry, expectException);
    +    }
    +
    +    /**
    +     * Validate an ZipException is thrown when the combined CEN Header, name
    +     * length, comment length, and extra data length exceeds 65,535 bytes when
    +     * the ZipOutputStream is closed.
    +     * @param  cenSize size of the combined CEN header to test
    +     * @param  setLastModifiedTime true if ZipEntry::setLastModifiedTime called;false otherwise
    +     */
    +    @ParameterizedTest
    +    @MethodSource("CEN_header_test_params")
    +    void setCommentExtraSizeTest(int cenSize, boolean setLastModifiedTime) {
    +        int timestampSize = setLastModifiedTime ? MTIME_EXTRA_SIZE : 0;
    +        int length = cenSize - ZipEntry.CENHDR - ENTRY_NAME.length() - timestampSize;
    +        boolean expectException = cenSize > MAX_COMBINED_CEN_HEADER_SIZE;
    +        ZipEntry zipEntry = new ZipEntry(ENTRY_NAME);
    +        zipEntry.setComment("a".repeat(length));
    +        if (setLastModifiedTime) {
    +            zipEntry.setLastModifiedTime(FileTime.fromMillis(0));
    +        }
    +        writeZipEntry(zipEntry, expectException);
    +    }
    +
    +    /**
    +     * Validate an ZipException is thrown when the combined CEN Header, name
    +     * length, comment length, and extra data length exceeds 65,535 bytes when
    +     * the ZipOutputStream is closed.
    +     * @param  cenSize size of the combined CEN header to test
    +     * @param  setLastModifiedTime true if ZipEntry::setLastModifiedTime called;false otherwise
    +     */
    +    @ParameterizedTest
    +    @MethodSource("CEN_header_test_params")
    +    void setExtraExtraSizeTest(int cenSize, boolean setLastModifiedTime) {
    +        int timestampSize = setLastModifiedTime ? MTIME_EXTRA_SIZE : 0;
    +        int length = cenSize - ZipEntry.CENHDR - ENTRY_NAME.length() - timestampSize;
    +        boolean expectException = cenSize > MAX_COMBINED_CEN_HEADER_SIZE;
    +        final byte[] bytes = new byte[length];
    +        Arrays.fill(bytes, (byte) 'a');
    +        // Little-endian ByteBuffer for updating the header fields
    +        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
    +        // We use the 'unknown' tag, specified in APPNOTE.TXT, 4.6.1 Third party mappings'
    +        buffer.putShort(UNKNOWN_ZIP_TAG);
    +        // Size of the actual data
    +        buffer.putShort((short) (length - 2 * Short.BYTES));
    +        ZipEntry zipEntry = new ZipEntry(ENTRY_NAME);
    +        System.out.printf("extra Len= %s, exception: %s%n", bytes.length, expectException);
    +        zipEntry.setExtra(bytes);
    +        if (setLastModifiedTime) {
    +            zipEntry.setLastModifiedTime(FileTime.fromMillis(0));
    +        }
    +        writeZipEntry(zipEntry, expectException);
    +    }
    +
    +    /**
    +     * Method used to provide arguments for testing the combined CEN size limit.
    +     * A ZipException is expected when the stream is closed when the CEN Header,
    +     * name length, comment length, and extra data length exceeds 65,535 bytes
    +     * 

    + * Each argument pair contains the final combined CEN size and a boolean + * indicating whether to set the last modification time. + * + * @return stream of test arguments + */ + private static Stream CEN_header_test_params() { + return Stream.of( + Arguments.of(65_534, false), + Arguments.of(65_535, false), + Arguments.of(65_534, true), + Arguments.of(65_535, true), + Arguments.of(65_536, true) + ); + } + + /** + * Write a single Zip entry using ZipOutputStream + * + * @param zipEntry the ZipEntry to write + * @param expectedException true if a ZipException should be thrown; false otherwise + */ + private static void writeZipEntry(ZipEntry zipEntry, boolean expectedException) { + boolean receivedException = false; + try (ZipOutputStream zos = new ZipOutputStream( + new BufferedOutputStream(Files.newOutputStream(ZIP_FILE)))) { + assertDoesNotThrow(() -> zos.putNextEntry(zipEntry)); + } catch (Exception e) { + assertInstanceOf(ZipException.class, e); + String emsg = e.getMessage(); + assertNotNull(emsg, "Expected ZipException message!"); + assertTrue(emsg.contains("bad header size"), "Unexpected ZipException message: " + emsg); + receivedException = true; + System.out.printf("writeZipEntry: exception: %s%n", e.getMessage()); + } + assertEquals(expectedException, receivedException); + // If we do not expect an Exception, sanity check we can open the ZIP file + if (!expectedException) { + assertDoesNotThrow(() -> { + try (ZipFile zip = new ZipFile(ZIP_FILE.toFile())) { + assertEquals(1, zip.size()); + ZipEntry actual = zip.getEntry(zipEntry.getName()); + assertNotNull(actual); + assertEquals(zipEntry.getComment(), actual.getComment()); + } + }); + } + } +} diff --git a/test/jdk/javax/crypto/KeyGenerator/CompareKeys.java b/test/jdk/javax/crypto/KeyGenerator/CompareKeys.java index 0ee2ca3bd0b8..c8ae5f28d5c6 100644 --- a/test/jdk/javax/crypto/KeyGenerator/CompareKeys.java +++ b/test/jdk/javax/crypto/KeyGenerator/CompareKeys.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,7 +38,7 @@ /* * @test - * @bug 8185127 + * @bug 8185127 8385968 * @summary Test key comparison for the Keys generated through KeyGenerator * @run main CompareKeys */ @@ -54,6 +54,15 @@ public static void main(String[] args) throws Exception { } for (KeygenAlgo alg : getSupportedAlgo("KeyPairGenerator")) { + // TLS hybrid KEM public keys use RAW key_share encoding and + // have no KeyFactory or X.509 encoding. + if (alg.provider().getService("KeyFactory", alg.algoName()) + == null) { + System.out.printf("Skipping provider %s and algorithm %s: " + + "no KeyFactory%n", alg.provider().getName(), + alg.algoName()); + continue; + } System.out.printf("Verifying provider %s and algorithm %s%n", alg.provider().getName(), alg.algoName()); KeyPair kp = genKeyPair(alg.algoName(), alg.provider()); diff --git a/test/jdk/jdk/incubator/vector/BasicFloat16ArithTests.java b/test/jdk/jdk/incubator/vector/BasicFloat16ArithTests.java index cdc7ce566f78..8798a8835278 100644 --- a/test/jdk/jdk/incubator/vector/BasicFloat16ArithTests.java +++ b/test/jdk/jdk/incubator/vector/BasicFloat16ArithTests.java @@ -23,13 +23,14 @@ /* * @test - * @bug 8329817 8334432 8339076 8341260 8362207 + * @bug 8329817 8334432 8339076 8341260 8362207 8394644 * @modules jdk.incubator.vector * @summary Basic tests of Float16 arithmetic and similar operations */ import jdk.incubator.vector.Float16; import static jdk.incubator.vector.Float16.*; +import java.math.BigDecimal; import java.util.HashSet; import java.util.List; @@ -530,6 +531,16 @@ private static void checkValueOfString() { new String2Float16Case("+0.0", 0.0f), new String2Float16Case("-0.0", -0.0f), + // Subnormal range + new String2Float16Case( "0x1.00000000000001p-25", MIN_VAL_FP16), + + new String2Float16Case( "2.9802322387695313e-8", MIN_VAL_FP16), + new String2Float16Case("-2.9802322387695313e-8", -MIN_VAL_FP16), + + new String2Float16Case( "8.9406967163085937e-8", MIN_VAL_FP16), + + new String2Float16Case( "6.1005353927612304e-5", 0x0.ffcp-14f), // Float16 max subnormal + // Decimal signed integers are accepted as input; hex // signed integers are not, see negative test cases below. new String2Float16Case( "1", 1.0f), @@ -619,6 +630,31 @@ private static void checkValueOfString() { } } + // Test half-way rounding cases + for(int i = 0; i <= Short.MAX_VALUE; i++ ) { + boolean isEven = ((i & 0x1) == 0); + Float16 f16 = Float16.shortBitsToFloat16((short)i); + + if (!isFinite(f16)) + continue; + + Float16 ulp = ulp(f16); + float halfWay = f16.floatValue() + ulp.floatValue() * 0.5f; + + Float16 result = Float16.valueOf((new BigDecimal( halfWay)).toString()); + Float16 resultNeg = Float16.valueOf((new BigDecimal(-halfWay)).toString()); + + // Under the round to nearest even rounding policy, the + // half-way case should round down to the starting value + // if the starting value is even; otherwise, it should round up. + float expected = (isEven ? + f16.floatValue() : + add(f16, ulp).floatValue()); + + checkFloat16(result, expected, "Half-way case"); + checkFloat16(resultNeg, -expected, "Half-way case"); + } + return; } diff --git a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingStop.java b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingStop.java index a367c218baac..0b3202834140 100644 --- a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingStop.java +++ b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingStop.java @@ -43,9 +43,10 @@ public class TestCPUTimeSamplingStop { private static final int TEST_ITERATIONS = 100; private static final int LOOP_ITERATIONS = 100; private static final int DELAY_MILLIS = 2; + private static final int MAX_THREADS = 64; public static void main(String[] args) throws Exception { - int threads = Math.max(Runtime.getRuntime().availableProcessors() - 1, 2); + int threads = Math.clamp(Runtime.getRuntime().availableProcessors() - 1, 2, MAX_THREADS); for (int i = 0; i < threads; i++) { Thread t = new Thread(TestCPUTimeSamplingStop::nativeBurner, "Native CPU burner " + i); t.setDaemon(true); diff --git a/test/jdk/jdk/jfr/event/runtime/TestExceptionEvents.java b/test/jdk/jdk/jfr/event/runtime/TestExceptionEvents.java index 8c447ac44bf3..b861dc5e3acf 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestExceptionEvents.java +++ b/test/jdk/jdk/jfr/event/runtime/TestExceptionEvents.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,176 +23,357 @@ package jdk.jfr.event.runtime; -import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; import java.util.List; +import java.util.Objects; import jdk.jfr.Recording; -import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedFrame; -import jdk.jfr.consumer.RecordedStackTrace; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.EventNames; import jdk.test.lib.jfr.Events; -/** +/* * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.event.runtime.TestExceptionEvents */ +@SuppressWarnings("serial") public class TestExceptionEvents { + private static final String EXCEPTION_EVENT_NAME = EventNames.JavaExceptionThrow; + private static final String ERROR_EVENT_NAME = EventNames.JavaErrorThrow; + private static final String EXCEPTION_STATISTICS_NAME = EventNames.ExceptionStatistics; + private static final String THREAD_NAME = Thread.currentThread().getName(); + private static final int THROWN_EXCEPTIONS = 5000; + private static final int NOISE_EXCEPTIONS = 2400; - private static final String EXCEPTION_EVENT_PATH = EventNames.JavaExceptionThrow; - private static final String ERROR_EVENT_PATH = EventNames.JavaErrorThrow; - private static final String EXCEPTION_STATISTICS_PATH = EventNames.ExceptionStatistics; - - private static final String EXCEPTION_MESSAGE = "exceptiontest"; - private static final String ERROR_MESSAGE = "errortest"; - private static final String THROWABLE_MESSAGE = "throwabletest"; - - private static final int ITERATIONS = 10; + public static void main(String[] args) throws Throwable { + testCheckedException(); + testRuntimeException(); + testThrowableException(); + testError(); + testErrorAndException(); + testErrorConstructors(); + testThrowableConstructors(); + testThrottling(); + } - private static int exceptionCount = 0; + private static void testCheckedException() throws Exception { + testException(MyCheckedException.class, "testCheckedException"); + } - public static void main(String[] args) throws Throwable { - Recording recording = createRecording(); + private static void testRuntimeException() throws Exception { + testException(MyRuntimeException.class, "testRuntimeException"); + } - List events = Events.fromRecording(recording); - checkStatisticsEvent(events, exceptionCount); - checkThrowableEvents(events, EXCEPTION_EVENT_PATH, ITERATIONS, MyException.class, EXCEPTION_MESSAGE); - checkThrowableEvents(events, ERROR_EVENT_PATH, ITERATIONS, MyError.class, ERROR_MESSAGE); - checkThrowableEvents(events, EXCEPTION_EVENT_PATH, ITERATIONS, MyThrowable.class, THROWABLE_MESSAGE); - checkExceptionStackTrace(); + private static void testThrowableException() throws Exception { + testException(MyThrowable.class, "testThrowableException"); } - private static void checkExceptionStackTrace() throws Exception { - @SuppressWarnings("serial") - class TestError extends Error { + private static void testError() throws Exception { + String message = "testError"; + try (Recording r = new Recording()) { + r.enable(ERROR_EVENT_NAME).withStackTrace(); + r.enable(EXCEPTION_STATISTICS_NAME) + .with("period", "everyChunk"); // Emits events at the beginning and end of the recording + r.start(); + for (int i = 0; i < THROWN_EXCEPTIONS; i++) { + try { + throw new MyError(message); + } catch (MyError e) { + } + try { + throw new MyCheckedException(message); + } catch (MyCheckedException e) { + } + } + r.stop(); + List events = Events.fromRecording(r); + checkEvents(events, ERROR_EVENT_NAME, message, THROWN_EXCEPTIONS, MyError.class); + checkEvents(events, EXCEPTION_EVENT_NAME, message, 0, MyError.class); + checkCount(events, 2 * THROWN_EXCEPTIONS); } - @SuppressWarnings("serial") - class TestException extends Exception { + } + + private static void testErrorAndException() throws Exception { + String message1 = "message-1"; + String message2 = "message-2"; + try (Recording r = new Recording()) { + r.enable(EXCEPTION_EVENT_NAME).withStackTrace(); + r.enable(ERROR_EVENT_NAME).withStackTrace(); + r.enable(EXCEPTION_STATISTICS_NAME) + .with("period", "everyChunk"); // Emits events at the beginning and end of the recording + r.start(); + for (int i = 0; i < THROWN_EXCEPTIONS; i++) { + try { + throw new MyCheckedException(message1); + } catch (MyCheckedException e) { + } + try { + throw new MyError(message2); + } catch (MyError e) { + } + } + r.stop(); + List events = Events.fromRecording(r); + checkEvents(events, EXCEPTION_EVENT_NAME, message1, THROWN_EXCEPTIONS, MyCheckedException.class); + checkEvents(events, EXCEPTION_EVENT_NAME, message2, THROWN_EXCEPTIONS, MyError.class); + checkEvents(events, ERROR_EVENT_NAME, message1, 0, MyError.class); + checkEvents(events, ERROR_EVENT_NAME, message2, THROWN_EXCEPTIONS, MyError.class); + checkCount(events, 2 * THROWN_EXCEPTIONS); } + } + private static void testThrowableConstructors() throws Exception { + Exception cause = new Exception("cause-message"); try (Recording r = new Recording()) { - r.enable(EventNames.JavaErrorThrow).withStackTrace(); - r.enable(EventNames.JavaExceptionThrow).withStackTrace(); + r.enable(EXCEPTION_EVENT_NAME).withStackTrace(); + r.enable(ERROR_EVENT_NAME).withStackTrace(); r.start(); try { - throw new TestError(); - } catch (Error e) { - System.out.println(e.getClass() + " thrown!"); + throw new Throwable(); + } catch (Throwable e) { + } + try { + throw new Throwable("throwable-message"); + } catch (Throwable e) { } try { - throw new TestException(); - } catch (Exception e) { - System.out.println(e.getClass() + " thrown!"); + throw new Throwable(cause); + } catch (Throwable e) { } try { - throw new Exception(); - } catch (Exception e) { - System.out.println(e.getClass() + " thrown!"); + throw new Throwable("throwable-message-and-cause", cause); + } catch (Throwable e) { + } + try { + throw new MyThrowable("my-throwable-message", cause, true, true); + } catch (MyThrowable e) { } r.stop(); List events = Events.fromRecording(r); - Events.hasEvents(events); - for (RecordedEvent e : events) { - RecordedStackTrace rs = e.getStackTrace(); - RecordedClass rc = e.getValue("thrownClass"); - List frames = rs.getFrames(); - RecordedFrame topFrame = frames.getFirst(); - System.out.println(rc.getName() + " Top frame: " + topFrame.getMethod().getName()); - if (!topFrame.getMethod().getName().equals("")) { - throw new Exception("Expected name of top frame to be "); - } - } + // new Throwable() + checkEvents(events, EXCEPTION_EVENT_NAME, null, 1, Throwable.class); + // new Throwable("throwable-message"); + checkEvents(events, EXCEPTION_EVENT_NAME, "throwable-message", 1, Throwable.class); + // new Throwable(cause) + checkEvents(events, EXCEPTION_EVENT_NAME, cause.toString(), 1, Throwable.class); + // new Throwable("throwable-message-and-cause", cause); + checkEvents(events, EXCEPTION_EVENT_NAME, "throwable-message-and-cause", 1, Throwable.class); + // new MyThrowable("my-throwable-message", cause, true, true); + checkEvents(events, EXCEPTION_EVENT_NAME, "my-throwable-message", 1, MyThrowable.class); } } - private static Recording createRecording() throws Exception { - Recording recording = new Recording(); - recording.enable(EXCEPTION_STATISTICS_PATH); - recording.enable(EXCEPTION_EVENT_PATH).withThreshold(Duration.ofMillis(0)); - recording.enable(ERROR_EVENT_PATH).withThreshold(Duration.ofMillis(0)); - recording.start(); - - for (int i = 0; i < ITERATIONS; i++) { + private static void testErrorConstructors() throws Exception { + Exception cause = new Exception("cause-message"); + try (Recording r = new Recording()) { + r.enable(EXCEPTION_EVENT_NAME).withStackTrace(); + r.enable(ERROR_EVENT_NAME).withStackTrace(); + r.start(); try { - throw new MyException(EXCEPTION_MESSAGE); - } catch (MyException e) { - exceptionCount++; + throw new Error(); + } catch (Error e) { } try { - throw new MyError(ERROR_MESSAGE); - } catch (MyError e) { - exceptionCount++; + throw new Error("error-message"); + } catch (Error e) { + } + try { + throw new Error(cause); + } catch (Error e) { + } + try { + throw new Error("error-message-and-cause", cause); + } catch (Error e) { } try { - throw new MyThrowable(THROWABLE_MESSAGE); - } catch (MyThrowable t) { - exceptionCount++; + throw new MyError("my-error-message", cause, true, true); + } catch (MyError e) { } + r.stop(); + List events = Events.fromRecording(r); + // new Error() + checkErrorEvents(events, null, Error.class); + // new Error("error-message"); + checkErrorEvents(events, "error-message", Error.class); + // new Error(cause) + checkErrorEvents(events, cause.toString(), Error.class); + // new Error("error-message-and-cause", cause); + checkErrorEvents(events, "error-message-and-cause", Error.class); + // new MyError("my-error-message", cause, true, true); + checkErrorEvents(events, "my-error-message", MyError.class); } - recording.stop(); - return recording; } + private static void checkErrorEvents(List events, String expectedMessage, Class expectedClass) throws Exception { + checkEvents(events, EXCEPTION_EVENT_NAME, expectedMessage, 1, expectedClass); + checkEvents(events, ERROR_EVENT_NAME, expectedMessage, 1, expectedClass); + } - private static void checkStatisticsEvent(List events, long minCount) throws Exception { - // Events are not guaranteed to be in chronological order, take highest value. - long count = -1; - for(RecordedEvent event : events) { - if (Events.isEventType(event, EXCEPTION_STATISTICS_PATH)) { - System.out.println("Event: " + event); - count = Math.max(count, Events.assertField(event, "throwables").getValue()); - System.out.println("count=" + count); + private static void testThrottling() throws Exception { + int thrown = 5000; + String message = "testThrottling"; + try (Recording r = new Recording()) { + r.enable(EXCEPTION_EVENT_NAME).withStackTrace().with("throttle", (thrown / 10) + "/s"); + r.enable(EXCEPTION_STATISTICS_NAME) + .with("period", "everyChunk"); // Emits events at the beginning and end of the recording + r.start(); + for (int i = 0; i < thrown; i++) { + try { + throw new MyCheckedException(message); + } catch (Exception e) { + } + } + r.stop(); + List events = Events.fromRecording(r); + long sampled = 0; + for (RecordedEvent event : ofType(events, EXCEPTION_EVENT_NAME)) { + if (message.equals(event.getString("message"))) { + sampled++; + } + } + if (sampled >= thrown) { + throw new Exception("No exception events were throttled"); + } + if (sampled < 2) { + throw new Exception("Expected at least two events to be sampled"); } } - Asserts.assertTrue(count != -1, "No events of type " + EXCEPTION_STATISTICS_PATH); - Asserts.assertGreaterThanOrEqual(count, minCount, "Too few exception count in statistics event"); } - private static void checkThrowableEvents(List events, String eventName, - int excpectedEvents, Class expectedClass, String expectedMessage) throws Exception { - int count = 0; - for(RecordedEvent event : events) { - if (Events.isEventType(event, eventName)) { - String message = Events.assertField(event, "message").getValue(); - if (expectedMessage.equals(message)) { - RecordedThread t = event.getThread(); - String threadName = t.getJavaName(); - if (threadName != null && threadName.equals(Thread.currentThread().getName())) { - RecordedClass jc = event.getValue("thrownClass"); - if (jc.getName().equals(expectedClass.getName())) { - count++; - } + private static void testException(Class type, String message) throws Exception { + int count = 5000; + try (Recording r = new Recording()) { + r.enable(EXCEPTION_EVENT_NAME).withStackTrace(); + r.enable(EXCEPTION_STATISTICS_NAME).with("period", "everyChunk"); + r.start(); + for (int i = 0; i < count; i++) { + if (type == MyCheckedException.class) { + try { + throw new MyCheckedException(message); + } catch (MyCheckedException e) { } } + if (type == MyRuntimeException.class) { + try { + throw new MyRuntimeException(message); + } catch (MyRuntimeException e) { + } + } + if (type == MyThrowable.class) { + try { + throw new MyThrowable(message); + } catch (MyThrowable e) { + } + } + } + r.stop(); + List events = Events.fromRecording(r); + checkEvents(events, EXCEPTION_EVENT_NAME, message, count, type); + checkEvents(events, ERROR_EVENT_NAME, message, 0, type); + checkCount(events, count); + } + } + + private static List ofType(List events, String eventType) { + List result = new ArrayList<>(); + for (RecordedEvent event : events) { + if (Events.isEventType(event, eventType)) { + result.add(event); } } - Asserts.assertEquals(count, excpectedEvents, "Wrong event count for type " + eventName); + return result; } - private static class MyException extends Exception { - private static final long serialVersionUID = -2614309279743448910L; - public MyException(String msg) { - super(msg); + private static void checkCount(List events, long expectedCount) throws Exception { + events.sort(Comparator.comparing(RecordedEvent::getEndTime)); + List statisticsEvents = ofType(events, EXCEPTION_STATISTICS_NAME); + if (statisticsEvents.size() != 2) { + throw new Exception("Expected two ExceptionStatistics events"); + } + RecordedEvent begin = statisticsEvents.get(0); + RecordedEvent end = statisticsEvents.get(1); + long count = end.getLong("throwables") - begin.getLong("throwables"); + Asserts.assertGreaterThanOrEqual(count, expectedCount, "Too few exceptions counted in statistics event"); + Asserts.assertLessThan(count, expectedCount + NOISE_EXCEPTIONS, "Too many exceptions counted in statistics event"); + } + + private static void checkEvents(List events, String eventType, String expectedMessage, int expectedCount, Class expectedClass) throws Exception { + int count = 0; + for (RecordedEvent event : ofType(events, eventType)) { + String message = Events.assertField(event, "message").getValue(); + if (Objects.equals(expectedMessage, message)) { + if (message == null && !isThrownFromTestClass(event)) { + continue; + } + RecordedThread t = event.getThread(); + if (!t.getJavaName().equals(THREAD_NAME)) { + System.out.println(event); + throw new Exception("Incorrect thread name, expected: " + THREAD_NAME); + } + String className = event.getClass("thrownClass").getName(); + if (!className.equals(expectedClass.getName())) { + throw new Exception("Incorrect exception class name, expected: " + expectedClass.getName()); + } + RecordedFrame topFrame = event.getStackTrace().getFrames().get(0); + if (!topFrame.getMethod().getName().equals("")) { + System.out.println(event); + throw new Exception("Expected name of top frame to be "); + } + count++; + } + } + if (count != expectedCount) { + throw new Exception("Expected " + expectedCount + " events, but found " + count + " with the message: " + expectedMessage); + } + } + + private static boolean isThrownFromTestClass(RecordedEvent event) { + for (RecordedFrame f : event.getStackTrace().getFrames()) { + if (f.isJavaFrame()) { + if (f.getMethod().getType().getName().equals(TestExceptionEvents.class.getName())) { + return true; + } + } + } + return false; + } + + private static class MyRuntimeException extends RuntimeException { + public MyRuntimeException(String message) { + super(message); + } + } + + private static class MyCheckedException extends Exception { + public MyCheckedException(String message) { + super(message); } } private static class MyError extends Error { - private static final long serialVersionUID = -8519872786387358196L; - public MyError(String msg) { - super(msg); + public MyError(String message) { + super(message); + } + + public MyError(String message, Exception cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); } } private static class MyThrowable extends Throwable { - private static final long serialVersionUID = -7929442863511070361L; - public MyThrowable(String msg) { - super(msg); + public MyThrowable(String message) { + super(message); + } + + public MyThrowable(String message, Exception cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); } } } diff --git a/test/jdk/sun/net/www/protocol/http/NTLMHeadTest.java b/test/jdk/sun/net/www/protocol/http/NTLMHeadTest.java index 2cbbf5f65342..40728a2b25ac 100644 --- a/test/jdk/sun/net/www/protocol/http/NTLMHeadTest.java +++ b/test/jdk/sun/net/www/protocol/http/NTLMHeadTest.java @@ -82,7 +82,9 @@ enum Mode { SERVER, PROXY, TUNNEL } static final String RESP_SERVER_NTLM = "HTTP/1.1 401 Unauthorized\r\n" + - "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n" + + "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAE" + + "AAgBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n" + "Connection: Keep-Alive\r\n" + "Content-Length: " + BODY_LEN + "\r\n" + "\r\n"; @@ -103,7 +105,9 @@ enum Mode { SERVER, PROXY, TUNNEL } static final String RESP_PROXY_NTLM = "HTTP/1.1 407 Proxy Authentication Required\r\n" + - "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n" + + "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAEAA" + + "gBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n" + "Proxy-Connection: Keep-Alive\r\n" + "Connection: Keep-Alive\r\n" + "Content-Length: " + BODY_LEN + "\r\n" + @@ -120,7 +124,9 @@ enum Mode { SERVER, PROXY, TUNNEL } static final String RESP_TUNNEL_NTLM = "HTTP/1.1 407 Proxy Authentication Required\r\n" + - "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n" + + "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAEAA" + + "gBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n" + "Proxy-Connection: Keep-Alive\r\n" + "Connection: Keep-Alive\r\n" + "Content-Length: " + BODY_LEN + "\r\n" + diff --git a/test/jdk/sun/net/www/protocol/http/NTLMTest.java b/test/jdk/sun/net/www/protocol/http/NTLMTest.java index c77c9854f5fa..34e6ec5c3b2b 100644 --- a/test/jdk/sun/net/www/protocol/http/NTLMTest.java +++ b/test/jdk/sun/net/www/protocol/http/NTLMTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,7 +90,9 @@ static void runClient(Proxy proxy, int serverPort) { "HTTP/1.1 401 Unauthorized\r\n" + "Content-Length: 0\r\n" + - "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n\r\n"}; + "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAE" + + "AAgBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n\r\n"}; static String[] proxyResp = new String[] { "HTTP/1.1 407 Proxy Authentication Required\r\n" + @@ -99,7 +101,9 @@ static void runClient(Proxy proxy, int serverPort) { "HTTP/1.1 407 Proxy Authentication Required\r\n" + "Content-Length: 0\r\n" + - "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n\r\n"}; + "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAEAA" + + "gBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n\r\n"}; static class NTLMServer extends Thread implements AutoCloseable { final ServerSocket ss; diff --git a/test/jdk/sun/net/www/protocol/http/TestTransparentNTLM.java b/test/jdk/sun/net/www/protocol/http/TestTransparentNTLM.java index 7a8082a40129..aa44ae9f0a02 100644 --- a/test/jdk/sun/net/www/protocol/http/TestTransparentNTLM.java +++ b/test/jdk/sun/net/www/protocol/http/TestTransparentNTLM.java @@ -116,7 +116,9 @@ int port() { static final String AUTH_STAGE_TWO = "HTTP/1.1 401 Unauthorized\r\n" + "Content-Length: 0\r\n" + - "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==\r\n\r\n"; + "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADgAAAAVgoriXva3" + + "eirBoiYAAAAAAAAAACgAKAA6AAAACgD0ZQAAAA9EAAIAAgBEAAE" + + "AAgBEAAQAAgBkAAMAAgBkAAcACAAAAAAAAAAAAAAAAAA=\r\n\r\n"; static final String AUTH_SUCCESSFUL = "HTTP/1.1 200 OK\r\n" + diff --git a/test/jdk/sun/security/krb5/auto/KDC.java b/test/jdk/sun/security/krb5/auto/KDC.java index 168a84722c7e..1cc774c4a41c 100644 --- a/test/jdk/sun/security/krb5/auto/KDC.java +++ b/test/jdk/sun/security/krb5/auto/KDC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1030,6 +1030,9 @@ protected byte[] processTgsReq(byte[] in) throws Exception { body.addresses != null ? body.addresses : etp.caddr, null); + + enc = modifyEncTicketPart(1, enc); + EncryptionKey skey = keyForUser(service, e3, true); if (skey == null) { throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO @@ -1090,6 +1093,12 @@ protected byte[] processTgsReq(byte[] in) throws Exception { } } + // Overridable by subclass to modify a ticket before encryption. + // type is 0 for AS-REQ and 1 for TGS-REQ. + protected EncTicketPart modifyEncTicketPart(int type, EncTicketPart enc) { + return enc; + } + /** * Processes a AS_REQ and generates a AS_REP (or KRB_ERROR) * @param in the request @@ -1375,6 +1384,9 @@ protected byte[] processAsReq(byte[] in) throws Exception { till, rtime, body.addresses, null); + + enc = modifyEncTicketPart(0, enc); + Ticket t = new Ticket( service, new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET) diff --git a/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttrEncoding.java b/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttrEncoding.java index 9f3d72f89837..2f3107622c82 100644 --- a/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttrEncoding.java +++ b/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttrEncoding.java @@ -36,8 +36,9 @@ import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.Enumeration; -import java.util.GregorianCalendar; import java.util.HashMap; import sun.security.pkcs.PKCS9Attribute; import sun.security.pkcs10.PKCS10; @@ -63,7 +64,8 @@ public static void main(String[] args) throws Exception { int len = ids.length; Object[] values = { ObjectIdentifier.of("1.2.3.4"), - new GregorianCalendar(1970, 1, 25, 8, 56, 7).getTime(), + LocalDateTime.of(1970, 2, 25, 8, 56, 7) + .toInstant(ZoneOffset.UTC), "challenging" }; for (int j = 0; j < len; j++) { diff --git a/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttributeReader.java b/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttributeReader.java index c4f8c9d0d4b1..df60c1518b8b 100644 --- a/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttributeReader.java +++ b/test/jdk/sun/security/pkcs/pkcs10/PKCS10AttributeReader.java @@ -32,10 +32,10 @@ * @compile -XDignore.symbol.file PKCS10AttributeReader.java * @run main PKCS10AttributeReader */ +import java.time.Instant; import java.util.Base64; import java.util.Enumeration; import java.util.HashMap; -import java.util.Date; import sun.security.pkcs.PKCS9Attribute; import sun.security.pkcs10.PKCS10Attribute; import sun.security.pkcs10.PKCS10Attributes; @@ -84,7 +84,8 @@ public static void main(String[] args) throws Exception { HashMap RequestStander = new HashMap() { { put(PKCS9Attribute.CHALLENGE_PASSWORD_OID, "GuessWhoAmI"); - put(PKCS9Attribute.SIGNING_TIME_OID, new Date(861720610000L)); + put(PKCS9Attribute.SIGNING_TIME_OID, + Instant.ofEpochMilli(861720610000L)); put(PKCS9Attribute.CONTENT_TYPE_OID, ObjectIdentifier.of("1.9.50.51.52")); } diff --git a/test/jdk/sun/security/pkcs/pkcs7/SignerOrder.java b/test/jdk/sun/security/pkcs/pkcs7/SignerOrder.java index 7d8333e6aa54..ac4e2cfbc675 100644 --- a/test/jdk/sun/security/pkcs/pkcs7/SignerOrder.java +++ b/test/jdk/sun/security/pkcs/pkcs7/SignerOrder.java @@ -40,7 +40,7 @@ import java.security.Signature; import java.security.SignatureException; import java.security.cert.X509Certificate; -import java.util.Date; +import java.time.Instant; import sun.security.pkcs.ContentInfo; import sun.security.pkcs.PKCS7; import sun.security.pkcs.SignerInfo; @@ -241,11 +241,10 @@ public X509Certificate getCert() { private X509Certificate getSelfCert() throws Exception { long validity = 1000; X509CertImpl certLocal; - Date firstDate, lastDate; + Instant firstDate, lastDate; - firstDate = new Date(); - lastDate = new Date(); - lastDate.setTime(lastDate.getTime() + validity + 1000); + firstDate = Instant.now(); + lastDate = firstDate.plusMillis(validity).plusMillis(1000); CertificateValidity interval = new CertificateValidity(firstDate, lastDate); @@ -254,7 +253,7 @@ private X509Certificate getSelfCert() throws Exception { // Add all mandatory attributes info.setVersion(new CertificateVersion(CertificateVersion.V1)); info.setSerialNumber(new CertificateSerialNumber( - (int) (firstDate.getTime() / 1000))); + (int) (firstDate.toEpochMilli() / 1000))); info.setAlgorithmId(new CertificateAlgorithmId(algId)); info.setSubject(agent); info.setKey(new CertificateX509Key(publicKey)); diff --git a/test/jdk/sun/security/pkcs/pkcs9/EncodeDecode.java b/test/jdk/sun/security/pkcs/pkcs9/EncodeDecode.java index 9ac5b3641992..2b2f9b6c8485 100644 --- a/test/jdk/sun/security/pkcs/pkcs9/EncodeDecode.java +++ b/test/jdk/sun/security/pkcs/pkcs9/EncodeDecode.java @@ -41,6 +41,7 @@ import sun.security.x509.X500Name; import java.math.BigInteger; +import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.HexFormat; @@ -57,7 +58,7 @@ public static void main(String[] args) throws Exception { "301806092a864886f70d010903310b06092a864886f70d010903"); test(MESSAGE_DIGEST_OID, new byte[10], "301906092a864886f70d010904310c040a00000000000000000000"); - test(SIGNING_TIME_OID, new Date(0), + test(SIGNING_TIME_OID, Instant.ofEpochMilli(0), "301c06092a864886f70d010905310f170d3730303130313030303030305a"); var sis = new SignerInfo[] { diff --git a/test/jdk/sun/security/pkcs11/rsa/GenKeyStore.java b/test/jdk/sun/security/pkcs11/rsa/GenKeyStore.java index 26178e9a576a..312e4d858341 100644 --- a/test/jdk/sun/security/pkcs11/rsa/GenKeyStore.java +++ b/test/jdk/sun/security/pkcs11/rsa/GenKeyStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.io.*; import java.math.BigInteger; +import java.time.Instant; import java.util.*; import java.security.*; @@ -46,7 +47,7 @@ public class GenKeyStore { private static X509Certificate getCertificate(String suffix, PublicKey publicKey, PrivateKey privateKey) throws Exception { X500Name name = new X500Name("CN=Dummy Certificate " + suffix); String algorithm = "SHA1with" + publicKey.getAlgorithm(); - Date date = new Date(); + Instant instant = Instant.now(); AlgorithmId algID = AlgorithmId.getAlgorithmId(algorithm); X509CertInfo certInfo = new X509CertInfo(); @@ -57,7 +58,7 @@ private static X509Certificate getCertificate(String suffix, PublicKey publicKey certInfo.set(X509CertInfo.SUBJECT, name); certInfo.set(X509CertInfo.ISSUER, name); certInfo.set(X509CertInfo.KEY, new CertificateX509Key(publicKey)); - certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(date, date)); + certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(instant, instant)); X509CertImpl cert = new X509CertImpl(certInfo); cert.sign(privateKey, algorithm); diff --git a/test/jdk/sun/security/pkcs12/EmptyAttributeSet.java b/test/jdk/sun/security/pkcs12/EmptyAttributeSet.java new file mode 100644 index 000000000000..aecff0a4238b --- /dev/null +++ b/test/jdk/sun/security/pkcs12/EmptyAttributeSet.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8397199 + * @summary Reject empty PKCS12 friendlyName and localKeyId value sets + * @library /test/lib + * @run main EmptyAttributeSet + */ + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.KeyStore; +import java.util.Base64; + +import jdk.test.lib.Asserts; + +public class EmptyAttributeSet { + private static void check(String encoded, String oid) throws Exception { + byte[] data = Base64.getDecoder().decode(encoded); + KeyStore store = KeyStore.getInstance("PKCS12"); + + IOException e = Asserts.assertThrows(IOException.class, + () -> store.load(new ByteArrayInputStream(data), null)); + + String message = e.getMessage(); + Asserts.assertNotNull(message); + Asserts.assertTrue(message.contains(oid), + "Missing OID in exception message: " + message); + Asserts.assertTrue(message.contains("Empty attribute value set"), + "Unexpected exception message: " + message); + } + + public static void main(String[] args) throws Exception { + // Empty friendlyName attribute value set. + check("MEUCAQMwQAYJKoZIhvcNAQcBoDMEMTAvMC0GCSqGSIb3DQEHAaAgBB4wHDAa" + + "BgMqAwSgAgUAMQ8wDQYJKoZIhvcNAQkUMQA=", + "1.2.840.113549.1.9.20"); + + // Empty localKeyId attribute value set. + check("MEUCAQMwQAYJKoZIhvcNAQcBoDMEMTAvMC0GCSqGSIb3DQEHAaAgBB4wHDAa" + + "BgMqAwSgAgUAMQ8wDQYJKoZIhvcNAQkVMQA=", + "1.2.840.113549.1.9.21"); + } +} diff --git a/test/jdk/sun/security/provider/KeyStore/DKSSystemPropertiesTest.java b/test/jdk/sun/security/provider/KeyStore/DKSSystemPropertiesTest.java new file mode 100644 index 000000000000..4b658e181ab3 --- /dev/null +++ b/test/jdk/sun/security/provider/KeyStore/DKSSystemPropertiesTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8007755 8374808 + * @library /test/lib + * @summary Support the logical grouping of keystores + */ + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; +import java.net.URI; +import java.nio.file.Paths; +import java.security.DomainLoadStoreParameter; +import java.security.KeyStore; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +// Load and store entries in domain keystores + +public class DKSSystemPropertiesTest { + + private static final String TEST_SRC = System.getProperty("test.src"); + private static final String USER_DIR = System.getProperty("user.dir", "."); + private static final String CONFIG = Paths.get( + TEST_SRC, "domains.cfg").toUri().toString(); + + public static void main(String[] args) throws Exception { + if (args.length == 0) { + // Environment variable and system properties referred in domains.cfg used by this Test. + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + List.of("-Dtest.src=" + TEST_SRC, "-Duser.dir=" + USER_DIR, + "DKSSystemPropertiesTest", "run")); + pb.environment().putAll(System.getenv()); + pb.environment().put("KEYSTORE_PWD", "test12"); + pb.environment().put("TRUSTSTORE_PWD", "changeit"); + OutputAnalyzer output = ProcessTools.executeProcess(pb); + output.shouldHaveExitValue(0); + output.outputTo(System.out); + return; + } + + /* + * domain keystore: system_env + */ + URI config = new URI(CONFIG + "#system_env"); + KeyStore keystore = KeyStore.getInstance("DKS"); + // load entries + keystore.load( + new DomainLoadStoreParameter(config, + Collections.emptyMap())); + + int expected = keystore.size(); + + System.out.println("\nLoading domain keystore: " + config + "\t[" + + expected + " entries]"); + checkEntries(keystore, expected); + } + + static void checkEntries(KeyStore keystore, int expectedCount) + throws Exception { + int currCount = 0; + for (String alias : Collections.list(keystore.aliases())) { + System.out.print("."); + currCount++; + + // check creation date and instant + Date keystoreCreation = + Date.from(keystore.getCreationInstant(alias)); + if (!keystore.getCreationDate(alias).equals(keystoreCreation)) { + throw new RuntimeException( + "Creation Date is not the same as Instant timestamp"); + } + } + System.out.println(); + // Check if current count is expected + if (expectedCount != currCount) { + throw new RuntimeException("Error: unexpected entry count in " + + "keystore: loaded=" + currCount + ", " + + "expected=" + expectedCount); + } + } + +} diff --git a/test/jdk/sun/security/provider/KeyStore/DKSTest.java b/test/jdk/sun/security/provider/KeyStore/DKSTest.java index ee655f5a2a6e..c69039f19247 100644 --- a/test/jdk/sun/security/provider/KeyStore/DKSTest.java +++ b/test/jdk/sun/security/provider/KeyStore/DKSTest.java @@ -26,6 +26,7 @@ * @bug 8007755 8374808 * @library /test/lib * @summary Support the logical grouping of keystores + * @run junit DKSTest */ import java.io.File; @@ -34,21 +35,32 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.security.DomainLoadStoreParameter; import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; import java.util.HashMap; -import java.util.List; +import java.util.LinkedHashMap; import java.util.Map; -import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.process.OutputAnalyzer; +import org.junit.jupiter.api.Test; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; // Load and store entries in domain keystores @@ -56,195 +68,360 @@ public class DKSTest { private static final String TEST_SRC = System.getProperty("test.src"); private static final String USER_DIR = System.getProperty("user.dir", "."); + private static final Path SCRATCH_FOLDER = Path.of("."); private static final String CERT = Paths.get( TEST_SRC, "..", "..", "pkcs12", "trusted.pem").toAbsolutePath().toString(); private static final String CONFIG = Paths.get( TEST_SRC, "domains.cfg").toUri().toString(); + private static final char[] KEYSTORE_PASSWORD = "test123".toCharArray(); private static final Map PASSWORDS = - new HashMap() {{ - put("keystore", - new KeyStore.PasswordProtection("test123".toCharArray())); - put("policy_keystore", + new HashMap<>() {{ + put("keystore", + new KeyStore.PasswordProtection(KEYSTORE_PASSWORD)); + put("policy_keystore", new KeyStore.PasswordProtection( - "Alias.password".toCharArray())); - put("pw_keystore", + "Alias.password".toCharArray())); + put("pw_keystore", new KeyStore.PasswordProtection("test12".toCharArray())); - put("eckeystore1", + put("eckeystore1", new KeyStore.PasswordProtection("password".toCharArray())); - put("truststore", + put("truststore", new KeyStore.PasswordProtection("changeit".toCharArray())); - put("empty", + put("empty", new KeyStore.PasswordProtection("passphrase".toCharArray())); - }}; + }}; private static final Map - WRONG_PASSWORDS = new HashMap() {{ - put("policy_keystore", + WRONG_PASSWORDS = new HashMap<>() {{ + put("policy_keystore", new KeyStore.PasswordProtection( - "wrong".toCharArray())); - put("pw_keystore", + "wrong".toCharArray())); + put("pw_keystore", new KeyStore.PasswordProtection("wrong".toCharArray())); - put("eckeystore1", + put("eckeystore1", new KeyStore.PasswordProtection("wrong".toCharArray())); - }}; - - public static void main(String[] args) throws Exception { - if (args.length == 0) { - // Environment variable and system properties referred in domains.cfg used by this Test. - ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(List.of( - "-Dtest.src=" + TEST_SRC , "-Duser.dir=" + USER_DIR, "DKSTest", "run")); - pb.environment().putAll(System.getenv()); - pb.environment().put("KEYSTORE_PWD", "test12"); - pb.environment().put("TRUSTSTORE_PWD", "changeit"); - OutputAnalyzer output = ProcessTools.executeProcess(pb); - output.shouldHaveExitValue(0); - output.outputTo(System.out); - return; - } - /* - * domain keystore: keystores with wrong passwords - */ - try { - URI config = new URI(CONFIG + "#keystores"); - KeyStore ks = KeyStore.getInstance("DKS"); - ks.load(new DomainLoadStoreParameter(config, WRONG_PASSWORDS)); - throw new RuntimeException("Expected exception not thrown"); - } catch (IOException e) { - System.out.println("Expected exception: " + e); - if (!causedBy(e, UnrecoverableKeyException.class)) { - e.printStackTrace(System.out); - throw new RuntimeException("Unexpected cause"); - } - System.out.println("Expected cause: " + e); - } + }}; - /* - * domain keystore: system - */ - URI config = new URI(CONFIG + "#system"); - int cacertsCount; - int expected; - KeyStore keystore = KeyStore.getInstance("DKS"); + /* + * domain keystore: keystores with wrong passwords + */ + @Test + public void wrongPasswordTest() throws Exception { + final URI config = new URI(CONFIG + "#keystores"); + final KeyStore ks = KeyStore.getInstance("DKS"); + + var e = assertThrows(IOException.class, + () -> ks.load(new DomainLoadStoreParameter( + config, WRONG_PASSWORDS))); + assertTrue(causedBy(e, UnrecoverableKeyException.class), + "Unexpected cause"); + System.out.println("Expected cause: " + e); + } + + /* + * domain keystore: system + */ + @Test + public void systemTest() throws Exception { + final URI config = new URI(CONFIG + "#system"); + final KeyStore keystore = KeyStore.getInstance("DKS"); // load entries keystore.load(new DomainLoadStoreParameter(config, PASSWORDS)); - cacertsCount = expected = keystore.size(); + final int expected = keystore.size(); System.out.println("\nLoading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); - - /* - * domain keystore: system_plus - */ - config = new URI(CONFIG + "#system_plus"); - expected = cacertsCount + 1; - keystore = KeyStore.getInstance("DKS"); + expected + " entries]"); + DKSSystemPropertiesTest.checkEntries(keystore, expected); + } + + /* + * domain keystore: system_plus + */ + @Test + public void systemPlusTest() throws Exception { + final URI config = new URI(CONFIG + "#system_plus"); + final KeyStore keystore = KeyStore.getInstance("DKS"); // load entries keystore.load(new DomainLoadStoreParameter(config, PASSWORDS)); + final int expected = keystore.size(); System.out.println("\nLoading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); - - /* - * domain keystore: system_env - */ - config = new URI(CONFIG + "#system_env"); - expected = 1 + cacertsCount; - keystore = KeyStore.getInstance("DKS"); - // load entries - keystore.load( - new DomainLoadStoreParameter(config, - Collections.emptyMap())); - System.out.println("\nLoading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); + expected + " entries]"); + DKSSystemPropertiesTest.checkEntries(keystore, expected); + } - /* - * domain keystore: empty - */ - KeyStore empty = KeyStore.getInstance("JKS"); + /* + * domain keystore: empty + */ + @Test + public void keystoreEmptyTest() throws Exception { + final KeyStore empty = KeyStore.getInstance("JKS"); empty.load(null, null); try (OutputStream outStream = - new FileOutputStream(new File(USER_DIR, "empty.jks"))) { + new FileOutputStream(new File(USER_DIR, "empty.jks"))) { empty.store(outStream, "passphrase".toCharArray()); } - config = new URI(CONFIG + "#empty"); - expected = 0; - keystore = KeyStore.getInstance("DKS"); + final URI config = new URI(CONFIG + "#empty"); + final KeyStore keystore = KeyStore.getInstance("DKS"); // load entries keystore.load(new DomainLoadStoreParameter(config, PASSWORDS)); - System.out.println("\nLoading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); - - /* - * domain keystore: keystores - */ - config = new URI(CONFIG + "#keystores"); - expected = 2 + 1 + 1; - keystore = KeyStore.getInstance("DKS"); + System.out.println("\nLoading domain keystore: " + config + + "\t[0 entries]"); + DKSSystemPropertiesTest.checkEntries(keystore, 0); + + } + + /* + * domain keystore: keystores + */ + @Test + public void multipleKeystoresTest() throws Exception { + + URI config = new URI(CONFIG + "#keystores"); + int expected = 4; + KeyStore keystore = KeyStore.getInstance("DKS"); // load entries keystore.load(new DomainLoadStoreParameter(config, PASSWORDS)); System.out.println("\nLoading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); + expected + " entries]"); + DKSSystemPropertiesTest.checkEntries(keystore, expected); // set a new trusted certificate entry Certificate cert = loadCertificate(CERT); String alias = "pw_keystore tmp-cert"; System.out.println("Setting new trusted certificate entry: " + alias); keystore.setEntry(alias, - new KeyStore.TrustedCertificateEntry(cert), null); + new KeyStore.TrustedCertificateEntry(cert), null); expected++; // store entries config = new URI(CONFIG + "#keystores_tmp"); System.out.println("Storing domain keystore: " + config + "\t[" + - expected + " entries]"); + expected + " entries]"); keystore.store(new DomainLoadStoreParameter(config, PASSWORDS)); keystore = KeyStore.getInstance("DKS"); // reload entries keystore.load(new DomainLoadStoreParameter(config, PASSWORDS)); System.out.println("Reloading domain keystore: " + config + "\t[" + - expected + " entries]"); - checkEntries(keystore, expected); + expected + " entries]"); + DKSSystemPropertiesTest.checkEntries(keystore, expected); // get the new trusted certificate entry System.out.println("Getting new trusted certificate entry: " + alias); - if (!keystore.isCertificateEntry(alias)) { - throw new Exception("Error: cannot retrieve certificate entry: " + - alias); - } + assertTrue(keystore.isCertificateEntry(alias), + "Error: cannot retrieve certificate entry: " + alias); + keystore.setEntry(alias, - new KeyStore.TrustedCertificateEntry(cert), null); + new KeyStore.TrustedCertificateEntry(cert), null); } - private static void checkEntries(KeyStore keystore, int expectedCount) - throws Exception { - int currCount = 0; - for (String alias : Collections.list(keystore.aliases())) { - System.out.print("."); - currCount++; - - // check creation date and instant - if(!keystore.getCreationDate(alias).equals( - Date.from(keystore.getCreationInstant(alias))) - ){ - throw new RuntimeException( - "Creation Date is not the same as Instant timestamp"); - } + @Test + public void getKeyTest() throws Exception { + + final SecretKey expected = generateSecretKey(); + final SecretKey expected2 = generateSecretKey(); + final KeyStore dks = generateKeystores(expected, expected2); + + SecretKey actual = + (SecretKey) dks.getKey("firstPkcs12 alias1", + KEYSTORE_PASSWORD); + assertNotNull(actual, "Key not found for 'firstPkcs12 alias1'"); + assertArrayEquals(expected.getEncoded(), actual.getEncoded(), + "Unexpected key for 'firstPkcs12 alias1'"); + + actual = (SecretKey) dks.getKey("alias2", KEYSTORE_PASSWORD); + assertNotNull(actual, "Key not found for 'alias2'"); + assertArrayEquals(expected2.getEncoded(), actual.getEncoded(), + "Unexpected key for 'alias2'"); + + assertNull(dks.getKey("missingAlias", KEYSTORE_PASSWORD), + "Unexpected key for 'missingAlias'"); + } + + @Test + public void containsAliasTest() throws Exception { + + final KeyStore dks = generateKeystores( + generateSecretKey(), + generateSecretKey()); + + assertTrue(dks.containsAlias("firstPkcs12 alias1"), + "'firstPkcs12 alias1' should be present"); + assertTrue(dks.containsAlias("alias2"), + "'alias2' should be present"); + assertFalse(dks.containsAlias("missingAlias"), + "'missingAlias' should not be present"); + assertFalse(dks.containsAlias("unknown alias2"), + "'unknown alias2' should not be present"); + } + + @Test + public void isKeyEntryTest() throws Exception { + + final KeyStore dks = generateKeystores( + generateSecretKey(), + generateSecretKey()); + + assertTrue(dks.isKeyEntry("firstPkcs12 alias1"), + "'firstPkcs12 alias1' should be a key entry"); + assertTrue(dks.isKeyEntry("alias2"), + "'alias2' should be a key entry"); + assertFalse(dks.isKeyEntry("missingAlias"), + "'missingAlias' should not be a key entry"); + assertFalse(dks.isKeyEntry("unknown alias2"), + "'unknown alias2' should not be a key entry"); + } + + @Test + public void isCertificateEntryTest() throws Exception { + + final KeyStore dks = generateKeyStoreFromPKCS12(generateSecretKey(), + loadCertificate(CERT)); + + assertTrue(dks.isCertificateEntry("firstPkcs12 alias1"), + "'firstPkcs12 alias1' should be a certificate entry"); + assertFalse(dks.isCertificateEntry("missingAlias"), + "'missingAlias' should not be a certificate entry"); + assertFalse(dks.isCertificateEntry("unknown alias2"), + "'unknown alias2' should not be a certificate entry"); + } + + @Test + public void getCertificateAliasEntryTest() throws Exception { + + final Certificate certificate = loadCertificate(CERT); + final KeyStore dks = generateKeyStoreFromPKCS12(generateSecretKey(), + certificate); + + assertEquals("alias1", dks.getCertificateAlias(certificate)); + } + + @Test + public void getCertificateTest() throws Exception { + + final Certificate certificate = loadCertificate(CERT); + final KeyStore dks = generateKeyStoreFromPKCS12(generateSecretKey(), + certificate); + + assertEquals(certificate, dks.getCertificate("alias1")); + } + + private KeyStore generateKeystores(final SecretKey secretKey, + final SecretKey secretKey2) + throws Exception { + + final Path firstPkcs12 = + generatePKCS12("firstPkcs12.p12", "alias1", + KEYSTORE_PASSWORD, secretKey); + final Path secondPkcs12 = + generatePKCS12("secondPkcs12.p12", "alias2", + KEYSTORE_PASSWORD, secretKey2); + final Path thirdPkcs12 = + generatePKCS12("thirdPkcs12.p12", null, + null, null); + + final Map protectionParameters = + new LinkedHashMap<>(); + protectionParameters.put("firstPkcs12", + new KeyStore.PasswordProtection(KEYSTORE_PASSWORD)); + protectionParameters.put("secondPkcs12", + new KeyStore.PasswordProtection(KEYSTORE_PASSWORD)); + + + final KeyStore dks = KeyStore.getInstance("DKS"); + final Path config = createDomainConfig(Map.of( + "firstPkcs12", firstPkcs12, + "secondPkcs12", secondPkcs12, + "thirdPkcs12", thirdPkcs12)); + dks.load(new DomainLoadStoreParameter(config.toUri(), + protectionParameters)); + + return dks; + } + + private KeyStore generateKeyStoreFromPKCS12(final SecretKey secretKey, + final Certificate certificate) throws Exception { + + // keystore with cert + final KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, null); + keystore.setEntry("alias1", + new KeyStore.TrustedCertificateEntry(certificate), null); + final Path firstPkcs12 = SCRATCH_FOLDER.resolve("firstPkcs12.p12"); + try (OutputStream output = Files.newOutputStream(firstPkcs12)) { + keystore.store(output, KEYSTORE_PASSWORD); } - System.out.println(); - // Check if current count is expected - if (expectedCount != currCount) { - throw new Exception("Error: unexpected entry count in keystore: " + - "loaded=" + currCount + ", expected=" + expectedCount); + + final Path secondPkcs12 = + generatePKCS12("secondPkcs12.p12", "alias2", + KEYSTORE_PASSWORD, secretKey); + final Path thirdPkcs12 = + generatePKCS12("thirdPkcs12.p12", null, + null, null); + + final Map protectionParameters = + new LinkedHashMap<>(); + protectionParameters.put("firstPkcs12", + new KeyStore.PasswordProtection(KEYSTORE_PASSWORD)); + protectionParameters.put("secondPkcs12", + new KeyStore.PasswordProtection(KEYSTORE_PASSWORD)); + + + final KeyStore dks = KeyStore.getInstance("DKS"); + final Path config = createDomainConfig(Map.of( + "firstPkcs12", firstPkcs12, + "secondPkcs12", secondPkcs12, + "thirdPkcs12", thirdPkcs12)); + dks.load(new DomainLoadStoreParameter(config.toUri(), + protectionParameters)); + + return dks; + } + + private SecretKey generateSecretKey() throws NoSuchAlgorithmException { + final KeyGenerator generator = KeyGenerator.getInstance("AES"); + generator.init(128); + return generator.generateKey(); + } + + private Path createDomainConfig(Map parts) throws Exception { + final StringBuilder config = new StringBuilder(); + config.append("domain TestDomain keystoreType=\"PKCS12\" {\n"); + for (final Map.Entry entry : parts.entrySet()) { + config.append(" keystore ") + .append(entry.getKey()) + .append(" keystoreURI=\"") + .append(entry.getValue().toUri()) + .append("\";\n"); + } + config.append("};\n"); + + Path path = SCRATCH_FOLDER.resolve("domain.cfg"); + Files.writeString(path, config.toString()); + return path; + } + + private Path generatePKCS12(final String fileName, + final String alias, + final char[] entryPassword, + final SecretKey secretKey) throws Exception { + final KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, null); + + if (alias != null) { + keystore.setEntry(alias, new KeyStore.SecretKeyEntry(secretKey), + new KeyStore.PasswordProtection(entryPassword)); + } + + final Path path = SCRATCH_FOLDER.resolve(fileName); + try (OutputStream output = Files.newOutputStream(path)) { + keystore.store(output, KEYSTORE_PASSWORD); } + return path; } private static Certificate loadCertificate(String certFile) - throws Exception { + throws Exception { X509Certificate cert = null; try (FileInputStream certStream = new FileInputStream(certFile)) { CertificateFactory factory = - CertificateFactory.getInstance("X.509"); + CertificateFactory.getInstance("X.509"); return factory.generateCertificate(certStream); } } diff --git a/test/jdk/sun/security/provider/all/Deterministic.java b/test/jdk/sun/security/provider/all/Deterministic.java index 60c56cd1b93d..eddf4a4bec63 100644 --- a/test/jdk/sun/security/provider/all/Deterministic.java +++ b/test/jdk/sun/security/provider/all/Deterministic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 8325506 + * @bug 8325506 8385968 * @library /test/lib * @modules java.base/sun.security.util * @run main/othervm Deterministic @@ -206,16 +206,19 @@ static void testKeyPairGenerator(Provider.Service s) throws Exception { static KeyPair generateKeyPair(String alg, int offset) throws Exception { var g = KeyPairGenerator.getInstance(alg); + var random = new SeededSecureRandom(SEED + offset); var size = switch (g.getAlgorithm()) { case "RSA", "RSASSA-PSS", "DSA", "DiffieHellman" -> 1024; case "EC" -> 256; case "EdDSA", "Ed25519", "XDH", "X25519" -> 255; case "Ed448", "X448" -> 448; case "ML-KEM", "ML-KEM-768", "ML-KEM-512", "ML-KEM-1024", - "ML-DSA", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87" -> -1; + "ML-DSA", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87", + "X25519MLKEM768", "SecP256r1MLKEM768", + "SecP384r1MLKEM1024" -> -1; default -> throw new UnsupportedOperationException(alg); }; - g.initialize(size, new SeededSecureRandom(SEED + offset)); + g.initialize(size, random); return g.generateKeyPair(); } diff --git a/test/jdk/sun/security/rsa/GenKeyStore.java b/test/jdk/sun/security/rsa/GenKeyStore.java index 8b0016e77af5..5653604634bb 100644 --- a/test/jdk/sun/security/rsa/GenKeyStore.java +++ b/test/jdk/sun/security/rsa/GenKeyStore.java @@ -31,16 +31,23 @@ // @author Andreas Sterbenz -import java.io.*; -import java.math.BigInteger; -import java.util.*; - -import java.security.*; -import java.security.cert.*; -import java.security.interfaces.*; -import java.security.spec.*; - -import sun.security.x509.*; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.io.FileOutputStream; +import java.io.OutputStream; + +import sun.security.x509.CertificateSerialNumber; +import sun.security.x509.CertificateValidity; +import sun.security.x509.CertificateVersion; +import sun.security.x509.CertificateX509Key; +import sun.security.x509.X500Name; +import sun.security.x509.X509CertImpl; +import sun.security.x509.X509CertInfo; public class GenKeyStore { @@ -51,7 +58,7 @@ private static X509Certificate getCertificate(String suffix, PrivateKey privateKey) throws Exception { X500Name name = new X500Name("CN=Dummy Certificate " + suffix); String algorithm = "SHA1with" + publicKey.getAlgorithm(); - Date date = new Date(); + Instant instant = Instant.now(); X509CertInfo certInfo = new X509CertInfo(); certInfo.setVersion(new CertificateVersion(CertificateVersion.V1)); @@ -59,7 +66,7 @@ private static X509Certificate getCertificate(String suffix, certInfo.setSubject(name); certInfo.setIssuer(name); certInfo.setKey(new CertificateX509Key(publicKey)); - certInfo.setValidity(new CertificateValidity(date, date)); + certInfo.setValidity(new CertificateValidity(instant, instant)); return X509CertImpl.newSigned(certInfo, privateKey, algorithm); } diff --git a/test/jdk/sun/security/ssl/HybridKeyExchange/ExternalHybridProvider.java b/test/jdk/sun/security/ssl/HybridKeyExchange/ExternalHybridProvider.java new file mode 100644 index 000000000000..ffd6394de714 --- /dev/null +++ b/test/jdk/sun/security/ssl/HybridKeyExchange/ExternalHybridProvider.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8385968 + * @summary Test TLS 1.3 use of an external hybrid key exchange provider + * @library /javax/net/ssl/templates + * @modules java.base/javax.crypto:+open + * @run main/othervm ExternalHybridProvider + */ + +import java.lang.ref.ReferenceQueue; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyPairGeneratorSpi; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.NamedParameterSpec; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.crypto.DecapsulateException; +import javax.crypto.KEM; +import javax.crypto.KEMSpi; +import javax.crypto.SecretKey; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; + +/* + * This provider models an external hybrid key exchange provider that + * provides hybrid KeyPairGenerator and KEM, and passes the peer + * key share as a RAW PublicKey. + */ +public class ExternalHybridProvider extends SSLSocketTemplate { + private static final String ALGORITHM = "X25519MLKEM768"; + private static final String PROVIDER_NAME = "MockHybrid"; + + private ExternalHybridProvider() { + super(true); + } + + @Override + protected void configureServerSocket(SSLServerSocket socket) { + configure(socket); + } + + @Override + protected void configureClientSocket(SSLSocket socket) { + configure(socket); + } + + private static void configure(SSLServerSocket socket) { + socket.setEnabledProtocols(new String[] { "TLSv1.3" }); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setNamedGroups(new String[] { ALGORITHM }); + socket.setSSLParameters(parameters); + } + + private static void configure(SSLSocket socket) { + socket.setEnabledProtocols(new String[] { "TLSv1.3" }); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setNamedGroups(new String[] { ALGORITHM }); + socket.setSSLParameters(parameters); + } + + public static void main(String[] args) throws Exception { + Provider provider = new MockProvider(); + Security.insertProviderAt(provider, 1); + try { + System.out.println(PROVIDER_NAME + + " as the most-preferred provider"); + allowMockProvider(provider); + System.out.println(PROVIDER_NAME + + " is marked as JCE-verified provider for this test"); + if (provider.getService("KeyFactory", ALGORITHM) != null) { + throw new RuntimeException(PROVIDER_NAME + + " must not provide " + + "KeyFactory." + ALGORITHM); + } + + new ExternalHybridProvider().run(); + + if (MockKPG.kpgCnt.get() == 0) { + throw new RuntimeException("TLS did not use external " + + "KeyPairGenerator." + ALGORITHM); + } + + if (MockKEM.encapsulatorCnt.get() == 0 || + MockKEM.decapsulatorCnt.get() == 0) { + throw new RuntimeException("TLS did not use external KEM." + + ALGORITHM + " for encapsulator and decapsulator operations"); + } + + System.out.printf("%s use counts: KPG=%d, encapsulator=%d, " + + "decapsulator=%d%n", PROVIDER_NAME, + MockKPG.kpgCnt.get(), + MockKEM.encapsulatorCnt.get(), + MockKEM.decapsulatorCnt.get()); + } finally { + Security.removeProvider(PROVIDER_NAME); + } + } + + @SuppressWarnings({ "unchecked", "removal" }) + private static void allowMockProvider(Provider provider) throws Exception { + Class jceSecurity = Class.forName("javax.crypto.JceSecurity"); + Field queueField = jceSecurity.getDeclaredField("queue"); + queueField.setAccessible(true); + ReferenceQueue queue = + (ReferenceQueue) queueField.get(null); + + Class wrapper = Class.forName( + "javax.crypto.JceSecurity$WeakIdentityWrapper"); + Constructor constructor = wrapper.getDeclaredConstructor( + Provider.class, ReferenceQueue.class); + constructor.setAccessible(true); + Object key = constructor.newInstance(provider, queue); + + Field resultsField = jceSecurity.getDeclaredField( + "verificationResults"); + resultsField.setAccessible(true); + Map results = + (Map) resultsField.get(null); + results.put(key, Boolean.TRUE); + } + + public static final class MockProvider extends Provider { + public MockProvider() { + super(PROVIDER_NAME, "1.0", "Mock TLS hybrid key exchange provider"); + put("KeyPairGenerator." + ALGORITHM, MockKPG.class.getName()); + put("KEM." + ALGORITHM, MockKEM.class.getName()); + } + } + + public static final class MockKPG extends KeyPairGeneratorSpi { + static final AtomicInteger kpgCnt = new AtomicInteger(); + private final KeyPairGenerator delegate; + + public MockKPG() { + try { + System.out.println("MockProvider KeyPairGenerator selected; " + + "delegating key generation to SunJCE"); + delegate = KeyPairGenerator.getInstance(ALGORITHM, "SunJCE"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + @Override + public void initialize(int keysize, SecureRandom random) { + throw new InvalidParameterException("Use named parameters"); + } + + @Override + public void initialize(AlgorithmParameterSpec params, + SecureRandom random) throws InvalidAlgorithmParameterException { + if (!(params instanceof NamedParameterSpec namedSpec) || + !ALGORITHM.equalsIgnoreCase(namedSpec.getName())) { + throw new InvalidAlgorithmParameterException( + "Expected NamedParameterSpec for " + ALGORITHM); + } + + delegate.initialize(params, random); + } + + @Override + public KeyPair generateKeyPair() { + kpgCnt.incrementAndGet(); + System.out.println("MockProvider KeyPairGenerator generated a " + + "hybrid key pair"); + return delegate.generateKeyPair(); + } + } + + public static final class MockKEM implements KEMSpi { + static final AtomicInteger encapsulatorCnt = new AtomicInteger(); + static final AtomicInteger decapsulatorCnt = new AtomicInteger(); + + @Override + public EncapsulatorSpi engineNewEncapsulator(PublicKey publicKey, + AlgorithmParameterSpec spec, SecureRandom secureRandom) throws + InvalidAlgorithmParameterException, InvalidKeyException { + if (!"RAW".equalsIgnoreCase(publicKey.getFormat())) { + throw new InvalidKeyException("Expected a RAW TLS key_share"); + } + encapsulatorCnt.incrementAndGet(); + + System.out.println("MockProvider KEM encapsulator selected for " + + "a RAW TLS key_share; delegating encapsulation to " + + "SunJCE"); + + KEM kem = sunJceKEM(); + return new MockEncapsulator(kem.newEncapsulator(publicKey, spec, + secureRandom)); + } + + @Override + public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, + AlgorithmParameterSpec spec) + throws InvalidAlgorithmParameterException, InvalidKeyException { + decapsulatorCnt.incrementAndGet(); + + System.out.println("MockProvider KEM decapsulator selected; " + + "delegating decapsulation to SunJCE"); + + KEM kem = sunJceKEM(); + return new MockDecapsulator(kem.newDecapsulator(privateKey, spec)); + } + + private static KEM sunJceKEM() { + try { + return KEM.getInstance(ALGORITHM, "SunJCE"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } + + private record MockEncapsulator(KEM.Encapsulator delegate) + implements KEMSpi.EncapsulatorSpi { + @Override + public KEM.Encapsulated engineEncapsulate(int from, int to, + String algorithm) { + return delegate.encapsulate(from, to, algorithm); + } + + @Override + public int engineSecretSize() { + return delegate.secretSize(); + } + + @Override + public int engineEncapsulationSize() { + return delegate.encapsulationSize(); + } + } + + private record MockDecapsulator(KEM.Decapsulator delegate) + implements KEMSpi.DecapsulatorSpi { + @Override + public SecretKey engineDecapsulate(byte[] encapsulation, int from, + int to, String algorithm) throws DecapsulateException { + return delegate.decapsulate(encapsulation, from, to, algorithm); + } + + @Override + public int engineSecretSize() { + return delegate.secretSize(); + } + + @Override + public int engineEncapsulationSize() { + return delegate.encapsulationSize(); + } + } +} diff --git a/test/jdk/sun/security/ssl/HybridKeyExchange/TestHybrid.java b/test/jdk/sun/security/ssl/HybridKeyExchange/TestHybrid.java index 82314c31dcf2..1d2cd744fc16 100644 --- a/test/jdk/sun/security/ssl/HybridKeyExchange/TestHybrid.java +++ b/test/jdk/sun/security/ssl/HybridKeyExchange/TestHybrid.java @@ -23,36 +23,132 @@ /* * @test - * @bug 8379433 - * @summary Test expected DecapsulateException thrown by Hybrid KEM implementation + * @bug 8379433 8385968 + * @summary Test TLS 1.3 hybrid KEM key generation, encapsulation, + * decapsulation, validation, and secret handling. * @modules java.base/sun.security.ssl * @run main/othervm TestHybrid */ +import java.io.ByteArrayOutputStream; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidParameterException; +import java.security.InvalidKeyException; import java.security.Provider; +import java.security.PublicKey; +import java.security.Security; +import java.security.spec.NamedParameterSpec; import java.util.Arrays; import javax.crypto.DecapsulateException; import javax.crypto.KEM; +import javax.crypto.SecretKey; public class TestHybrid { + private record HybridGroup(String name, int publicKeyLength) { } + + private static final HybridGroup[] HYBRID_GROUPS = { + new HybridGroup("X25519MLKEM768", 1216), + new HybridGroup("SecP256r1MLKEM768", 1249), + new HybridGroup("SecP384r1MLKEM1024", 1665) + }; + public static void main(String[] args) throws Exception { - Class clazz = Class.forName("sun.security.ssl.HybridProvider"); - Provider p = (Provider) clazz.getField("PROVIDER").get(null); + Provider p = Security.getProvider("SunJCE"); + if (p == null) { + throw new RuntimeException("SunJCE provider not found"); + } + if (p.getService("KEM", "DH") != null) { + throw new RuntimeException("SunJCE exposes internal KEM.DH"); + } + + for (int i = 0; i < HYBRID_GROUPS.length; i++) { + HybridGroup group = HYBRID_GROUPS[i]; + HybridGroup otherGroup = HYBRID_GROUPS[ + (i + 1) % HYBRID_GROUPS.length]; + testKPG(p, group); + testRawKeyLen(p, group); + testKEM(p, group, otherGroup); + } + } + + private static void testKPG(Provider provider, + HybridGroup group) throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(group.name, + provider); + KeyPair kp = kpg.generateKeyPair(); + + if (!group.name.equals(kp.getPublic().getAlgorithm()) || + !group.name.equals(kp.getPrivate().getAlgorithm())) { + throw new RuntimeException("Unexpected hybrid key algorithm for " + + group.name); + } + if (kp.getPublic().getEncoded().length != group.publicKeyLength) { + throw new RuntimeException("Unexpected public key length for " + + group.name); + } + + kpg.initialize(new NamedParameterSpec(group.name), null); + try { + kpg.initialize(new NamedParameterSpec("X448"), null); + throw new RuntimeException("Accepted incorrect parameters for " + + group.name); + } catch (InvalidAlgorithmParameterException expected) { + checkMessage(expected, "Expected NamedParameterSpec for " + + group.name); + System.out.println("Rejected incorrect parameters for " + + group.name); + } + kpg.initialize(-1, null); + kp = kpg.generateKeyPair(); + if (kp.getPublic().getEncoded().length != group.publicKeyLength) { + throw new RuntimeException("Unexpected public key length after " + + "key size initialization for " + group.name); + } + try { + kpg.initialize(256, null); + throw new RuntimeException("Accepted unsupported key size for " + + group.name); + } catch (InvalidParameterException expected) { + checkMessage(expected, "keysize not supported"); + System.out.println("Rejected unsupported key size for " + + group.name); + } + } - String alg = "X25519MLKEM768"; - KeyPairGenerator kpg = KeyPairGenerator.getInstance(alg, p); + private static void testKEM(Provider provider, HybridGroup group, + HybridGroup otherGroup) throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(group.name, + provider); KeyPair kp = kpg.generateKeyPair(); - KEM kem = KEM.getInstance(alg, p); + KEM kem = KEM.getInstance(group.name, provider); KEM.Encapsulator e = kem.newEncapsulator(kp.getPublic()); KEM.Decapsulator d = kem.newDecapsulator(kp.getPrivate()); int secretSize = e.secretSize(); KEM.Encapsulated enc = e.encapsulate(); + if (enc.key().getFormat() != null || enc.key().getEncoded() != null) { + throw new RuntimeException("Hybrid secret must be opaque"); + } + testNotSerializable(kp.getPrivate(), "hybrid private key", + "Hybrid private key must not be serialized"); + testNotSerializable(enc.key(), "hybrid shared secret", + "Hybrid shared secret must not be serialized"); byte[] ciphertext = enc.encapsulation(); + SecretKey decapsulated = d.decapsulate(ciphertext, 0, secretSize, + "generic"); + + if (!enc.key().equals(decapsulated) || + enc.key().hashCode() != decapsulated.hashCode()) { + throw new RuntimeException("Hybrid shared secrets are not equal"); + } + + testKEMArgs(e, d, ciphertext, secretSize); byte[] badCiphertext = Arrays.copyOf(ciphertext, ciphertext.length - 1); @@ -61,7 +157,152 @@ public static void main(String[] args) throws Exception { throw new RuntimeException( "Expected DecapsulateException not thrown"); } catch (DecapsulateException expected) { + checkMessage(expected, "Invalid key encapsulation message length: " + + badCiphertext.length + ", expected = " + ciphertext.length); System.out.println("Expected DecapsulateException thrown"); } + + try { + kem.newEncapsulator(kp.getPublic(), + new NamedParameterSpec(group.name), null); + throw new RuntimeException("Accepted KEM parameters"); + } catch (InvalidAlgorithmParameterException expected) { + checkMessage(expected, "KEM parameters are not supported for " + + group.name); + System.out.println("Rejected KEM parameters"); + } + + KEM otherKem = KEM.getInstance(otherGroup.name, provider); + try { + otherKem.newEncapsulator(kp.getPublic()); + throw new RuntimeException("Accepted " + group.name + + " key for " + otherGroup.name); + } catch (InvalidKeyException expected) { + checkMessage(expected, "Incorrect public key algorithm"); + System.out.println("Rejected " + group.name + + " key for " + otherGroup.name); + } + } + + private static void testKEMArgs(KEM.Encapsulator encapsulator, + KEM.Decapsulator decapsulator, byte[] ciphertext, int secretSize) + throws Exception { + try { + encapsulator.encapsulate(-1, secretSize, "Generic"); + throw new RuntimeException("Accepted negative encapsulation range"); + } catch (IndexOutOfBoundsException expected) { + checkMessage(expected, "Invalid secret range: from = -1, to = " + + secretSize + ", secret size = " + secretSize); + System.out.println("Rejected negative encapsulation range"); + } + + try { + decapsulator.decapsulate(ciphertext, 0, secretSize + 1, "Generic"); + throw new RuntimeException("Accepted oversized decapsulation range"); + } catch (IndexOutOfBoundsException expected) { + checkMessage(expected, "Invalid secret range: from = 0, to = " + + (secretSize + 1) + ", secret size = " + secretSize); + System.out.println("Rejected oversized decapsulation range"); + } + + try { + encapsulator.encapsulate(0, secretSize - 1, "Generic"); + throw new RuntimeException("Accepted partial encapsulation range"); + } catch (UnsupportedOperationException expected) { + checkMessage(expected, "Partial hybrid secrets are not supported"); + System.out.println("Rejected partial encapsulation range"); + } + + try { + decapsulator.decapsulate(ciphertext, 0, secretSize - 1, "Generic"); + throw new RuntimeException("Accepted partial decapsulation range"); + } catch (UnsupportedOperationException expected) { + checkMessage(expected, "Partial hybrid secrets are not supported"); + System.out.println("Rejected partial decapsulation range"); + } + + try { + encapsulator.encapsulate(0, secretSize, null); + throw new RuntimeException("Accepted null encapsulation algorithm"); + } catch (NullPointerException expected) { + checkMessage(expected, "algorithm must not be null"); + System.out.println("Rejected null encapsulation algorithm"); + } + + try { + decapsulator.decapsulate(ciphertext, 0, secretSize, null); + throw new RuntimeException("Accepted null decapsulation algorithm"); + } catch (NullPointerException expected) { + checkMessage(expected, "algorithm must not be null"); + System.out.println("Rejected null decapsulation algorithm"); + } + } + + private static void testRawKeyLen(Provider provider, HybridGroup group) + throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(group.name, + provider); + byte[] encoded = kpg.generateKeyPair().getPublic().getEncoded(); + KEM kem = KEM.getInstance(group.name, provider); + + testInvalidLen(kem, group.name, + Arrays.copyOf(encoded, encoded.length - 1), encoded.length); + testInvalidLen(kem, group.name, + Arrays.copyOf(encoded, encoded.length + 1), encoded.length); + } + + private static void testInvalidLen(KEM kem, String alg, + byte[] encoded, int expectedLength) throws Exception { + try { + kem.newEncapsulator(new RawPublicKey(alg, encoded)); + throw new RuntimeException("Accepted invalid RAW key length for " + + alg); + } catch (InvalidKeyException expected) { + checkMessage(expected, "Invalid hybrid key length " + + encoded.length + ", expected " + expectedLength); + System.out.println("Rejected invalid RAW key length for " + + alg); + } + } + + private static void testNotSerializable(Object obj, String name, + String expectedMessage) throws Exception { + try (var bytes = new ByteArrayOutputStream(); + var output = new ObjectOutputStream(bytes)) { + output.writeObject(obj); + throw new RuntimeException("Serialized " + name); + } catch (NotSerializableException expected) { + checkMessage(expected, expectedMessage); + System.out.println("Rejected serialization of " + name); + } + } + + private static void checkMessage(Throwable exception, + String expectedMessage) { + String actualMessage = exception.getMessage(); + if (!expectedMessage.equals(actualMessage)) { + throw new RuntimeException("Unexpected " + + exception.getClass().getSimpleName() + " message: expected \"" + + expectedMessage + "\", got \"" + actualMessage + "\"", + exception); + } + } + + private record RawPublicKey(String alg, byte[] encoded) + implements PublicKey { + @Override + public String getAlgorithm() { + return alg; + } + + @Override + public String getFormat() { + return "RAW"; + } + + @Override + public byte[] getEncoded() { + return encoded.clone(); + } } } diff --git a/test/jdk/sun/security/ssl/X509KeyManager/CertChecking.java b/test/jdk/sun/security/ssl/X509KeyManager/CertChecking.java index a6963e314f3c..17addb72f312 100644 --- a/test/jdk/sun/security/ssl/X509KeyManager/CertChecking.java +++ b/test/jdk/sun/security/ssl/X509KeyManager/CertChecking.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,7 +40,9 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509KeyManager; @@ -62,10 +64,10 @@ * @modules java.base/sun.security.x509 * java.base/sun.security.util * @library /test/lib - * @run main/othervm/timeout=480 CertChecking false SunX509 - * @run main/othervm/timeout=480 CertChecking true SunX509 - * @run main/othervm/timeout=480 CertChecking false PKIX - * @run main/othervm/timeout=480 CertChecking true PKIX + * @run main/othervm/timeout=240 CertChecking false SunX509 + * @run main/othervm/timeout=240 CertChecking true SunX509 + * @run main/othervm/timeout=240 CertChecking false PKIX + * @run main/othervm/timeout=240 CertChecking true PKIX */ /* @@ -112,6 +114,14 @@ public class CertChecking { private static final boolean[] NO_KA_USAGE = new boolean[]{true, true, true, true, false, true}; + // Key generation is fixture setup. Reuse keys across cases, but keep + // distinct keys for the valid, expired and usage-mismatch aliases. + private record EndpointKeys(KeyPair valid, KeyPair expired, + KeyPair usageMismatch) { } + + private static final Map ENDPOINT_KEYS = new HashMap<>(); + private static KeyPair caKeys; + private static X509Certificate trustedCert; public static void main(String[] args) throws Exception { if (args.length != 2) { @@ -123,6 +133,9 @@ public static void main(String[] args) throws Exception { System.setProperty("jdk.tls.SunX509KeyManager.certChecking", enabled); + caKeys = KeyPairGenerator.getInstance(CA_KEY_TYPE).generateKeyPair(); + trustedCert = createTrustedCert(caKeys); + // --- Usage and expired test cases -- // Both client and server should be checked with no usages at all @@ -358,15 +371,13 @@ private static X509KeyManager getKeyManager(String kmAlg, KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(null, null); - // Generate and set the trusted cert. - KeyPair caKeys = KeyPairGenerator.getInstance(CA_KEY_TYPE) - .generateKeyPair(); - X509Certificate trustedCert = createTrustedCert(caKeys); + // Reuse the CA and endpoint keys, but create fresh endpoint + // certificates, a key store and a key manager for each case. ks.setCertificateEntry("CA entry", trustedCert); + EndpointKeys keys = getEndpointKeys(keyAlg); // Generate valid certificate chain. - KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlg); - KeyPair validEndpointKeys = kpg.generateKeyPair(); + KeyPair validEndpointKeys = keys.valid(); X509Certificate validEndpointCert = customCertificateBuilder( EE_ISSUER_STRING, @@ -380,7 +391,7 @@ private static X509KeyManager getKeyManager(String kmAlg, validChain[1] = trustedCert; // Generate expired certificate chain. - KeyPair expiredEndpointKeys = kpg.generateKeyPair(); + KeyPair expiredEndpointKeys = keys.expired(); X509Certificate expiredEndpointCert = customCertificateBuilder( EE_ISSUER_STRING, @@ -394,7 +405,7 @@ private static X509KeyManager getKeyManager(String kmAlg, expiredChain[1] = trustedCert; // Generate usage mismatch certificate chain. - KeyPair usageMismatchEndpointKeys = kpg.generateKeyPair(); + KeyPair usageMismatchEndpointKeys = keys.usageMismatch(); X509Certificate usageMismatchEndpointCert = customCertificateBuilder( EE_ISSUER_STRING, @@ -425,6 +436,17 @@ private static X509KeyManager getKeyManager(String kmAlg, return (X509KeyManager) kmf.getKeyManagers()[0]; } + private static EndpointKeys getEndpointKeys(String keyAlg) throws Exception { + EndpointKeys keys = ENDPOINT_KEYS.get(keyAlg); + if (keys == null) { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlg); + keys = new EndpointKeys(kpg.generateKeyPair(), kpg.generateKeyPair(), + kpg.generateKeyPair()); + ENDPOINT_KEYS.put(keyAlg, keys); + } + return keys; + } + // Certificate-building helper methods. private static X509Certificate createTrustedCert(KeyPair caKeys) diff --git a/test/jdk/sun/security/util/DerInputBuffer/TimeParsing.java b/test/jdk/sun/security/util/DerInputBuffer/TimeParsing.java index e387f26d88ea..682628063760 100644 --- a/test/jdk/sun/security/util/DerInputBuffer/TimeParsing.java +++ b/test/jdk/sun/security/util/DerInputBuffer/TimeParsing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,8 @@ * @modules java.base/sun.security.util */ -import java.io.*; +import java.io.IOException; +import java.time.Instant; import java.util.Date; import sun.security.util.DerInputStream; @@ -111,27 +112,43 @@ private static Date decodeUTC(byte[] b) throws IOException { } private static Date decodeGeneralized(byte[] b) throws IOException { + DerInputStream derin = new DerInputStream(b); + return derin.getGeneralizedTime(); + } + + private static Instant decodeUTCInstant(byte[] b) throws IOException { DerInputStream derin = new DerInputStream(b); - return derin.getGeneralizedTime(); + return derin.getUTCInstant(); + } + + private static Instant decodeGeneralizedInstant(byte[] b) throws IOException { + DerInputStream derin = new DerInputStream(b); + return derin.getGeneralizedInstant(); } private static void checkUTC(Date d0, byte[] b, String text) throws Exception { - Date d1 = decodeUTC(b); - if( !d0.equals(d1) ) { - throw new Exception("UTCTime " + text + " failed: " + d1.toGMTString()); - } else { - System.out.println("UTCTime " + text + " ok"); - } + Date d1 = decodeUTC(b); + Instant d1Instant = decodeUTCInstant(b); + if (!d0.equals(d1) || !d1.toInstant().equals(d1Instant)) { + throw new Exception("UTCTime " + text + + " failed: " + d1.toGMTString()); + } else { + System.out.println("UTCTime " + text + " ok"); + } } - private static void checkGeneralized(Date d0, byte[] b, String text) throws Exception { - Date d1 = decodeGeneralized(b); - if( !d0.equals(d1) ) { - throw new Exception("GeneralizedTime " + text + " failed: " + d1.toGMTString()); - } else { - System.out.println("GeneralizedTime " + text + " ok"); + private static void checkGeneralized(Date d0, byte[] b, String text) + throws Exception { + + Date d1 = decodeGeneralized(b); + Instant d1Instant = decodeGeneralizedInstant(b); + if (!d0.equals(d1) || !d1.toInstant().equals(d1Instant)) { + throw new Exception("GeneralizedTime " + text + + " failed: " + d1.toGMTString()); + } else { + System.out.println("GeneralizedTime " + text + " ok"); + } } - } public static void main(String args[]) throws Exception { Date d0 = new Date(TIME); diff --git a/test/jdk/sun/security/util/DerOutputStream/DerTimeEncoding.java b/test/jdk/sun/security/util/DerOutputStream/DerTimeEncoding.java index 1fbfc73f3d68..b5e745567989 100644 --- a/test/jdk/sun/security/util/DerOutputStream/DerTimeEncoding.java +++ b/test/jdk/sun/security/util/DerOutputStream/DerTimeEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ * @modules java.base/sun.security.util */ -import java.util.Date; +import java.time.Instant; import sun.security.util.DerOutputStream; import sun.security.util.DerValue; @@ -37,8 +37,9 @@ public class DerTimeEncoding { public static void main(String args[]) throws Exception { //Check that dates after 2050 use GeneralizedTime DerOutputStream out = new DerOutputStream(); - Date generalizedTimeDate = new Date(2688854400000L); // Test date is 3/17/2055 - out.putTime(generalizedTimeDate); + // Test instant is 3/17/2055 + Instant generalizedTimeInstant = Instant.ofEpochMilli(2688854400000L); + out.putTime(generalizedTimeInstant); DerValue val = new DerValue(out.toByteArray()); if (val.tag != DerValue.tag_GeneralizedTime) { System.out.println("putTime incorrectly serialized to UTC time instead of GeneralizedTime"); @@ -47,8 +48,9 @@ public static void main(String args[]) throws Exception { //Check dates between 1950-2050 use UTC time out = new DerOutputStream(); - Date utcDate = new Date(242092800000L); //Test date is 9/3/1977 - out.putTime(utcDate); + //Test instant is 9/3/1977 + Instant utcInstant = Instant.ofEpochMilli(242092800000L); + out.putTime(utcInstant); val = new DerValue(out.toByteArray()); if (val.tag != DerValue.tag_UtcTime) { System.out.println("putTime incorrectly serialized to Generalized time instead of UTC time"); diff --git a/test/jdk/sun/security/x509/CertificateValidity/NullName.java b/test/jdk/sun/security/x509/CertificateValidity/NullName.java index cc0a3a8b556e..a26449726889 100644 --- a/test/jdk/sun/security/x509/CertificateValidity/NullName.java +++ b/test/jdk/sun/security/x509/CertificateValidity/NullName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,12 +31,12 @@ import jdk.test.lib.Utils; import sun.security.x509.CertificateValidity; -import java.util.Date; +import java.time.Instant; public class NullName { public static void main(String[] argv) throws Exception { - Date now = new Date(); + Instant now = Instant.now(); Utils.runAndCheckException( () -> new CertificateValidity(null, null), NullPointerException.class); diff --git a/test/jdk/sun/security/x509/Extensions/IllegalExtensions.java b/test/jdk/sun/security/x509/Extensions/IllegalExtensions.java index 596a434292c8..79787f2e8bcb 100644 --- a/test/jdk/sun/security/x509/Extensions/IllegalExtensions.java +++ b/test/jdk/sun/security/x509/Extensions/IllegalExtensions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,9 +32,40 @@ import jdk.test.lib.Utils; import sun.security.util.ObjectIdentifier; -import sun.security.x509.*; +import sun.security.x509.AccessDescription; +import sun.security.x509.AuthorityInfoAccessExtension; +import sun.security.x509.AuthorityKeyIdentifierExtension; +import sun.security.x509.CRLDistributionPointsExtension; +import sun.security.x509.CRLNumberExtension; +import sun.security.x509.CRLReasonCodeExtension; +import sun.security.x509.CertificateIssuerExtension; +import sun.security.x509.CertificatePoliciesExtension; +import sun.security.x509.CertificatePolicyId; +import sun.security.x509.CertificatePolicyMap; +import sun.security.x509.DistributionPoint; +import sun.security.x509.DistributionPointName; +import sun.security.x509.ExtendedKeyUsageExtension; +import sun.security.x509.GeneralName; +import sun.security.x509.GeneralNames; +import sun.security.x509.GeneralSubtrees; +import sun.security.x509.InhibitAnyPolicyExtension; +import sun.security.x509.InvalidityDateExtension; +import sun.security.x509.IssuerAlternativeNameExtension; +import sun.security.x509.IssuingDistributionPointExtension; +import sun.security.x509.KeyIdentifier; +import sun.security.x509.NameConstraintsExtension; +import sun.security.x509.PolicyConstraintsExtension; +import sun.security.x509.PolicyInformation; +import sun.security.x509.PolicyMappingsExtension; +import sun.security.x509.PrivateKeyUsageExtension; +import sun.security.x509.ReasonFlags; +import sun.security.x509.SerialNumber; +import sun.security.x509.SubjectAlternativeNameExtension; +import sun.security.x509.SubjectInfoAccessExtension; +import sun.security.x509.X500Name; import java.math.BigInteger; +import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.List; @@ -125,10 +156,11 @@ public static void main(String [] args) throws Exception { Utils.runAndCheckException(() -> new PolicyMappingsExtension(List.of()), IllegalArgumentException.class); Utils.runAndCheckException(() -> new PolicyMappingsExtension(null), IllegalArgumentException.class); - new PrivateKeyUsageExtension(new Date(), new Date()); - new PrivateKeyUsageExtension(new Date(), null); - new PrivateKeyUsageExtension((Date) null, new Date()); - Utils.runAndCheckException(() -> new PrivateKeyUsageExtension((Date) null, null), IllegalArgumentException.class); + Instant now = Instant.now(); + new PrivateKeyUsageExtension(now, now); + new PrivateKeyUsageExtension(now, null); + new PrivateKeyUsageExtension((Instant) null, now); + Utils.runAndCheckException(() -> new PrivateKeyUsageExtension((Instant) null, null), IllegalArgumentException.class); new SubjectAlternativeNameExtension(names); Utils.runAndCheckException(() -> new SubjectAlternativeNameExtension(null), IllegalArgumentException.class); diff --git a/test/jdk/sun/security/x509/X509CertImpl/CertExtensions.java b/test/jdk/sun/security/x509/X509CertImpl/CertExtensions.java index f8ee13e8f511..54eeab61183c 100644 --- a/test/jdk/sun/security/x509/X509CertImpl/CertExtensions.java +++ b/test/jdk/sun/security/x509/X509CertImpl/CertExtensions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,14 +33,49 @@ import jdk.test.lib.Asserts; import sun.security.util.ObjectIdentifier; -import sun.security.x509.*; +import sun.security.x509.AlgorithmId; +import sun.security.x509.AuthorityKeyIdentifierExtension; +import sun.security.x509.BasicConstraintsExtension; +import sun.security.x509.CertificateAlgorithmId; +import sun.security.x509.CertificateSerialNumber; +import sun.security.x509.CertificateValidity; +import sun.security.x509.CertificateVersion; +import sun.security.x509.CertificateX509Key; +import sun.security.x509.DNSName; +import sun.security.x509.GeneralName; +import sun.security.x509.GeneralNameInterface; +import sun.security.x509.GeneralNames; +import sun.security.x509.IPAddressName; +import sun.security.x509.IssuerAlternativeNameExtension; +import sun.security.x509.KeyIdentifier; +import sun.security.x509.KeyUsageExtension; +import sun.security.x509.OIDName; +import sun.security.x509.PolicyConstraintsExtension; +import sun.security.x509.PrivateKeyUsageExtension; +import sun.security.x509.RFC822Name; +import sun.security.x509.SerialNumber; +import sun.security.x509.SubjectAlternativeNameExtension; +import sun.security.x509.SubjectKeyIdentifierExtension; +import sun.security.x509.URIName; +import sun.security.x509.UniqueIdentity; +import sun.security.x509.X500Name; +import sun.security.x509.X509CertImpl; +import sun.security.x509.X509CertInfo; import java.io.IOException; import java.math.BigInteger; -import java.security.*; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; public class CertExtensions { @@ -108,8 +143,9 @@ private static X509CertImpl createCertificate() throws Exception { x509CertInfo.setSerialNumber(new CertificateSerialNumber(serialNumber)); // create and set the validity interval - Date notBefore = new Date(); // Valid from now - Date notAfter = new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000); // Valid for 1 year + // valid from now and for 1 year + Instant notBefore = Instant.now(); + Instant notAfter = notBefore.plus(365, ChronoUnit.DAYS); x509CertInfo.setValidity(new CertificateValidity(notBefore, notAfter)); // Create Certificate Info which is the representation of X509 Certificate. @@ -164,11 +200,9 @@ private static X509CertImpl createCertificate() throws Exception { issuerNames.add(ip); issuerNames.add(oid); IssuerAlternativeNameExtension issuerName = new IssuerAlternativeNameExtension(issuerNames); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); - cal.set(2014, 03, 10, 12, 30, 30); - cal.set(2000, 11, 15, 12, 30, 30); - Date lastDate = cal.getTime(); - Date firstDate = new Date(); + Instant lastDate = LocalDateTime.of(2000, 11, 15, 12, 30, 3) + .toInstant(ZoneOffset.UTC); + Instant firstDate = Instant.now(); PrivateKeyUsageExtension pkusage = new PrivateKeyUsageExtension(firstDate, lastDate); KeyUsageExtension usage = new KeyUsageExtension(); diff --git a/test/jdk/sun/security/x509/X509CertImpl/V3Certificate.java b/test/jdk/sun/security/x509/X509CertImpl/V3Certificate.java index 29c651164d3f..ea250e5b63c2 100644 --- a/test/jdk/sun/security/x509/X509CertImpl/V3Certificate.java +++ b/test/jdk/sun/security/x509/X509CertImpl/V3Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,6 +52,7 @@ import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.time.Instant; import java.util.Base64; import java.util.Calendar; import java.util.Date; @@ -113,18 +114,18 @@ public static boolean test(String algorithm, String sigAlg, int keyLength) signature.initSign(privateKey); // Validity interval - Date firstDate = new Date(); + Instant firstDate = Instant.now(); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); cal.set(2014, 03, 10, 12, 30, 30); Date lastDate = cal.getTime(); CertificateValidity interval = new CertificateValidity(firstDate, - lastDate); + lastDate.toInstant()); // Certificate Info X509CertInfo cert = new X509CertInfo(); cert.setVersion(new CertificateVersion(CertificateVersion.V3)); - cert.setSerialNumber(new CertificateSerialNumber((int) (firstDate.getTime() / 1000))); + cert.setSerialNumber(new CertificateSerialNumber((int) (firstDate.toEpochMilli() / 1000))); cert.setAlgorithmId(new CertificateAlgorithmId(AlgorithmId.get(sigAlg))); cert.setSubject(subject); cert.setKey(new CertificateX509Key(publicKey)); @@ -172,7 +173,7 @@ public static boolean test(String algorithm, String sigAlg, int keyLength) cal.set(2000, 11, 15, 12, 30, 30); lastDate = cal.getTime(); PrivateKeyUsageExtension pkusage - = new PrivateKeyUsageExtension(firstDate, lastDate); + = new PrivateKeyUsageExtension(firstDate, lastDate.toInstant()); KeyUsageExtension usage = new KeyUsageExtension(); usage.set(KeyUsageExtension.CRL_SIGN, true); diff --git a/test/jdk/tools/sincechecker/modules/java.base/JavaBaseCheckSince.java b/test/jdk/tools/sincechecker/modules/java.base/JavaBaseCheckSince.java index b75b6d9401aa..5d1f93a3f528 100644 --- a/test/jdk/tools/sincechecker/modules/java.base/JavaBaseCheckSince.java +++ b/test/jdk/tools/sincechecker/modules/java.base/JavaBaseCheckSince.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,5 +26,5 @@ * @bug 8331051 8367610 * @summary Test for `@since` in java.base module * @library /test/lib /test/jdk/tools/sincechecker - * @run main/timeout=480 SinceChecker java.base --exclude java.lang.classfile + * @run main/timeout=480 SinceChecker java.base --exclude java.lang.classfile java.io */ diff --git a/test/langtools/tools/javac/lambda/MethodReferenceVarargsIntersectionTest.java b/test/langtools/tools/javac/lambda/MethodReferenceVarargsIntersectionTest.java new file mode 100644 index 000000000000..d043ed19253e --- /dev/null +++ b/test/langtools/tools/javac/lambda/MethodReferenceVarargsIntersectionTest.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8397176 + * @summary VerifyError when running compiled varargs method references with + * intersection type receivers. + * @compile MethodReferenceVarargsIntersectionTest.java + * @run main MethodReferenceVarargsIntersectionTest + */ + +public class MethodReferenceVarargsIntersectionTest { + + static class A {} + + interface B { + void m(String... args); + } + + static class C extends A implements B { + @Override + public void m(String... args) {} + } + + public static void main(String... args) { + var i = (A & B) new C(); + ((Runnable) i::m).run(); + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/patterns/Exhaustiveness.java b/test/langtools/tools/javac/patterns/Exhaustiveness.java index ce5f63059d28..bea95eba1179 100644 --- a/test/langtools/tools/javac/patterns/Exhaustiveness.java +++ b/test/langtools/tools/javac/patterns/Exhaustiveness.java @@ -30,8 +30,8 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util * @build toolbox.ToolBox toolbox.JavacTask - * @run main Exhaustiveness -*/ + * @run main/othervm/timeout=480 Exhaustiveness + */ import java.io.IOException; import java.nio.file.Files; diff --git a/test/lib/jdk/test/lib/security/timestamp/TsaSigner.java b/test/lib/jdk/test/lib/security/timestamp/TsaSigner.java index 7ec2609e779f..f3378a5b4a97 100644 --- a/test/lib/jdk/test/lib/security/timestamp/TsaSigner.java +++ b/test/lib/jdk/test/lib/security/timestamp/TsaSigner.java @@ -27,6 +27,7 @@ import java.security.MessageDigest; import java.security.Signature; import java.security.cert.X509Certificate; +import java.time.Instant; import java.util.Date; import java.util.Objects; @@ -232,7 +233,7 @@ private byte[] createResponse(TsaParam requestParam) throws Exception { new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, infoOid), new PKCS9Attribute(PKCS9Attribute.SIGNING_TIME_OID, - new Date()), + Instant.now()), new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, MessageDigest.getInstance(digestAlg.getName()) .digest(tstInfoSeqData)) diff --git a/test/micro/org/openjdk/bench/java/lang/StringBuilders.java b/test/micro/org/openjdk/bench/java/lang/StringBuilders.java index bf3e5f7a06b5..e1ed0f493ad8 100644 --- a/test/micro/org/openjdk/bench/java/lang/StringBuilders.java +++ b/test/micro/org/openjdk/bench/java/lang/StringBuilders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2025, Alibaba Group Holding Limited. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -491,6 +491,54 @@ public String emptyToString(Data data) { return data.sbEmpty.toString(); } + @Benchmark + public StringBuilder repeatLatin1StringOntoLatin1StringBuilder(Data data) { + var sbLatin1 = new StringBuilder("a"); + return sbLatin1.repeat(data.str, data.length); + } + + @Benchmark + public StringBuilder repeatLatin1StringOntoUtf16StringBuilder(Data data) { + var sbUtf16 = new StringBuilder("\u04FF"); + return sbUtf16.repeat(data.str, data.length); + } + + @Benchmark + public StringBuilder repeatUtf16StringOntoLatin1StringBuilder(Data data) { + var sbLatin1 = new StringBuilder("a"); + return sbLatin1.repeat(data.utf16Str, data.length); + } + + @Benchmark + public StringBuilder repeatUtf16StringOntoUtf16StringBuilder(Data data) { + var sbUtf16 = new StringBuilder("\u04FF"); + return sbUtf16.repeat(data.utf16Str, data.length); + } + + @Benchmark + public StringBuilder repeatLatin1CodePointOntoLatin1StringBuilder(Data data) { + var sbLatin1 = new StringBuilder("a"); + return sbLatin1.repeat('a', data.length); + } + + @Benchmark + public StringBuilder repeatLatin1CodePointOntoUtf16StringBuilder(Data data) { + var sbUtf16 = new StringBuilder("\u04FF"); + return sbUtf16.repeat('a', data.length); + } + + @Benchmark + public StringBuilder repeatUtf16BmpCodePointOntoLatin1StringBuilder(Data data) { + var sbLatin1 = new StringBuilder("a"); + return sbLatin1.repeat(0x4FF, data.length); + } + + @Benchmark + public StringBuilder repeatUtf16BmpCodePointOntoUtf16StringBuilder(Data data) { + var sbUtf16 = new StringBuilder("\u04FF"); + return sbUtf16.repeat(0x4FF, data.length); + } + @State(Scope.Thread) public static class Data { int i = 0; diff --git a/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java b/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java index dc6d2060f5e4..6c313f1d665d 100644 --- a/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java +++ b/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,10 +98,21 @@ public void setup() throws NoSuchAlgorithmException, InvalidKeyException, } } - private static Provider getInternalJce() { + private static Provider getSunJCE() { + Provider provider = Security.getProvider("SunJCE"); + if (provider == null) { + throw new RuntimeException("SunJCE provider not found"); + } + + return provider; + } + + private static Provider getInternalDHAsKEM() { try { - Class dhClazz = Class.forName("sun.security.ssl.HybridProvider"); - return (Provider) dhClazz.getField("PROVIDER").get(null); + Class dhClass = Class.forName("sun.security.ssl.DHasKEM"); + var provider = dhClass.getDeclaredField("PROVIDER"); + provider.setAccessible(true); + return (Provider) provider.get(null); } catch (ReflectiveOperationException exc) { throw new RuntimeException(exc); } @@ -140,7 +151,7 @@ public static class JSSE_DHasKEM extends KEMBench { @Setup public void init() { try { - prov = getInternalJce(); + prov = getInternalDHAsKEM(); super.setup(); } catch (GeneralSecurityException gse) { throw new RuntimeException(gse); @@ -160,7 +171,7 @@ public static class JSSE_Hybrid extends KEMBench { @Setup public void init() { try { - prov = getInternalJce(); + prov = getSunJCE(); super.setup(); } catch (GeneralSecurityException gse) { throw new RuntimeException(gse); diff --git a/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java b/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java index 5a3c72fb2638..78e4ff531c21 100644 --- a/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java +++ b/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.security.Security; public class KeyPairGeneratorBench extends CryptoBase { @@ -54,13 +55,13 @@ public void setup() throws NoSuchAlgorithmException { } } - private static Provider getInternalJce() { - try { - Class dhClazz = Class.forName("sun.security.ssl.HybridProvider"); - return (Provider) dhClazz.getField("PROVIDER").get(null); - } catch (ReflectiveOperationException exc) { - throw new RuntimeException(exc); + private static Provider getSunJCE() { + Provider provider = Security.getProvider("SunJCE"); + if (provider == null) { + throw new RuntimeException("SunJCE provider not found"); } + + return provider; } @Benchmark @@ -137,7 +138,7 @@ public static class JSSE_Hybrid extends KeyPairGeneratorBench { @Setup public void init() { try { - prov = getInternalJce(); + prov = getSunJCE(); super.setup(); } catch (GeneralSecurityException gse) { throw new RuntimeException(gse); diff --git a/test/micro/org/openjdk/bench/jdk/incubator/vector/ByteShiftBenchmark.java b/test/micro/org/openjdk/bench/jdk/incubator/vector/ByteShiftBenchmark.java new file mode 100644 index 000000000000..939722015c06 --- /dev/null +++ b/test/micro/org/openjdk/bench/jdk/incubator/vector/ByteShiftBenchmark.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.jdk.incubator.vector; + +import java.util.concurrent.TimeUnit; +import jdk.incubator.vector.ByteVector; +import jdk.incubator.vector.VectorOperators; +import jdk.incubator.vector.VectorSpecies; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OperationsPerInvocation; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Thread) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(value = 1, jvmArgs = {"--add-modules=jdk.incubator.vector"}) +public class ByteShiftBenchmark { + static final int BYTES = 4096; + + static final VectorSpecies B128 = ByteVector.SPECIES_128; + static final VectorSpecies B256 = ByteVector.SPECIES_256; + static final VectorSpecies B512 = ByteVector.SPECIES_512; + + @Param({"3"}) + int shift; + + byte[] src; + byte[] dst; + + @Setup + public void setup() { + src = new byte[BYTES]; + dst = new byte[BYTES]; + for (int i = 0; i < src.length; i++) { + src[i] = (byte) i; + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void autoVecLshl() { + for (int i = 0; i < BYTES; i++) { + dst[i] = (byte) (src[i] << shift); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void autoVecAshr() { + for (int i = 0; i < BYTES; i++) { + dst[i] = (byte) (src[i] >> shift); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshl128() { + for (int i = 0; i < BYTES; i += B128.length()) { + ByteVector.fromArray(B128, src, i) + .lanewise(VectorOperators.LSHL, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void ashr128() { + for (int i = 0; i < BYTES; i += B128.length()) { + ByteVector.fromArray(B128, src, i) + .lanewise(VectorOperators.ASHR, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshr128() { + for (int i = 0; i < BYTES; i += B128.length()) { + ByteVector.fromArray(B128, src, i) + .lanewise(VectorOperators.LSHR, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshl256() { + for (int i = 0; i < BYTES; i += B256.length()) { + ByteVector.fromArray(B256, src, i) + .lanewise(VectorOperators.LSHL, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void ashr256() { + for (int i = 0; i < BYTES; i += B256.length()) { + ByteVector.fromArray(B256, src, i) + .lanewise(VectorOperators.ASHR, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshr256() { + for (int i = 0; i < BYTES; i += B256.length()) { + ByteVector.fromArray(B256, src, i) + .lanewise(VectorOperators.LSHR, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshl512() { + for (int i = 0; i < BYTES; i += B512.length()) { + ByteVector.fromArray(B512, src, i) + .lanewise(VectorOperators.LSHL, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void ashr512() { + for (int i = 0; i < BYTES; i += B512.length()) { + ByteVector.fromArray(B512, src, i) + .lanewise(VectorOperators.ASHR, shift).intoArray(dst, i); + } + } + + @Benchmark + @OperationsPerInvocation(BYTES) + public void lshr512() { + for (int i = 0; i < BYTES; i += B512.length()) { + ByteVector.fromArray(B512, src, i) + .lanewise(VectorOperators.LSHR, shift).intoArray(dst, i); + } + } +} diff --git a/test/micro/org/openjdk/bench/jdk/incubator/vector/LongVectorReduction.java b/test/micro/org/openjdk/bench/jdk/incubator/vector/LongVectorReduction.java new file mode 100644 index 000000000000..360d10e3b62c --- /dev/null +++ b/test/micro/org/openjdk/bench/jdk/incubator/vector/LongVectorReduction.java @@ -0,0 +1,190 @@ +/* + * Copyright 2026 Arm Limited and/or its affiliates. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.jdk.incubator.vector; + +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import jdk.incubator.vector.LongVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorOperators; +import jdk.incubator.vector.VectorSpecies; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(value = 1, jvmArgs = {"--add-modules=jdk.incubator.vector"}) +public class LongVectorReduction { + private static final VectorSpecies SPECIES_128 = LongVector.SPECIES_128; + + @Param({"512", "2048"}) + public int size; + + private long[] in1; + private long[] in2; + private long[] in3; + private VectorMask mask; + + @Setup + public void setup() { + Random r = new Random(0); + in1 = new long[size]; + in2 = new long[size]; + in3 = new long[size]; + mask = VectorMask.fromLong(SPECIES_128, 1); + for (int i = 0; i < size; i++) { + in1[i] = r.nextLong(); + in2[i] = r.nextLong(); + in3[i] = r.nextLong(); + } + } + + @Benchmark + public void addDotProduct(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + acc = acc.add(a.mul(b)); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void addDotProductShared(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + LongVector c = LongVector.fromArray(SPECIES_128, in3, i); + LongVector val = a.mul(b); + acc = acc.add(val.add(val.mul(c))); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void subDotProduct(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + acc = acc.sub(a.mul(b)); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void addDotProductMasked(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + acc = acc.add(a.mul(b), mask); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void subDotProductMasked(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + acc = acc.sub(a.mul(b), mask); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void addBig(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + LongVector c = LongVector.fromArray(SPECIES_128, in3, i); + LongVector val = a.mul(b).add(a.mul(c)).add(b.mul(c)); + acc = acc.add(val); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void ifElsePhiAdd(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + LongVector c = LongVector.fromArray(SPECIES_128, in3, i); + LongVector selected; + if ((i & SPECIES_128.length()) == 0) { + selected = a.mul(b); + } else { + selected = b.mul(c); + } + acc = acc.add(selected.add(a.mul(c))); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } + + @Benchmark + public void ifElsePhiSub(Blackhole bh) { + LongVector acc = LongVector.zero(SPECIES_128); + for (int i = 0; i < SPECIES_128.loopBound(size); i += SPECIES_128.length()) { + LongVector a = LongVector.fromArray(SPECIES_128, in1, i); + LongVector b = LongVector.fromArray(SPECIES_128, in2, i); + LongVector c = LongVector.fromArray(SPECIES_128, in3, i); + LongVector selected; + if ((i & SPECIES_128.length()) == 0) { + selected = a.mul(b); + } else { + selected = b.mul(c); + } + acc = acc.add(selected.sub(a.mul(c))); + } + long res = acc.reduceLanes(VectorOperators.ADD); + bh.consume(res); + } +} diff --git a/test/micro/org/openjdk/bench/vm/compiler/TypeVectorOperations.java b/test/micro/org/openjdk/bench/vm/compiler/TypeVectorOperations.java index 9ef580d09c73..584c060a3320 100644 --- a/test/micro/org/openjdk/bench/vm/compiler/TypeVectorOperations.java +++ b/test/micro/org/openjdk/bench/vm/compiler/TypeVectorOperations.java @@ -1,6 +1,7 @@ /* * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2025 IBM Corporation. All rights reserved. + * Copyright 2026 Arm Limited and/or its affiliates. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +50,10 @@ public abstract class TypeVectorOperations { private short[] resS; private int[] ints; private int[] resI; - private long[] longs; + private long[] longsA; + private long[] longsB; + private long[] longsC; + private long[] longsD; private long[] resL; private double[] doubles; private double[] resD; @@ -72,7 +76,10 @@ public void init() { resS = new short[COUNT]; ints = new int[COUNT]; resI = new int[COUNT]; - longs = new long[COUNT]; + longsA = new long[COUNT]; + longsB = new long[COUNT]; + longsC = new long[COUNT]; + longsD = new long[COUNT]; resL = new long[COUNT]; doubles = new double[COUNT]; resD = new double[COUNT]; @@ -84,7 +91,10 @@ public void init() { boolsB[i] = r.nextBoolean(); shorts[i] = (short) r.nextInt(Short.MAX_VALUE + 1); ints[i] = r.nextInt(); - longs[i] = r.nextLong(); + longsA[i] = r.nextLong(); + longsB[i] = r.nextLong(); + longsC[i] = r.nextLong(); + longsD[i] = r.nextLong(); floats[i] = r.nextFloat(); doubles[i] = r.nextDouble(); } @@ -158,14 +168,43 @@ public void mulI() { @Benchmark public void mulL() { for (int i = 0; i < COUNT; i++) { - resL[i] = (longs[i] * longs[i]); + resL[i] = (longsA[i] * longsA[i]); + } + } + + @Benchmark + public void mlaL() { + for (int i = 0; i < COUNT; i++) { + resL[i] = longsA[i] + longsA[i] * longsB[i]; + } + } + + @Benchmark + public void mlsL() { + for (int i = 0; i < COUNT; i++) { + resL[i] = longsA[i] - longsA[i] * longsB[i]; + } + } + + @Benchmark + public void mulMlaLIndependent() { + for (int i = 0; i < COUNT; i++) { + resL[i] = longsA[i] * longsB[i] + longsC[i] * longsD[i]; + } + } + + @Benchmark + public void mulMlaLDependent() { + for (int i = 0; i < COUNT; i++) { + long res = longsA[i] * longsB[i]; + resL[i] = res + res * longsC[i]; } } @Benchmark public void absL() { for (int i = 0; i < COUNT; i++) { - long a = longs[i]; + long a = longsA[i]; resL[i] = (long) (Math.abs((long) a)); } } @@ -173,7 +212,7 @@ public void absL() { @Benchmark public void rShiftL() { for (int i = 0; i < COUNT; i++) { - resL[i] = longs[i] >> 3; + resL[i] = longsA[i] >> 3; } } @@ -357,42 +396,42 @@ public void convertI2L() { @Benchmark public void convertL2D() { for (int i = 0; i < COUNT; i++) { - resD[i] = (double) longs[i]; + resD[i] = (double) longsA[i]; } } @Benchmark public void convertLBits2D() { for (int i = 0; i < COUNT; i++) { - resD[i] = Double.longBitsToDouble(longs[i]); + resD[i] = Double.longBitsToDouble(longsA[i]); } } @Benchmark public void convertL2B() { for (int i = 0; i < COUNT; i++) { - resB[i] = (byte) longs[i]; + resB[i] = (byte) longsA[i]; } } @Benchmark public void convertL2F() { for (int i = 0; i < COUNT; i++) { - resF[i] = (float) longs[i]; + resF[i] = (float) longsA[i]; } } @Benchmark public void convertL2I() { for (int i = 0; i < COUNT; i++) { - resI[i] = (int) longs[i]; + resI[i] = (int) longsA[i]; } } @Benchmark public void convertL2S() { for (int i = 0; i < COUNT; i++) { - resS[i] = (short) longs[i]; + resS[i] = (short) longsA[i]; } } diff --git a/test/micro/org/openjdk/bench/vm/compiler/VectorReduction2.java b/test/micro/org/openjdk/bench/vm/compiler/VectorReduction2.java index 0d11705c8ec6..141b50eac25d 100644 --- a/test/micro/org/openjdk/bench/vm/compiler/VectorReduction2.java +++ b/test/micro/org/openjdk/bench/vm/compiler/VectorReduction2.java @@ -1113,6 +1113,16 @@ public void longAddDotProduct(Blackhole bh) { bh.consume(acc); } + @Benchmark + public void longAddDotProductShared(Blackhole bh) { + long acc = 0; // neutral element + for (int i = 0; i < SIZE; i++) { + long val = in1L[i] * in2L[i]; + acc += val + val * in3L[i]; + } + bh.consume(acc); + } + @Benchmark public void longMulDotProduct(Blackhole bh) { long acc = 1; // neutral element @@ -1184,6 +1194,36 @@ public void longAddBig(Blackhole bh) { bh.consume(acc); } + @Benchmark + public void longAddBigMixSub1(Blackhole bh) { + long acc = 0; // neutral element + for (int i = 0; i < SIZE; i++) { + long val = (in1L[i] * in2L[i]) + (in1L[i] * in3L[i]) - (in2L[i] * in3L[i]); + acc += val; + } + bh.consume(acc); + } + + @Benchmark + public void longAddBigMixSub2(Blackhole bh) { + long acc = 0; // neutral element + for (int i = 0; i < SIZE; i++) { + long val = (in1L[i] * in2L[i]) - (in1L[i] * in3L[i]) + (in2L[i] * in3L[i]); + acc += val; + } + bh.consume(acc); + } + + @Benchmark + public void longAddBigMixSub3(Blackhole bh) { + long acc = 0; // neutral element + for (int i = 0; i < SIZE; i++) { + long val = (in1L[i] * in2L[i]) - (in1L[i] * in3L[i]) - (in2L[i] * in3L[i]); + acc += val; + } + bh.consume(acc); + } + @Benchmark public void longMulBig(Blackhole bh) { long acc = 1; // neutral element