Add allowpermittedsubclassesremoval keep rule modifier

Bug: b/227160052
Change-Id: I0b964fcfc861655c206a43e6253edb825bd621cd
diff --git a/src/main/java/com/android/tools/r8/shaking/KeepClassInfo.java b/src/main/java/com/android/tools/r8/shaking/KeepClassInfo.java
index 9898d34..c199247 100644
--- a/src/main/java/com/android/tools/r8/shaking/KeepClassInfo.java
+++ b/src/main/java/com/android/tools/r8/shaking/KeepClassInfo.java
@@ -257,6 +257,11 @@
       return self();
     }
 
+    public Joiner allowPermittedSubclassesRemoval() {
+      builder.allowPermittedSubclassesRemoval();
+      return self();
+    }
+
     @Override
     public Joiner asClassJoiner() {
       return this;
diff --git a/src/main/java/com/android/tools/r8/shaking/ProguardConfigurationParser.java b/src/main/java/com/android/tools/r8/shaking/ProguardConfigurationParser.java
index bec7ae6..9d98730 100644
--- a/src/main/java/com/android/tools/r8/shaking/ProguardConfigurationParser.java
+++ b/src/main/java/com/android/tools/r8/shaking/ProguardConfigurationParser.java
@@ -1050,6 +1050,8 @@
             builder.getModifiersBuilder().setAllowsAccessModification(true);
           } else if (acceptString("repackage")) {
             builder.getModifiersBuilder().setAllowsRepackaging(true);
+          } else if (acceptString("permittedsubclassesremoval")) {
+            builder.getModifiersBuilder().setAllowsPermittedSubclassesRemoval(true);
           } else if (options.isTestingOptionsEnabled()) {
             if (acceptString("annotationremoval")) {
               builder.getModifiersBuilder().setAllowsAnnotationRemoval(true);
diff --git a/src/main/java/com/android/tools/r8/shaking/ProguardKeepRuleModifiers.java b/src/main/java/com/android/tools/r8/shaking/ProguardKeepRuleModifiers.java
index ec825c3..6073953 100644
--- a/src/main/java/com/android/tools/r8/shaking/ProguardKeepRuleModifiers.java
+++ b/src/main/java/com/android/tools/r8/shaking/ProguardKeepRuleModifiers.java
@@ -15,6 +15,7 @@
     private boolean allowsOptimization = false;
     private boolean allowsObfuscation = false;
     private boolean includeDescriptorClasses = false;
+    private boolean allowsPermittedSubclassesRemoval = false;
 
     private Builder() {}
 
@@ -61,6 +62,11 @@
       return this;
     }
 
+    public Builder setAllowsPermittedSubclassesRemoval(boolean allowsPermittedSubclassesRemoval) {
+      this.allowsPermittedSubclassesRemoval = allowsPermittedSubclassesRemoval;
+      return this;
+    }
+
     public void setIncludeDescriptorClasses(boolean includeDescriptorClasses) {
       this.includeDescriptorClasses = includeDescriptorClasses;
     }
@@ -73,7 +79,8 @@
           allowsShrinking,
           allowsOptimization,
           allowsObfuscation,
-          includeDescriptorClasses);
+          includeDescriptorClasses,
+          allowsPermittedSubclassesRemoval);
     }
   }
 
@@ -84,6 +91,7 @@
   public final boolean allowsOptimization;
   public final boolean allowsObfuscation;
   public final boolean includeDescriptorClasses;
+  public final boolean allowsPermittedSubclassesRemoval;
 
   private ProguardKeepRuleModifiers(
       boolean allowsAccessModification,
@@ -92,7 +100,8 @@
       boolean allowsShrinking,
       boolean allowsOptimization,
       boolean allowsObfuscation,
-      boolean includeDescriptorClasses) {
+      boolean includeDescriptorClasses,
+      boolean allowsPermittedSubclassesRemoval) {
     this.allowsAccessModification = allowsAccessModification;
     this.allowsAnnotationRemoval = allowsAnnotationRemoval;
     this.allowsRepackaging = allowsRepackaging;
@@ -100,6 +109,7 @@
     this.allowsOptimization = allowsOptimization;
     this.allowsObfuscation = allowsObfuscation;
     this.includeDescriptorClasses = includeDescriptorClasses;
+    this.allowsPermittedSubclassesRemoval = allowsPermittedSubclassesRemoval;
   }
 
   /**
@@ -116,7 +126,8 @@
         && allowsObfuscation
         && allowsOptimization
         && allowsShrinking
-        && !includeDescriptorClasses;
+        && !includeDescriptorClasses
+        && allowsPermittedSubclassesRemoval;
   }
 
   @Override
@@ -131,7 +142,8 @@
         && allowsShrinking == that.allowsShrinking
         && allowsOptimization == that.allowsOptimization
         && allowsObfuscation == that.allowsObfuscation
-        && includeDescriptorClasses == that.includeDescriptorClasses;
+        && includeDescriptorClasses == that.includeDescriptorClasses
+        && allowsPermittedSubclassesRemoval == that.allowsPermittedSubclassesRemoval;
   }
 
   @Override
@@ -143,7 +155,8 @@
         allowsShrinking,
         allowsOptimization,
         allowsObfuscation,
-        includeDescriptorClasses);
+        includeDescriptorClasses,
+        allowsPermittedSubclassesRemoval);
   }
 
   @Override
@@ -156,6 +169,7 @@
     appendWithComma(builder, allowsShrinking, "allowshrinking");
     appendWithComma(builder, allowsOptimization, "allowoptimization");
     appendWithComma(builder, includeDescriptorClasses, "includedescriptorclasses");
+    appendWithComma(builder, allowsPermittedSubclassesRemoval, "allowpermittedsubclassesremoval");
     return builder.toString();
   }
 
diff --git a/src/main/java/com/android/tools/r8/shaking/RootSetUtils.java b/src/main/java/com/android/tools/r8/shaking/RootSetUtils.java
index 8678717..afe4006 100644
--- a/src/main/java/com/android/tools/r8/shaking/RootSetUtils.java
+++ b/src/main/java/com/android/tools/r8/shaking/RootSetUtils.java
@@ -1665,6 +1665,16 @@
         includeDescriptorClasses(item, keepRule, preconditionEvent);
         context.markAsUsed();
       }
+
+      if (item.isProgramClass()
+          && appView.options().isKeepPermittedSubclassesEnabled()
+          && !modifiers.allowsPermittedSubclassesRemoval) {
+        dependentMinimumKeepInfo
+            .getOrCreateMinimumKeepInfoFor(preconditionEvent, item.getReference())
+            .asClassJoiner()
+            .disallowPermittedSubclassesRemoval();
+        context.markAsUsed();
+      }
     }
 
     private boolean isRepackagingDisallowed(
diff --git a/src/test/java/com/android/tools/r8/desugar/sealed/SealedClassesTestAllowPermittedSubclassesRemovalTest.java b/src/test/java/com/android/tools/r8/desugar/sealed/SealedClassesTestAllowPermittedSubclassesRemovalTest.java
new file mode 100644
index 0000000..c220e9d
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/sealed/SealedClassesTestAllowPermittedSubclassesRemovalTest.java
@@ -0,0 +1,99 @@
+// Copyright (c) 2023, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.desugar.sealed;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isPresentAndRenamed;
+import static junit.framework.Assert.assertEquals;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestBuilder;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.TestRuntime.CfVm;
+import com.android.tools.r8.utils.StringUtils;
+import com.android.tools.r8.utils.codeinspector.ClassSubject;
+import com.android.tools.r8.utils.codeinspector.CodeInspector;
+import com.android.tools.r8.utils.codeinspector.Matchers;
+import com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class SealedClassesTestAllowPermittedSubclassesRemovalTest extends TestBase {
+
+  @Parameter(0)
+  public TestParameters parameters;
+
+  static final String EXPECTED = StringUtils.lines("Success!");
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimes().withAllApiLevelsAlsoForCf().build();
+  }
+
+  private void addTestClasses(TestBuilder<?, ?> builder) throws Exception {
+    builder
+        .addProgramClasses(TestClass.class, Sub1.class, Sub2.class)
+        .addProgramClassFileData(getTransformedClasses());
+  }
+
+  private void inspect(CodeInspector inspector) {
+    ClassSubject clazz = inspector.clazz(Super.class);
+    assertThat(clazz, Matchers.isPresentAndNotRenamed());
+    ClassSubject sub1 = inspector.clazz(Sub1.class);
+    ClassSubject sub2 = inspector.clazz(Sub2.class);
+    assertThat(sub1, isPresentAndRenamed());
+    assertThat(sub2, isPresentAndRenamed());
+    assertEquals(
+        parameters.isCfRuntime()
+            ? ImmutableList.of(sub1.asTypeSubject(), sub2.asTypeSubject())
+            : ImmutableList.of(),
+        clazz.getFinalPermittedSubclassAttributes());
+  }
+
+  @Test
+  public void testR8() throws Exception {
+    parameters.assumeR8TestParameters();
+    testForR8(parameters.getBackend())
+        .apply(this::addTestClasses)
+        .setMinApi(parameters)
+        .addKeepAttributePermittedSubclasses()
+        .addKeepRules("-keep,allowpermittedsubclassesremoval class " + Super.class.getTypeName())
+        .addKeepClassRulesWithAllowObfuscation(Sub1.class, Sub2.class)
+        .addKeepMainRule(TestClass.class)
+        .compile()
+        .inspect(this::inspect)
+        .run(parameters.getRuntime(), TestClass.class)
+        .applyIf(
+            !parameters.isCfRuntime() || parameters.asCfRuntime().isNewerThanOrEqual(CfVm.JDK17),
+            r -> r.assertSuccessWithOutput(EXPECTED),
+            r -> r.assertFailureWithErrorThatThrows(UnsupportedClassVersionError.class));
+  }
+
+  public byte[] getTransformedClasses() throws Exception {
+    return transformer(Super.class)
+        .setPermittedSubclasses(Super.class, Sub1.class, Sub2.class)
+        .transform();
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      new Sub1();
+      new Sub2();
+      System.out.println("Success!");
+    }
+  }
+
+  abstract static class Super /* permits Sub1, Sub2 */ {}
+
+  static class Sub1 extends Super {}
+
+  static class Sub2 extends Super {}
+}