/*
 * Renjin : JVM-based interpreter for the R language for the statistical analysis
 * Copyright Â© 2010-2019 BeDataDriven Groep B.V. and contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, a copy is available at
 * https://www.gnu.org/licenses/gpl-2.0.txt
 */
package org.renjin.gcc.peephole;

import org.renjin.repackaged.asm.Label;
import org.renjin.repackaged.asm.Type;
import org.renjin.repackaged.asm.tree.*;
import org.renjin.repackaged.asm.util.Textifier;
import org.renjin.repackaged.asm.util.TraceMethodVisitor;
import org.renjin.repackaged.guava.collect.Lists;
import org.renjin.repackaged.guava.collect.Sets;

import java.util.*;

/**
 * Optimizes generated bytecode by replacing groups of instructions with more space efficient representations.
 *
 * <p>These sorts of optimizations don't appear to have much impact on the performance of compiled
 * methods, but it can drastically reduce the size of the generated bytecode.</p>
 */
public class PeepholeOptimizer {

  public static PeepholeOptimizer INSTANCE = new PeepholeOptimizer();

  private List<PeepholeOptimization> optimizations = Lists.newArrayList();

  public PeepholeOptimizer() {
    optimizations.add(new StoreLoad());
    optimizations.add(new LoadLoad());
    optimizations.add(new IntegerIncrement());
    optimizations.add(new ConstantMath());
    optimizations.add(new ZeroComparison());
    optimizations.add(new ZeroAdd());
    optimizations.add(new ConstantBranch());
    optimizations.add(new PointerPlus());
    optimizations.add(new PointerAccess());
  }

  public void optimize(MethodNode methodNode) {

    methodNode.accept(new TraceMethodVisitor(new Textifier()));

    Set<Label> jumpTargets = findJumpTargets(methodNode);

    boolean changing;
    do {
      NodeIt it = new NodeIt(methodNode.instructions, jumpTargets);
      changing = false;
      do {
        for (PeepholeOptimization optimization : optimizations) {
          if (optimization.apply(it)) {
            changing = true;
          }
        }
      } while (it.next());

      if(propagateConstants(methodNode, jumpTargets)) {
        changing = true;
      }
    } while (changing);
  }


  private Set<Label> findJumpTargets(MethodNode methodNode) {
    Set<Label> targets = Sets.newHashSet();
    ListIterator<AbstractInsnNode> it = methodNode.instructions.iterator();
    while(it.hasNext()) {
      AbstractInsnNode node = it.next();
      if(node instanceof JumpInsnNode) {
        JumpInsnNode jumpNode = (JumpInsnNode) node;
        targets.add(jumpNode.label.getLabel());
      }
    }
    return targets;
  }


  private boolean propagateConstants(MethodNode methodNode, Set<Label> jumpTargets) {

    // First find all local variables which are stored only once
    Set<Integer> stores = new HashSet<>();
    Set<Integer> multipleStores = new HashSet<>();

    // Exclude parameters...
    int parameterIndex = 0;
    for (Type parameterType : Type.getArgumentTypes(methodNode.desc)) {
      for (int i = 0; i < parameterType.getSize(); i++) {
        multipleStores.add(parameterIndex++);
      }
    }
    NodeIt it = new NodeIt(methodNode.instructions, jumpTargets);
    do {
      if(it.matches(Pattern.ISTORE)) {
        VarInsnNode store = it.get(0);
        if(!stores.add(store.var)) {
          multipleStores.add(store.var);
        }
      } else if(it.matches(Pattern.IINC)) {
        IincInsnNode iinc = it.get(0);
        multipleStores.add(iinc.var);
      }
    } while(it.next());

    Set<Integer> singleStores = Sets.difference(stores, multipleStores);

    // Now find all constant single store
    Map<Integer, Integer> constantStores = new HashMap<>();
    it.reset();
    do {
      if(it.matches(Pattern.ICONST, Pattern.ISTORE)) {
        VarInsnNode store = it.get(1);
        if(singleStores.contains(store.var)) {
          int constantValue = Instructions.getInteger(it.get(0));
          constantStores.put(store.var, constantValue);
        }
      }
    } while (it.next());


    // And finally remove the constant stores and replace the loads with constants
    boolean changed = false;
    it.reset();
    do {
      if(it.matches(Pattern.ICONST, Pattern.ISTORE)) {
        VarInsnNode store = it.get(1);
        if(constantStores.containsKey(store.var)) {
          it.remove(2);
        }
      } else if(it.matches(Pattern.ILOAD)) {
        VarInsnNode load = it.get(0);
        Integer constantValue = constantStores.get(load.var);
        if(constantValue != null) {
          it.remove(1);
          it.insert(Instructions.constantNode(constantValue));
          changed = true;
        }
      }
    } while (it.next());

    return changed;
  }
}