1 /*
   2  * Copyright (c) 2009, 2012, 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  */
  23 package org.graalvm.compiler.lir.alloc.lsra;
  24 
  25 import static jdk.vm.ci.code.ValueUtil.asRegister;
  26 import static jdk.vm.ci.code.ValueUtil.isRegister;
  27 
  28 import java.util.ArrayList;
  29 import java.util.EnumSet;
  30 
  31 import org.graalvm.compiler.core.common.cfg.AbstractBlockBase;
  32 import org.graalvm.compiler.core.common.cfg.BlockMap;
  33 import org.graalvm.compiler.debug.DebugContext;
  34 import org.graalvm.compiler.debug.GraalError;
  35 import org.graalvm.compiler.debug.Indent;
  36 import org.graalvm.compiler.lir.InstructionValueConsumer;
  37 import org.graalvm.compiler.lir.LIRInstruction;
  38 import org.graalvm.compiler.lir.LIRInstruction.OperandFlag;
  39 import org.graalvm.compiler.lir.LIRInstruction.OperandMode;
  40 
  41 import jdk.vm.ci.code.Register;
  42 import jdk.vm.ci.meta.Value;
  43 
  44 /**
  45  */
  46 final class RegisterVerifier {
  47 
  48     LinearScan allocator;
  49     ArrayList<AbstractBlockBase<?>> workList; // all blocks that must be processed
  50     BlockMap<Interval[]> savedStates; // saved information of previous check
  51 
  52     // simplified access to methods of LinearScan
  53     Interval intervalAt(Value operand) {
  54         return allocator.intervalFor(operand);
  55     }
  56 
  57     // currently, only registers are processed
  58     int stateSize() {
  59         return allocator.maxRegisterNumber() + 1;
  60     }
  61 
  62     // accessors
  63     Interval[] stateForBlock(AbstractBlockBase<?> block) {
  64         return savedStates.get(block);
  65     }
  66 
  67     void setStateForBlock(AbstractBlockBase<?> block, Interval[] savedState) {
  68         savedStates.put(block, savedState);
  69     }
  70 
  71     void addToWorkList(AbstractBlockBase<?> block) {
  72         if (!workList.contains(block)) {
  73             workList.add(block);
  74         }
  75     }
  76 
  77     RegisterVerifier(LinearScan allocator) {
  78         this.allocator = allocator;
  79         workList = new ArrayList<>(16);
  80         this.savedStates = new BlockMap<>(allocator.getLIR().getControlFlowGraph());
  81 
  82     }
  83 
  84     @SuppressWarnings("try")
  85     void verify(AbstractBlockBase<?> start) {
  86         DebugContext debug = allocator.getDebug();
  87         try (DebugContext.Scope s = debug.scope("RegisterVerifier")) {
  88             // setup input registers (method arguments) for first block
  89             Interval[] inputState = new Interval[stateSize()];
  90             setStateForBlock(start, inputState);
  91             addToWorkList(start);
  92 
  93             // main loop for verification
  94             do {
  95                 AbstractBlockBase<?> block = workList.get(0);
  96                 workList.remove(0);
  97 
  98                 processBlock(block);
  99             } while (!workList.isEmpty());
 100         }
 101     }
 102 
 103     @SuppressWarnings("try")
 104     private void processBlock(AbstractBlockBase<?> block) {
 105         DebugContext debug = allocator.getDebug();
 106         try (Indent indent = debug.logAndIndent("processBlock B%d", block.getId())) {
 107             // must copy state because it is modified
 108             Interval[] inputState = copy(stateForBlock(block));
 109 
 110             try (Indent indent2 = debug.logAndIndent("Input-State of intervals:")) {
 111                 printState(inputState);
 112             }
 113 
 114             // process all operations of the block
 115             processOperations(block, inputState);
 116 
 117             try (Indent indent2 = debug.logAndIndent("Output-State of intervals:")) {
 118                 printState(inputState);
 119             }
 120 
 121             // iterate all successors
 122             for (AbstractBlockBase<?> succ : block.getSuccessors()) {
 123                 processSuccessor(succ, inputState);
 124             }
 125         }
 126     }
 127 
 128     protected void printState(Interval[] inputState) {
 129         DebugContext debug = allocator.getDebug();
 130         for (int i = 0; i < stateSize(); i++) {
 131             Register reg = allocator.getRegisters().get(i);
 132             assert reg.number == i;
 133             if (inputState[i] != null) {
 134                 debug.log(" %6s %4d  --  %s", reg, inputState[i].operandNumber, inputState[i]);
 135             } else {
 136                 debug.log(" %6s   __", reg);
 137             }
 138         }
 139     }
 140 
 141     private void processSuccessor(AbstractBlockBase<?> block, Interval[] inputState) {
 142         DebugContext debug = allocator.getDebug();
 143         Interval[] savedState = stateForBlock(block);
 144 
 145         if (savedState != null) {
 146             // this block was already processed before.
 147             // check if new inputState is consistent with savedState
 148 
 149             boolean savedStateCorrect = true;
 150             for (int i = 0; i < stateSize(); i++) {
 151                 if (inputState[i] != savedState[i]) {
 152                     // current inputState and previous savedState assume a different
 153                     // interval in this register . assume that this register is invalid
 154                     if (savedState[i] != null) {
 155                         // invalidate old calculation only if it assumed that
 156                         // register was valid. when the register was already invalid,
 157                         // then the old calculation was correct.
 158                         savedStateCorrect = false;
 159                         savedState[i] = null;
 160 
 161                         debug.log("processSuccessor B%d: invalidating slot %d", block.getId(), i);
 162                     }
 163                 }
 164             }
 165 
 166             if (savedStateCorrect) {
 167                 // already processed block with correct inputState
 168                 debug.log("processSuccessor B%d: previous visit already correct", block.getId());
 169             } else {
 170                 // must re-visit this block
 171                 debug.log("processSuccessor B%d: must re-visit because input state changed", block.getId());
 172                 addToWorkList(block);
 173             }
 174 
 175         } else {
 176             // block was not processed before, so set initial inputState
 177             debug.log("processSuccessor B%d: initial visit", block.getId());
 178 
 179             setStateForBlock(block, copy(inputState));
 180             addToWorkList(block);
 181         }
 182     }
 183 
 184     static Interval[] copy(Interval[] inputState) {
 185         return inputState.clone();
 186     }
 187 
 188     static void statePut(DebugContext debug, Interval[] inputState, Value location, Interval interval) {
 189         if (location != null && isRegister(location)) {
 190             Register reg = asRegister(location);
 191             int regNum = reg.number;
 192             if (interval != null) {
 193                 debug.log("%s = %s", reg, interval.operand);
 194             } else if (inputState[regNum] != null) {
 195                 debug.log("%s = null", reg);
 196             }
 197 
 198             inputState[regNum] = interval;
 199         }
 200     }
 201 
 202     static boolean checkState(AbstractBlockBase<?> block, LIRInstruction op, Interval[] inputState, Value operand, Value reg, Interval interval) {
 203         if (reg != null && isRegister(reg)) {
 204             if (inputState[asRegister(reg).number] != interval) {
 205                 throw new GraalError(
 206                                 "Error in register allocation: operation (%s) in block %s expected register %s (operand %s) to contain the value of interval %s but data-flow says it contains interval %s",
 207                                 op, block, reg, operand, interval, inputState[asRegister(reg).number]);
 208             }
 209         }
 210         return true;
 211     }
 212 
 213     void processOperations(AbstractBlockBase<?> block, final Interval[] inputState) {
 214         ArrayList<LIRInstruction> ops = allocator.getLIR().getLIRforBlock(block);
 215         DebugContext debug = allocator.getDebug();
 216         InstructionValueConsumer useConsumer = new InstructionValueConsumer() {
 217 
 218             @Override
 219             public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
 220                 // we skip spill moves inserted by the spill position optimization
 221                 if (LinearScan.isVariableOrRegister(operand) && allocator.isProcessed(operand) && op.id() != LinearScan.DOMINATOR_SPILL_MOVE_ID) {
 222                     Interval interval = intervalAt(operand);
 223                     if (op.id() != -1) {
 224                         interval = interval.getSplitChildAtOpId(op.id(), mode, allocator);
 225                     }
 226 
 227                     assert checkState(block, op, inputState, interval.operand, interval.location(), interval.splitParent());
 228                 }
 229             }
 230         };
 231 
 232         InstructionValueConsumer defConsumer = (op, operand, mode, flags) -> {
 233             if (LinearScan.isVariableOrRegister(operand) && allocator.isProcessed(operand)) {
 234                 Interval interval = intervalAt(operand);
 235                 if (op.id() != -1) {
 236                     interval = interval.getSplitChildAtOpId(op.id(), mode, allocator);
 237                 }
 238 
 239                 statePut(debug, inputState, interval.location(), interval.splitParent());
 240             }
 241         };
 242 
 243         // visit all instructions of the block
 244         for (int i = 0; i < ops.size(); i++) {
 245             final LIRInstruction op = ops.get(i);
 246 
 247             if (debug.isLogEnabled()) {
 248                 debug.log("%s", op.toStringWithIdPrefix());
 249             }
 250 
 251             // check if input operands are correct
 252             op.visitEachInput(useConsumer);
 253             // invalidate all caller save registers at calls
 254             if (op.destroysCallerSavedRegisters()) {
 255                 for (Register r : allocator.getRegisterAllocationConfig().getRegisterConfig().getCallerSaveRegisters()) {
 256                     statePut(debug, inputState, r.asValue(), null);
 257                 }
 258             }
 259             op.visitEachAlive(useConsumer);
 260             // set temp operands (some operations use temp operands also as output operands, so
 261             // can't set them null)
 262             op.visitEachTemp(defConsumer);
 263             // set output operands
 264             op.visitEachOutput(defConsumer);
 265         }
 266     }
 267 }