001/*
002 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation.
008 *
009 * This code is distributed in the hope that it will be useful, but WITHOUT
010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
011 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
012 * version 2 for more details (a copy is included in the LICENSE file that
013 * accompanied this code).
014 *
015 * You should have received a copy of the GNU General Public License version
016 * 2 along with this work; if not, write to the Free Software Foundation,
017 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
018 *
019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
020 * or visit www.oracle.com if you need additional information or have any
021 * questions.
022 */
023package com.oracle.graal.lir;
024
025import java.util.*;
026
027/**
028 * A buffer to enqueue updates to a list. This avoids frequent re-sizing of the list and copying of
029 * list elements when insertions are done at multiple positions of the list. Additionally, it
030 * ensures that the list is not modified while it is, e.g., iterated, and instead only modified once
031 * after the iteration is done.
032 * <p>
033 * The buffer uses internal data structures to store the enqueued updates. To avoid allocations, a
034 * buffer can be re-used. Call the methods in the following order: {@link #init}, {@link #append},
035 * {@link #append}, ..., {@link #finish()}, {@link #init}, ...
036 * <p>
037 * Note: This class does not depend on LIRInstruction, so we could make it a generic utility class.
038 */
039public final class LIRInsertionBuffer {
040
041    /**
042     * The lir list where ops of this buffer should be inserted later (null when uninitialized).
043     */
044    private List<LIRInstruction> lir;
045
046    /**
047     * List of insertion points. index and count are stored alternately: indexAndCount[i * 2]: the
048     * index into lir list where "count" ops should be inserted indexAndCount[i * 2 + 1]: the number
049     * of ops to be inserted at index
050     */
051    private int[] indexAndCount;
052    private int indexAndCountSize;
053
054    /**
055     * The LIROps to be inserted.
056     */
057    private final List<LIRInstruction> ops;
058
059    public LIRInsertionBuffer() {
060        indexAndCount = new int[8];
061        ops = new ArrayList<>(4);
062    }
063
064    /**
065     * Initialize this buffer. This method must be called before using {@link #append}.
066     */
067    public void init(List<LIRInstruction> newLir) {
068        assert !initialized() : "already initialized";
069        assert indexAndCountSize == 0 && ops.size() == 0;
070        this.lir = newLir;
071    }
072
073    public boolean initialized() {
074        return lir != null;
075    }
076
077    public List<LIRInstruction> lirList() {
078        return lir;
079    }
080
081    /**
082     * Enqueue a new instruction that will be appended to the instruction list when
083     * {@link #finish()} is called. The new instruction is added <b>before</b> the existing
084     * instruction with the given index. This method can only be called with increasing values of
085     * index, e.g., once an instruction was appended with index 4, subsequent instructions can only
086     * be appended with index 4 or higher.
087     */
088    public void append(int index, LIRInstruction op) {
089        int i = numberOfInsertionPoints() - 1;
090        if (i < 0 || indexAt(i) < index) {
091            appendNew(index, 1);
092        } else {
093            assert indexAt(i) == index : "can append LIROps in ascending order only";
094            assert countAt(i) > 0 : "check";
095            setCountAt(i, countAt(i) + 1);
096        }
097        ops.add(op);
098
099        assert verify();
100    }
101
102    /**
103     * Append all enqueued instructions to the instruction list. After that, {@link #init(List)} can
104     * be called again to re-use this buffer.
105     */
106    public void finish() {
107        if (ops.size() > 0) {
108            int n = lir.size();
109            // increase size of instructions list
110            for (int i = 0; i < ops.size(); i++) {
111                lir.add(null);
112            }
113            // insert ops from buffer into instructions list
114            int opIndex = ops.size() - 1;
115            int ipIndex = numberOfInsertionPoints() - 1;
116            int fromIndex = n - 1;
117            int toIndex = lir.size() - 1;
118            while (ipIndex >= 0) {
119                int index = indexAt(ipIndex);
120                // make room after insertion point
121                while (fromIndex >= index) {
122                    lir.set(toIndex--, lir.get(fromIndex--));
123                }
124                // insert ops from buffer
125                for (int i = countAt(ipIndex); i > 0; i--) {
126                    lir.set(toIndex--, ops.get(opIndex--));
127                }
128                ipIndex--;
129            }
130            indexAndCountSize = 0;
131            ops.clear();
132        }
133        lir = null;
134    }
135
136    private void appendNew(int index, int count) {
137        int oldSize = indexAndCountSize;
138        int newSize = oldSize + 2;
139        if (newSize > this.indexAndCount.length) {
140            indexAndCount = Arrays.copyOf(indexAndCount, newSize * 2);
141        }
142        indexAndCount[oldSize] = index;
143        indexAndCount[oldSize + 1] = count;
144        this.indexAndCountSize = newSize;
145    }
146
147    private void setCountAt(int i, int value) {
148        indexAndCount[(i << 1) + 1] = value;
149    }
150
151    private int numberOfInsertionPoints() {
152        assert indexAndCount.length % 2 == 0 : "must have a count for each index";
153        return indexAndCountSize >> 1;
154    }
155
156    private int indexAt(int i) {
157        return indexAndCount[(i << 1)];
158    }
159
160    private int countAt(int i) {
161        return indexAndCount[(i << 1) + 1];
162    }
163
164    private boolean verify() {
165        int sum = 0;
166        int prevIdx = -1;
167
168        for (int i = 0; i < numberOfInsertionPoints(); i++) {
169            assert prevIdx < indexAt(i) : "index must be ordered ascending";
170            sum += countAt(i);
171        }
172        assert sum == ops.size() : "wrong total sum";
173        return true;
174    }
175}