1/*
2 * Copyright (c) 2014, 2015, 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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.graalvm.compiler.lir.constopt;
24
25import java.util.ArrayList;
26import java.util.List;
27import java.util.function.Consumer;
28
29import org.graalvm.compiler.core.common.cfg.AbstractBlockBase;
30import org.graalvm.compiler.lir.LIRInstruction;
31import org.graalvm.compiler.lir.StandardOp.LoadConstantOp;
32import org.graalvm.compiler.lir.Variable;
33
34import jdk.vm.ci.meta.Constant;
35import jdk.vm.ci.meta.Value;
36
37/**
38 * Represents def-use tree of a constant.
39 */
40class DefUseTree {
41    private final LoadConstantOp instruction;
42    private final AbstractBlockBase<?> block;
43    private final List<UseEntry> uses;
44
45    DefUseTree(LIRInstruction instruction, AbstractBlockBase<?> block) {
46        assert LoadConstantOp.isLoadConstantOp(instruction) : "Not a LoadConstantOp: " + instruction;
47        this.instruction = LoadConstantOp.asLoadConstantOp(instruction);
48        this.block = block;
49        this.uses = new ArrayList<>();
50    }
51
52    public Variable getVariable() {
53        return (Variable) instruction.getResult();
54    }
55
56    public Constant getConstant() {
57        return instruction.getConstant();
58    }
59
60    public LIRInstruction getInstruction() {
61        return (LIRInstruction) instruction;
62    }
63
64    public AbstractBlockBase<?> getBlock() {
65        return block;
66    }
67
68    @Override
69    public String toString() {
70        return "DefUseTree [" + instruction + "|" + block + "," + uses + "]";
71    }
72
73    public void addUsage(AbstractBlockBase<?> b, LIRInstruction inst, Value value) {
74        uses.add(new UseEntry(b, inst, value));
75    }
76
77    public int usageCount() {
78        return uses.size();
79    }
80
81    public void forEach(Consumer<? super UseEntry> action) {
82        uses.forEach(action);
83    }
84
85}
86