Skip to content

Conversation

@rwestrel
Copy link
Contributor

@rwestrel rwestrel commented Feb 13, 2025

The test crashes because of a division by zero. The Div node for
that one is initially part of a counted loop. The control input of the
node is cleared because the divisor is non zero. This is because the
divisor depends on the loop phi and the type of the loop phi is
narrowed down when the counted loop is created. pre/main/post loops
are created, unrolling happens, the main loop looses its backedge. The
Div node can then float above the zero trip guard for the main
loop. When the zero trip guard is not taken, there's no guarantee the
divisor is non zero so the Div node should be pinned below it.

I propose we revert the change I made with 8334724 which removed
PhaseIdealLoop::cast_incr_before_loop(). The CastII that this
method inserted was there to handle exactly this problem. It was added
initially for a similar issue but with array loads. That problem with
loads is handled some other way now and that's why I thought it was
safe to proceed with the removal.

The code in this patch is somewhat different from the one we had
before for a couple reasons:

1- assert predicate code evolved and so previous logic can't be
resurrected as it was.

2- the previous logic has a bug.

Regarding 1-: during pre/main/post loop creation, we used to add the
CastII and then to add assertion predicates (so assertion predicates
depended on the CastII). Then when unrolling, when assertion
predicates are updated, we would skip over the CastII. What I
propose here is to add the CastII after assertion predicates are
added. As a result, they don't depend on the CastII and there's no
need for any extra logic when unrolling happens. This, however,
doesn't work when the assertion predicates are added by RCE. In that
case, I had to add logic to skip over the CastII (similar to what
existed before I removed it).

Regarding 2-: previous implementation for
PhaseIdealLoop::cast_incr_before_loop() would add the CastII at
the first loop Phi it encounters that's a use of the loop increment:
it's usually the iv but not always. I tweaked the test case to show,
this bug can actually cause a crash and changed the logic for
PhaseIdealLoop::cast_incr_before_loop() accordingly.


Progress

  • Change must be properly reviewed (1 review required, with at least 1 Reviewer)
  • Change must not contain extraneous whitespace
  • Commit message must refer to an issue

Issue

  • JDK-8349139: C2: Div looses dependency on condition that guarantees divisor not zero in counted loop (Bug - P3)

Reviewers

Reviewing

Using git

Checkout this PR locally:
$ git fetch https://git.openjdk.org/jdk.git pull/23617/head:pull/23617
$ git checkout pull/23617

Update a local copy of the PR:
$ git checkout pull/23617
$ git pull https://git.openjdk.org/jdk.git pull/23617/head

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 23617

View PR using the GUI difftool:
$ git pr show -t 23617

Using diff file

Download this PR as a diff file:
https://git.openjdk.org/jdk/pull/23617.diff

Using Webrev

Link to Webrev Comment

@bridgekeeper
Copy link

bridgekeeper bot commented Feb 13, 2025

👋 Welcome back roland! A progress list of the required criteria for merging this PR into master will be added to the body of your pull request. There are additional pull request commands available for use with this pull request.

@openjdk
Copy link

openjdk bot commented Feb 13, 2025

@rwestrel This change now passes all automated pre-integration checks.

ℹ️ This project also has non-automated pre-integration requirements. Please see the file CONTRIBUTING.md for details.

After integration, the commit message for the final commit will be:

8349139: C2: Div looses dependency on condition that guarantees divisor not zero in counted loop

Reviewed-by: chagedorn, epeter, qamai

You can use pull request commands such as /summary, /contributor and /issue to adjust it as needed.

At the time when this comment was updated there had been 1 new commit pushed to the master branch:

  • 290d24d: 8355400: Better git detection in update_copyright_year.sh

Please see this link for an up-to-date comparison between the source branch of this pull request and the master branch.
As there are no conflicts, your changes will automatically be rebased on top of these commits when integrating. If you prefer to avoid this automatic rebasing, please check the documentation for the /integrate command for further details.

➡️ To integrate this PR with the above commit message to the master branch, type /integrate in a new comment.

@openjdk
Copy link

openjdk bot commented Feb 13, 2025

@rwestrel this pull request can not be integrated into master due to one or more merge conflicts. To resolve these merge conflicts and update this pull request you can run the following commands in the local repository for your personal fork:

git checkout JDK-8349139
git fetch https://git.openjdk.org/jdk.git master
git merge FETCH_HEAD
# resolve conflicts and follow the instructions given by git merge
git commit -m "Merge master"
git push

@openjdk openjdk bot added merge-conflict Pull request has merge conflict with target branch rfr Pull request is ready for review labels Feb 13, 2025
@openjdk
Copy link

openjdk bot commented Feb 13, 2025

@rwestrel The following label will be automatically applied to this pull request:

  • hotspot-compiler

When this pull request is ready to be reviewed, an "RFR" email will be sent to the corresponding mailing list. If you would like to change these labels, use the /label pull request command.

@openjdk openjdk bot added the hotspot-compiler hotspot-compiler-dev@openjdk.org label Feb 13, 2025
@mlbridge
Copy link

mlbridge bot commented Feb 13, 2025

Webrevs

@openjdk openjdk bot removed the merge-conflict Pull request has merge conflict with target branch label Feb 13, 2025
@merykitty
Copy link
Member

My understanding here is that when the backedge is removed, the loop head (which is a merge) is idealized out, and as a result, the Phi is idealized to its only live input. I think the idealization of the Phi is the issue here, the Phi is pinned at the control input it is at, so the result of the idealization cannot float freely. As a result, I propose fixing the idealization of Phi to become a CastNode that has UnknownControlDependency on its input. What do you think?

I think this may be true for other kind of merge points as well. For example, if you perform conditional elimination (the patch you have worked at) on this code:

if (v > 0) {
    int y;
    if (b) {
        y = v;
    } else {
        y = v + 1;
    }
    x / y;
}

Then we can be very clever and see that y cannot be 0 because it is a Phi. However, if we also later see that b == true, then the Phi is removed and the division x / v does not have a control input, which is wrong.

@rwestrel
Copy link
Contributor Author

My understanding here is that when the backedge is removed, the loop head (which is a merge) is idealized out, and as a result, the Phi is idealized to its only live input. I think the idealization of the Phi is the issue here, the Phi is pinned at the control input it is at, so the result of the idealization cannot float freely. As a result, I propose fixing the idealization of Phi to become a CastNode that has UnknownControlDependency on its input. What do you think?

For any Phi? This seems like an issue that's specific to the counted loop iv. I don't think we want to add CastII nodes unless we're sure they are needed.

I thought about adding the CastII when the loop backedge disappears but I think when this happens it's too late to find which of the Phi is the loop phi.

I think this may be true for other kind of merge points as well. For example, if you perform conditional elimination (the patch you have worked at) on this code:

Are you talking about https://bugs.openjdk.org/browse/JDK-8275202 ?
But then wouldn't we want to add the CastII only if one is needed, that is when that pass runs, so we don't end up with those casts all over the place?

@merykitty
Copy link
Member

For any Phi? This seems like an issue that's specific to the counted loop iv. I don't think we want to add CastII nodes unless we're sure they are needed.

I think it is probably because we are more aggressive with the type of loop phis. Conceptually, a Phi is pinned, and idealizing it into a floating node is incorrect. So, there may be issues lurking around due to this. We can introduce another phase that tries to remove all CastNode and pins all nodes that need that dependency (such as Div, loads, etc). What do you think?

@rwestrel
Copy link
Contributor Author

For any Phi? This seems like an issue that's specific to the counted loop iv. I don't think we want to add CastII nodes unless we're sure they are needed.

I think it is probably because we are more aggressive with the type of loop phis. Conceptually, a Phi is pinned, and idealizing it into a floating node is incorrect. So, there may be issues lurking around due to this. We can introduce another phase that tries to remove all CastNode and pins all nodes that need that dependency (such as Div, loads, etc). What do you think?

In general a Phi's type is the union of the types of its inputs. There's no narrowing happening at the Phi. So I don't think there's any implicit dependency from some floating node that uses the Phi on the Phi's Region.

Counted loops are a bit different: the loop's Phi is the union of the type of the value on loop entry and a narrowed type for the value flowing through the backedge. The loop exit condition is what narrows the type the value that flows along the backedge and, as a result, of the loop Phi.

Trouble occurs when the loop is cloned by pre/main/post. Then the Phi for the main or post loop inherits the type of the Phi before transformation, the one that depends on the loop exit condition. Say the pre loop runs iterations 0 to p and the main loop runs iteration p+1 to m. In the loop before transformation, to reach iteration p+1, we have to go through the backedge at least once. One pre/main/post loops are created, going through the backedge to reach iteration p+1 implies exiting the pre loop and passing the zero trip guard for the main loop. So the type of the main loop's Phi is dependent on the zero trip guard for the main loop which is why we need the CastII.

AFAICT, this issue really only exists for counted loop Phis and once some transformation has "unfolded" the loop exit test. Now that I think more about it, a similar issue may happen with peeling (I will look into that separately). But I don't think it's a generic issue that affects all Phis and as such it should be fixed by adding extra dependencies where they are needed.

@merykitty
Copy link
Member

Hmmm, may be you are right. I think adding a comment at PhiNode saying that people must not rely on it being pinned at the Region for dependencies would be a wise move, I can't think of any reason for that besides value narrowing right now but being pinned is a property of Phi regardless and we should tell people not to rely on this behaviour.

For this bug, I think a more general fix is to try to compare the type of the Phi with that of the input it is going to be replaced with. If the former is not wider than the latter then we add a CastNode, since the cast is only about value range, not strict dependency, we can use CarryDependency instead of UnconditionalDependency. Am I right?

@rwestrel
Copy link
Contributor Author

For this bug, I think a more general fix is to try to compare the type of the Phi with that of the input it is going to be replaced with. If the former is not wider than the latter then we add a CastNode, since the cast is only about value range, not strict dependency, we can use CarryDependency instead of UnconditionalDependency. Am I right?

I don't think so. Consider this test case:

ublic class TestMainLoopNoBackedgeFloatingDiv {
    public static void main(String[] args) {
        for (int i = 0; i < 20_000; i++) {
            test1(1000, 0, false);
            test1Helper(1000, 0, false, false);
        }
        test1(1, 0, false);
    }

    private static int test1(int stop, int res, boolean alwaysTrueInMain) {
        stop = Integer.max(stop, 1);
        res = test1Helper(stop, res, alwaysTrueInMain, true);
        return res;
    }

    private static int test1Helper(int stop, int res, boolean alwaysTrueInMain, boolean flag) {
        for (int i = stop; i >= 1; i--) {
            res = res / i;
            if (alwaysTrueInMain) {
                break;
            }
            alwaysTrueInMain = flag;
        }
        return res;
    }
}

It reproduces this issue and is actually a better test case because it doesn't even need StressGCM:

All we know about the loop Phi is that it's expected to be in [1, max]. That allows the removal of the control dependency on the Div node. pre/main/post loops are then created and then because alwaysTrueInMain is true in the main and post loops, the main and post loops loose there backedge. All that's left from their loop body is:

res = res / (i-1);

(one copy for each one). The 2 Div nodes are commoned and placed above the checks that were added to guard the main and post loops and it's always executed out of the pre loop. Depending on the value of stop, the test may execute the pre loop and what's left of the main or post loops or only the pre loop. With stop = 1, only the pre loop needs to be executed, but the Div is executed anyway and the crash occurs.

The type of the input to the main loop Phi is the same as the type of the loop Phi in this case.

Copy link
Contributor

@eme64 eme64 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks reasonable. I have a few questions / suggestions.
I'm running some testing, please ping me again in a day or two ;)

do {
i1 <<= i3;
} while (++i2 < 68);
for (i23 = 68; i23 > 2; otherPhi=i23-1, i23--) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is essencially the test from #3190, we only changed the 3 to a 2. This indicates that we need to probably slightly generalize the test. Can we maybe randomize the constant, just to get a little better coverage?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the other test became ineffective, and it would be a shame if the same happened to this one ;)

Comment on lines 6090 to 6091
// skip over the cast added by PhaseIdealLoop::cast_incr_before_loop() when pre/post/main loops are created because
// it can get in the way of type propagation
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be nice if you said more about how it can get in the way of type propagation. Why would we sometimes have uncast on and sometimes off? You may even have a quick comment about it at the use-site.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I improved the comment in the new commit.

initialize_assertion_predicates_for_post_loop(main_head, post_head, first_node_index_in_cloned_loop_body);
}
// CastII for the new post loop:
cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see it is added for the main and post loop. Why not for the pre loop?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type of the trip phi of the loop before pre/main/post is computed from the type of the init value (input 1 of the trip phi) and the limit input to the exit condition. The way the trip phi type is computed, it can't be narrower than the init value type. If the loop body has a Div node and its control dependency is cleared because the divisor is known not zero from the type of the trip phi, then the divisor computed from the init value is also not zero and if the backedge of the loop is removed, the Div node can float.

i.e.

for (int i = start; i < stop; i += stride) {
  v = x / i;
}

if i not zero, it's because its type is computed from start and start is not zero so, if, for some reason, the loop runs for a single iteration:

v = x/start;

can float as high as the control of start.

Same reasoning applies to the pre loop because the trip phi of that loop "includes" the whole type of the init value. But that doesn't work for the main (or post loop) because its trip phi gets its type from the loop before transformation and it captures the type of the init value for what is now the pre loop which is not the same as the type of the init value for the main (or post loop).

In the example above, let's say start has type [min, -1] , stop is 0 and stride is 1. i's type is [min, -1]. That doesn't include 0 so the Div is free to float. Now once pre/main/post loops are created, the type of the trip phi for the main loop is [min, -1]. Now let's say the main loop looses its back edge. The Div in the main loop can float and say the value for i out of the pre loop is 0. Now the floating Div from the main loop can trigger a fault.

@eme64
Copy link
Contributor

eme64 commented Feb 25, 2025

Ah, I only just now read the comments from @merykitty and you. Oops. Hmm.

Yes it seems that the CountedLoop trip phi is special. That's maybe not great to have such implicit assumptions laying around. But not sure what would have been the better alternative.

@rwestrel

It reproduces this issue and is actually a better test case because it doesn't even need StressGCM:

Are you saying this is another test? I'd really be happy if we had more tests for this case, because the current version seems fragile, since it is an almost perfect copy of a previous test that became ineffective this makes me even more nervous 😅

@rwestrel
Copy link
Contributor Author

For this bug, I think a more general fix is to try to compare the type of the Phi with that of the input it is going to be replaced with. If the former is not wider than the latter then we add a CastNode, since the cast is only about value range, not strict dependency, we can use CarryDependency instead of UnconditionalDependency. Am I right?

There's no CarryDependency. Is your question about RegularDependency or StrongDependency?

About the Phi type: I'm not sure I understood the comment correctly. Are you suggesting the fix shouldn't be triggered by pre/main/post insertion but rather whenever the test you mention passes? When then? igvn? Or are you suggesting to only apply the fix during pre/main/post insertion when the test you mention passes?

@rwestrel
Copy link
Contributor Author

@merykitty see above my late reply to your comments if you missed it.

@merykitty
Copy link
Member

@rwestrel I have thought about this issue for a while and come to the conclusion that we do depend on a loop phi being a pinned node when doing optimizations (e.g init <= iv < limit). As a result, it seems logical to insert a pinned cast here so that the Phi does not freely float away when the loop disappears. I agree with your patch then.

@rwestrel
Copy link
Contributor Author

Are you saying this is another test? I'd really be happy if we had more tests for this case, because the current version seems fragile, since it is an almost perfect copy of a previous test that became ineffective this makes me even more nervous 😅

I added that test case.

@rwestrel
Copy link
Contributor Author

@eme64 the PR is ready for reviews in case you have time.

Copy link
Contributor

@eme64 eme64 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this looks reasonable.

test/hotspot/jtreg/compiler/controldependency/TestDivDependentOnMainLoopGuard.java
In this test you could also randomize the 2 I commented on. Because in #3190 you had the same test but with a constant 3. A public static final int with a random value in a reasonable range could do the trick.

Comment on lines 28 to 31
* @run main/othervm -Xcomp -XX:-TieredCompilation -XX:CompileOnly=TestDivDependentOnMainLoopGuard::*
* -XX:+UnlockDiagnosticVMOptions -XX:+StressGCM -XX:StressSeed=139899009 TestDivDependentOnMainLoopGuard
* @run main/othervm -Xcomp -XX:-TieredCompilation -XX:CompileOnly=TestDivDependentOnMainLoopGuard::*
* -XX:+UnlockDiagnosticVMOptions -XX:+StressGCM TestDivDependentOnMainLoopGuard
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to have a run without some of the flags here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@eme64
Copy link
Contributor

eme64 commented Apr 11, 2025

Just submitted some more testing :)

@rwestrel
Copy link
Contributor Author

I think this looks reasonable.

test/hotspot/jtreg/compiler/controldependency/TestDivDependentOnMainLoopGuard.java In this test you could also randomize the 2 I commented on. Because in #3190 you had the same test but with a constant 3. A public static final int with a random value in a reasonable range could do the trick.

Updated the test. Does it look like what you had in mind?

@rwestrel
Copy link
Contributor Author

Just submitted some more testing :)

Thanks. Any update on test results? @eme64

@openjdk openjdk bot removed the rfr Pull request is ready for review label Apr 14, 2025
Copy link
Contributor

@eme64 eme64 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, except for the whitespace issue :)

* @run main/othervm -Xcomp -XX:-TieredCompilation -XX:CompileOnly=TestDivDependentOnMainLoopGuard::*
* -XX:+UnlockDiagnosticVMOptions -XX:+StressGCM TestDivDependentOnMainLoopGuard
* @run main/othervm -Xcomp -XX:CompileOnly=TestDivDependentOnMainLoopGuard::* TestDivDependentOnMainLoopGuard
*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
*

You got some whitespace issues here, we could just remove the line :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I missed that. Fixed now.

@openjdk openjdk bot added the rfr Pull request is ready for review label Apr 18, 2025
@rwestrel
Copy link
Contributor Author

@merykitty @eme64 thanks for the reviews.
Can one of you approve the latest change (with the extra whitespaces removed)?

Copy link
Contributor

@eme64 eme64 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks for the work @rwestrel 😊

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Apr 21, 2025
Copy link
Member

@chhagedorn chhagedorn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, too.

Nit: You should probably update the title: "divisor not null" -> "divisor not zero".

Comment on lines 6064 to 6072
// skip over the cast added by PhaseIdealLoop::cast_incr_before_loop() when pre/post/main loops are created because
// it can get in the way of type propagation. For instance, the index tested by an assert predicate, if the cast is
// not skipped over, could be (1):
// (AddI (CastII (AddI pre_loop_iv -2) int) 1)
// while without the cast, it is (2):
// (AddI (AddI pre_loop_iv -2) 1)
// which is be transformed to (3):
// (AddI pre_loop_iv -1)
// The compiler may be able to constant fold the assert predicate condition for (3) but not (1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// skip over the cast added by PhaseIdealLoop::cast_incr_before_loop() when pre/post/main loops are created because
// it can get in the way of type propagation. For instance, the index tested by an assert predicate, if the cast is
// not skipped over, could be (1):
// (AddI (CastII (AddI pre_loop_iv -2) int) 1)
// while without the cast, it is (2):
// (AddI (AddI pre_loop_iv -2) 1)
// which is be transformed to (3):
// (AddI pre_loop_iv -1)
// The compiler may be able to constant fold the assert predicate condition for (3) but not (1)
// skip over the cast added by PhaseIdealLoop::cast_incr_before_loop() when pre/post/main loops are created because
// it can get in the way of type propagation. For instance, the index tested by an Assertion Predicate, if the cast is
// not skipped over, could be (1):
// (AddI (CastII (AddI pre_loop_iv -2) int) 1)
// while without the cast, it is (2):
// (AddI (AddI pre_loop_iv -2) 1)
// which is be transformed to (3):
// (AddI pre_loop_iv -1)
// The compiler may be able to constant fold the Assertion Predicate condition for (3) but not (1)

@openjdk openjdk bot removed the ready Pull request is ready to be integrated label Apr 24, 2025
@rwestrel rwestrel changed the title 8349139: C2: Div looses dependency on condition that guarantees divisor not null in counted loop 8349139: C2: Div looses dependency on condition that guarantees divisor not zero in counted loop Apr 24, 2025
@rwestrel
Copy link
Contributor Author

Looks good to me, too.

Nit: You should probably update the title: "divisor not null" -> "divisor not zero".

Thanks for reviewing this. I made the changes you suggested.

Copy link
Member

@chhagedorn chhagedorn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update!

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Apr 24, 2025
@rwestrel
Copy link
Contributor Author

@chhagedorn thanks for the review.

@rwestrel
Copy link
Contributor Author

/integrate

@openjdk
Copy link

openjdk bot commented Apr 24, 2025

Going to push as commit be6e440.
Since your change was applied there has been 1 commit pushed to the master branch:

  • 290d24d: 8355400: Better git detection in update_copyright_year.sh

Your commit was automatically rebased without conflicts.

@openjdk openjdk bot added the integrated Pull request has been integrated label Apr 24, 2025
@openjdk openjdk bot closed this Apr 24, 2025
@openjdk openjdk bot removed ready Pull request is ready to be integrated rfr Pull request is ready for review labels Apr 24, 2025
@openjdk
Copy link

openjdk bot commented Apr 24, 2025

@rwestrel Pushed as commit be6e440.

💡 You may see a message that your pull request was closed with unmerged commits. This can be safely ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hotspot-compiler hotspot-compiler-dev@openjdk.org integrated Pull request has been integrated

Development

Successfully merging this pull request may close these issues.

4 participants