1 /*
2 * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package jdk.incubator.code.dialect.core;
27
28 import jdk.incubator.code.*;
29 import jdk.incubator.code.dialect.java.JavaOp;
30 import jdk.incubator.code.dialect.java.JavaType;
31
32 import java.util.*;
33
34 /**
35 * A code model transformer that normalizes blocks.
36 * <p>
37 * Merges redundant blocks with their predecessors, those which are unconditionally
38 * branched to and have only one predecessor.
39 * <p>
40 * Removes unused block parameters.
41 * <p>
42 * Skips intermediate conditional branches that use a single constant boolean argument,
43 * directly redirecting to the target true or false branch based on the constant's value.
44 */
45 public final class NormalizeBlocksTransformer implements CodeTransformer {
46 final Set<Block> mergedBlocks = new HashSet<>();
47 final Map<Block, BitSet> adjustedBlocks = new HashMap<>();
48
49 private NormalizeBlocksTransformer() {
50 }
51
52 /**
53 * Transforms an operation, merging redundant blocks.
54 *
55 * @param op the operation to transform
56 * @param <O> the type of operation
57 * @return the transformed operation
58 */
59 @SuppressWarnings("unchecked")
60 public static <O extends Op> O transform(O op) {
61 return (O) op.transform(CodeContext.create(), new NormalizeBlocksTransformer());
62 }
63
64 @Override
65 public void acceptBlock(Block.Builder block, Block b) {
66 // Ignore merged block
67 if (!mergedBlocks.contains(b)) {
68 CodeTransformer.super.acceptBlock(block, b);
69 }
70 }
71
72 @Override
73 public Block.Builder acceptOp(Block.Builder b, Op op) {
74 switch (op) {
75 // Handle constant dispatch before generic merge.
76 // Boolean constants used only as dispatch arguments are dropped and generic merge cannot handle them.
77 case CoreOp.BranchOp bop when isPureConditionalDispatchingBlock(bop.branch().targetBlock())
78 && bop.branch().arguments().getFirst() instanceof Op.Result or
79 && or.op() instanceof CoreOp.ConstantOp cop -> {
80 // Skip intermediate conditional branch with constant boolean argument and re-target
81 // directly to the true or false branch, based on the constant value.
82 CoreOp.ConditionalBranchOp cbo = (CoreOp.ConditionalBranchOp)bop.branch().targetBlock().terminatingOp();
83 Block.Reference br = (Boolean)cop.value() ? cbo.trueBranch() : cbo.falseBranch();
84 // Remove the conditional dispatching block if all predecessor reference args are constants
85 if (bop.branch().targetBlock().predecessorReferences().stream()
86 .allMatch(r -> r.arguments().getFirst() instanceof Op.Result orr && orr.op() instanceof CoreOp.ConstantOp)) {
87 mergedBlocks.add(bop.branch().targetBlock());
88 if (br.targetBlock().predecessors().size() == 1) {
89 // Merge the successor's target block with this block
90 mergeBlock(b, br.targetBlock());
91 break;
92 }
93 }
94 b.add(CoreOp.branch(b.context().getReferenceOrCreate(br)));
95 }
96 case CoreOp.BranchOp bop when bop.branch().targetBlock().predecessors().size() == 1 -> {
97 // Merge the successor's target block with this block, and so on
98 // The terminal branch operation is replaced with the operations in the
99 // successor's target block
100 mergeBlock(b, bop);
101 }
102 case CoreOp.ConstantOp cop when cop.resultType().equals(JavaType.BOOLEAN)
103 && cop.result().uses().stream().allMatch(cr -> cr.op() instanceof CoreOp.BranchOp bop
104 && isPureConditionalDispatchingBlock(bop.branch().targetBlock())) -> {
105 // Remove boolean ConstantOp used purelly as BranchOp successor arguments to a conditional dispatching block
106 }
107 case JavaOp.ExceptionRegionEnter ere -> {
108 // Cannot remove block parameters from exception handlers
109 removeUnusedBlockParameters(b, ere.startReference());
110 b.add(op);
111 }
112 case JavaOp.ExceptionRegionExit ere -> {
113 // Cannot remove block parameters from exception handlers
114 removeUnusedBlockParameters(b, ere.endReference());
115 b.add(op);
116 }
117 case Op.Terminating _ -> {
118 for (Block.Reference successor : op.successors()) {
119 removeUnusedBlockParameters(b, successor);
120 }
121 b.add(op);
122 }
123 default -> {
124 b.add(op);
125 }
126 }
127 return b;
128 }
129
130 private static boolean isPureConditionalDispatchingBlock(Block b) {
131 return b.parameters().size() == 1
132 && b.parameters().getFirst().type().equals(JavaType.BOOLEAN)
133 && b.ops().size() == 1
134 && b.terminatingOp() instanceof CoreOp.ConditionalBranchOp cbo
135 && cbo.operands().getFirst() == b.parameters().getFirst()
136 && cbo.trueBranch().arguments().isEmpty()
137 && cbo.falseBranch().arguments().isEmpty();
138 }
139
140 // Remove any unused block parameters and successor arguments
141 private void removeUnusedBlockParameters(Block.Builder b, Block.Reference successor) {
142 Block target = successor.targetBlock();
143 BitSet unusedParameterIndexes = adjustedBlocks.computeIfAbsent(target,
144 k -> adjustBlock(b, k));
145 if (!unusedParameterIndexes.isEmpty()) {
146 adjustSuccessor(unusedParameterIndexes, b, successor);
147 }
148
149 }
150
151 // Remove any unused block parameters
152 BitSet adjustBlock(Block.Builder b, Block target) {
153 // Determine the indexes of unused block parameters
154 List<Block.Parameter> parameters = target.parameters();
155 BitSet unusedParameterIndexes = parameters.stream()
156 .filter(p -> p.uses().isEmpty())
157 .mapToInt(Block.Parameter::index)
158 .collect(BitSet::new, BitSet::set, BitSet::or);
159
160 if (!unusedParameterIndexes.isEmpty()) {
161 // Create a new output block and remap it to the target block,
162 // overriding any previous mapping
163 Block.Builder adjustedBlock = b.block();
164 b.context().mapBlock(target, adjustedBlock);
165
166 // Update and remap the output block parameters
167 for (int i = 0; i < parameters.size(); i++) {
168 if (!unusedParameterIndexes.get(i)) {
169 Block.Parameter parameter = parameters.get(i);
170 b.context().mapValue(
171 parameter,
172 adjustedBlock.parameter(parameter.type()));
173 }
174 }
175 }
176
177 return unusedParameterIndexes;
178 }
179
180 // Remove any unused successor arguments
181 void adjustSuccessor(BitSet unusedParameterIndexes, Block.Builder b, Block.Reference successor) {
182 // Create a new output successor and remap it
183 List<Value> arguments = new ArrayList<>();
184 for (int i = 0; i < successor.arguments().size(); i++) {
185 if (!unusedParameterIndexes.get(i)) {
186 arguments.add(b.context().getValue(successor.arguments().get(i)));
187 }
188 }
189 Block.Reference adjustedSuccessor = b.context().getBlock(successor.targetBlock())
190 .reference(arguments);
191 b.context().mapReference(successor, adjustedSuccessor);
192 }
193
194 void mergeBlock(Block.Builder b, CoreOp.BranchOp bop) {
195 Block.Reference reference = bop.branch();
196 Block successor = reference.targetBlock();
197 // Replace use of the successor's parameters with the reference's arguments
198 b.context().mapValues(successor.parameters(),
199 b.context().getValues(reference.arguments()));
200 mergeBlock(b, successor);
201 }
202
203 void mergeBlock(Block.Builder b, Block successor) {
204 mergedBlocks.add(successor);
205
206 // Merge non-terminal operations
207 for (int i = 0; i < successor.ops().size() - 1; i++) {
208 acceptOp(b, successor.ops().get(i));
209 }
210
211 // Check if subsequent successor block can be normalized
212 acceptOp(b, successor.terminatingOp());
213 }
214 }