1 /*
  2  * Copyright (c) 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.internal;
 27 
 28 import java.util.ArrayList;
 29 import java.util.HashMap;
 30 import java.util.List;
 31 import java.util.Map;
 32 import java.util.Optional;
 33 import java.util.function.Function;
 34 
 35 import jdk.incubator.code.Block;
 36 import jdk.incubator.code.Body;
 37 import jdk.incubator.code.Op;
 38 import jdk.incubator.code.Value;
 39 import jdk.incubator.code.dialect.core.CoreOp;
 40 import jdk.incubator.code.dialect.java.JavaOp;
 41 import jdk.incubator.code.dialect.java.JavaType;
 42 import jdk.incubator.code.dialect.java.PrimitiveType;
 43 
 44 public final class ConstantValueAnalysis {
 45     private final Function<Block, List<List<Value>>> incomingArguments;
 46     private final Map<Value, Optional<Object>> cache = new HashMap<>();
 47 
 48     public ConstantValueAnalysis(Function<Block, List<List<Value>>> incomingArguments) {
 49         this.incomingArguments = incomingArguments;
 50     }
 51 
 52     public ConstantValueAnalysis() {
 53         this.incomingArguments = _ -> List.of();
 54     }
 55 
 56     void clearUnknowns() {
 57         cache.values().removeIf(Optional::isEmpty);
 58     }
 59 
 60     public Optional<Object> evaluate(Value value) {
 61         if (value == null
 62                 || !(value.type() instanceof PrimitiveType && !value.type().equals(JavaType.VOID)
 63                 || value.type().equals(JavaType.J_L_STRING))) {
 64             return Optional.empty();
 65         }
 66         Optional<Object> cached = cache.get(value);
 67         if (cached != null) {
 68             return cached;
 69         }
 70         cache.put(value, Optional.empty());
 71         Optional<Object> resultValue = switch (value) {
 72             case Block.Parameter parameter -> {
 73                 List<List<Value>> incoming = incomingArguments.apply(parameter.declaringBlock());
 74                 if (incoming.isEmpty()) {
 75                     yield Optional.empty();
 76                 }
 77                 Object agreed = null;
 78                 for (List<Value> arguments : incoming) {
 79                     Optional<Object> constant = evaluate(arguments.get(parameter.index()));
 80                     if (constant.isEmpty()) {
 81                         yield Optional.empty();
 82                     }
 83                     Object candidate = constant.orElseThrow();
 84                     if (agreed != null && !agreed.equals(candidate)) {
 85                         yield Optional.empty();
 86                     }
 87                     agreed = candidate;
 88                 }
 89                 yield Optional.of(agreed);
 90             }
 91             case Op.Result result ->
 92                 switch (result.op()) {
 93                     case CoreOp.ConstantOp constant when isConstantValue(constant.value()) ->
 94                             Optional.of(constant.value() instanceof String s ? s.intern() : constant.value());
 95                     case JavaOp.ArithmeticOperation _, JavaOp.ConvOp _ -> {
 96                         List<Object> operands = new ArrayList<>(result.op().operands().size());
 97                         for (Value operand : result.op().operands()) {
 98                             Optional<Object> constant = evaluate(operand);
 99                             if (constant.isEmpty()) {
100                                 yield Optional.empty();
101                             }
102                             operands.add(constant.orElseThrow());
103                         }
104                         try {
105                             yield Optional.ofNullable(ArithmeticAndConvOpImpls.evaluate(result.op(), operands));
106                         } catch (ArithmeticException _) {
107                             yield Optional.empty();
108                         }
109                     }
110                     case JavaOp.CastOp co when value.type().equals(JavaType.J_L_STRING) ->
111                         evaluate(co.operands().getFirst()).filter(String.class::isInstance);
112                     case JavaOp.ConcatOp co ->
113                             co.operands().stream().map(this::evaluate)
114                                     .reduce((r, e) -> r.flatMap(a -> e.map(b -> a.toString() + b)))
115                                     .get()
116                                     .map(s -> s.toString().intern());
117                     case JavaOp.ConditionalExpressionOp co -> {
118                         Optional<Object> p = yieldValue(co.predicateBody());
119                         Optional<Object> t = yieldValue(co.trueBody());
120                         Optional<Object> f = yieldValue(co.falseBody());
121                         if (p.isEmpty() || t.isEmpty() || f.isEmpty()) {
122                             yield Optional.empty();
123                         }
124                         yield ((Boolean) p.get()) ? t : f;
125                     }
126                     case JavaOp.ConditionalOrOp co -> co.bodies().stream().map(this::yieldValue)
127                             .reduce((r, e) -> r.flatMap(a -> e.map(b -> (Boolean) a | (Boolean) b))).get();
128                     case JavaOp.ConditionalAndOp co -> co.bodies().stream().map(this::yieldValue)
129                             .reduce((r, e) -> r.flatMap(a -> e.map(b -> (Boolean) a & (Boolean) b))).get();
130                     default ->  Optional.empty();
131                 };
132         };
133         cache.put(value, resultValue);
134         return resultValue;
135     }
136 
137     public Boolean booleanValue(Value value) {
138         return evaluate(value).filter(Boolean.class::isInstance).map(Boolean.class::cast).orElse(null);
139     }
140 
141     private Optional<Object> yieldValue(Body body) {
142         return body.blocks().size() == 1 && body.entryBlock().terminatingOp() instanceof CoreOp.YieldOp yield
143                 ? evaluate(yield.yieldValue())
144                 : Optional.empty();
145     }
146 
147     private static boolean isConstantValue(Object o) {
148         return switch (o) {
149             case String _ -> true;
150             case Boolean _, Byte _, Short _, Character _, Integer _, Long _, Float _, Double _ -> true;
151             case null, default -> false;
152         };
153     }
154 }