/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package analise;

import API.MiddlewareInterface;
import common.Instruction;
import common.Block;
import common.Code;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

/**
 *
 * @author lucas
 */
public class AnaliseDependenciaMiddleware implements MiddlewareInterface {

    int id = 0;
    protected Code target;
    protected Code blocosBasicos = new Code("Blocos.Basicos");

    public AnaliseDependenciaMiddleware() {

    }

    @Override
    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
//        Block bloco = c.Block();
        target = c;

        System.out.println("Chamada analise dependencia");

        for (Map.Entry<String, Block> entry : target.Blocks().entrySet()) {
            Block mips = entry.getValue();

            boolean first = true, isLabel, add;

            for (Instruction inst : mips.Instructions()) {

                isLabel = inst.eq("type", "label");

//            inst.Get("inst.bin"); pra acessar os atributos
//            inst.getint
                if (first || isLabel || inst.eq("type", "J") || inst.in("inst", new String[]{"beq", "bne", "blez", "bgtz", "bgez", "bltz"})) {
                    if (blocosBasicos.Block() != null) {
                        if (!isLabel) {
                            blocosBasicos.Block().Add(inst);
                        }
//                    System.out.println("blocosBasicos.Block().instructions > " + blocosBasicos.Block().instructions);
                        if (blocosBasicos.Block().instructions.size() == 0) {
                            blocosBasicos.stmts.remove(blocosBasicos.Block().getName());
                        }
                        blocosBasicos.CloseBlock();
                    }
                    blocosBasicos.OpenBlock("bloco." + (id++));
                    if (first) {
                        first = false;
//                    if (!isLabel) {
                        blocosBasicos.Block().Add(inst);
//                    }
                    }

//            } else if (inst.eq("type", "label")) {
//                System.out.println("Label:" + inst);
                } else {
                    blocosBasicos.Block().Add(inst);
                }
//            if (add) {;
//                blocosBasicos.Block().Add(inst);
//            }
            }
//        System.out.println("Print mips:" + mips.getName() + "\n" + mips.Instructions());
        }
        Post();
    }

    public void Post() {
        ArrayList<String> contextTable = new ArrayList<>();
        ArrayList<String> listaTrocar = new ArrayList<>();
        ArrayList<String> lw_sw_Table = new ArrayList<>();

        WriteTable writeBitmapTable = new WriteTable(5);
        WriteTable readsTable = new WriteTable(5);
        WriteTable nome = new WriteTable(5);
        WriteTable lol = new WriteTable(5);

        //Map valor, chave do bloco e suas instruções
        for (Map.Entry<String, Block> b : blocosBasicos.Blocks().entrySet()) {
            System.out.println("Bloco:" + b.getKey() + "\n" + b.getValue().Instructions());

//            Pega os valores dos registradores
            for (int i = 0; i < b.getValue().Instructions().size(); i++) {
                System.out.println(b.getValue().Instructions().get(i).Get("inst") + ": " + "RS: " + b.getValue().Instructions().get(i).Get("rs") + " RT: " + b.getValue().Instructions().get(i).Get("rt") + " RD: " + b.getValue().Instructions().get(i).Get("rd"));
//
                contextTable.add(b.getValue().Instructions().get(i).Get("rs"));
                contextTable.add(b.getValue().Instructions().get(i).Get("rt"));
                contextTable.add(b.getValue().Instructions().get(i).Get("rd"));
                for (int k = i + 1; k < b.getValue().Instructions().size(); k++) {

                    //WAW  RT == RT
                    if ((b.getValue().Instructions().get(i).Get("rt") == b.getValue().Instructions().get(k).Get("rt"))
                            && (b.getValue().Instructions().get(k).diferente("inst", "beq")
                            && b.getValue().Instructions().get(k).diferente("inst", "bne")
                            && b.getValue().Instructions().get(k).diferente("inst", "sb")
                            && b.getValue().Instructions().get(k).diferente("inst", "sh")
                            && b.getValue().Instructions().get(k).diferente("inst", "sw")
                            && b.getValue().Instructions().get(k).diferente("inst", "swcl")
                            && b.getValue().Instructions().get(k).diferente("inst", "add")
                            && b.getValue().Instructions().get(k).diferente("inst", "addu")
                            && b.getValue().Instructions().get(k).diferente("inst", "and")
                            && b.getValue().Instructions().get(k).diferente("inst", "div")
                            && b.getValue().Instructions().get(k).diferente("inst", "divu")
                            && b.getValue().Instructions().get(k).diferente("inst", "mult")
                            && b.getValue().Instructions().get(k).diferente("inst", "multu")
                            && b.getValue().Instructions().get(k).diferente("inst", "nor")
                            && b.getValue().Instructions().get(k).diferente("inst", "or")
                            && b.getValue().Instructions().get(k).diferente("inst", "sll")
                            && b.getValue().Instructions().get(k).diferente("inst", "sllv")
                            && b.getValue().Instructions().get(k).diferente("inst", "slt")
                            && b.getValue().Instructions().get(k).diferente("inst", "sltu")
                            && b.getValue().Instructions().get(k).diferente("inst", "sra")
                            && b.getValue().Instructions().get(k).diferente("inst", "srav")
                            && b.getValue().Instructions().get(k).diferente("inst", "srl")
                            && b.getValue().Instructions().get(k).diferente("inst", "srlv")
                            && b.getValue().Instructions().get(k).diferente("inst", "sub")
                            && b.getValue().Instructions().get(k).diferente("inst", "subu")
                            && b.getValue().Instructions().get(k).diferente("inst", "xor"))) {

                        //Registradores a serem trocados
                        listaTrocar.add(b.getValue().Instructions().get(k).Get("rt"));

                    }
                    //WAW CLASSICO RD == RD
                    if (b.getValue().Instructions().get(i).Get("rd") == b.getValue().Instructions().get(k).Get("rd")) {
                        listaTrocar.add(b.getValue().Instructions().get(k).Get("rd"));
                    }

                    if (b.getValue().Instructions().get(i).Get("rt") == b.getValue().Instructions().get(k).Get("rd")) {
                        listaTrocar.add(b.getValue().Instructions().get(k).Get("rd"));

                    }

                    //Caso em que o RT nao é destino 
                    if ((b.getValue().Instructions().get(i).Get("rs") == b.getValue().Instructions().get(k).Get("rt"))
                            && (b.getValue().Instructions().get(k).diferente("inst", "beq")
                            && b.getValue().Instructions().get(k).diferente("inst", "bne")
                            && b.getValue().Instructions().get(k).diferente("inst", "sb")
                            && b.getValue().Instructions().get(k).diferente("inst", "sh")
                            && b.getValue().Instructions().get(k).diferente("inst", "sw")
                            && b.getValue().Instructions().get(k).diferente("inst", "swcl")
                            && b.getValue().Instructions().get(k).diferente("inst", "add")
                            && b.getValue().Instructions().get(k).diferente("inst", "addu")
                            && b.getValue().Instructions().get(k).diferente("inst", "and")
                            && b.getValue().Instructions().get(k).diferente("inst", "div")
                            && b.getValue().Instructions().get(k).diferente("inst", "divu")
                            && b.getValue().Instructions().get(k).diferente("inst", "mult")
                            && b.getValue().Instructions().get(k).diferente("inst", "multu")
                            && b.getValue().Instructions().get(k).diferente("inst", "nor")
                            && b.getValue().Instructions().get(k).diferente("inst", "or")
                            && b.getValue().Instructions().get(k).diferente("inst", "sll")
                            && b.getValue().Instructions().get(k).diferente("inst", "sllv")
                            && b.getValue().Instructions().get(k).diferente("inst", "slt")
                            && b.getValue().Instructions().get(k).diferente("inst", "sltu")
                            && b.getValue().Instructions().get(k).diferente("inst", "sra")
                            && b.getValue().Instructions().get(k).diferente("inst", "srav")
                            && b.getValue().Instructions().get(k).diferente("inst", "srl")
                            && b.getValue().Instructions().get(k).diferente("inst", "srlv")
                            && b.getValue().Instructions().get(k).diferente("inst", "sub")
                            && b.getValue().Instructions().get(k).diferente("inst", "subu")
                            && b.getValue().Instructions().get(k).diferente("inst", "xor"))) {
                        listaTrocar.add(b.getValue().Instructions().get(k).Get("rt"));

                    }

                    if (b.getValue().Instructions().get(i).Get("rs") == b.getValue().Instructions().get(k).Get("rd")) {
                        listaTrocar.add(b.getValue().Instructions().get(k).Get("rd"));

                    }
                }

            }
            //Remove blank da contextTable
            contextTable.removeAll(Arrays.asList("", null));
            listaTrocar.removeAll(Arrays.asList("", null));

            //Remove repetições           
            listaTrocar = new ArrayList<>(new LinkedHashSet<>(listaTrocar));

            for (int i = 0; i < listaTrocar.size(); i++) {
                for (int j = contextTable.size() - 1; j >= 0; j--) {
                    if (listaTrocar.get(i) == contextTable.get(j)) {
                        if (contextTable.get(j).equals("zero")) {
                            contextTable.set(j, "r32");
                        }
                        if (contextTable.get(j).equals("at")) {
                            contextTable.set(j, "r33");
                        }
                        if (contextTable.get(j).equals("v0")) {
                            contextTable.set(j, "r34");
                        }
                        if (contextTable.get(j).equals("v1")) {
                            contextTable.set(j, "r35");
                        }
                        if (contextTable.get(j).equals("a0")) {
                            contextTable.set(j, "r36");
                        }
                        if (contextTable.get(j).equals("a1")) {
                            contextTable.set(j, "r37");
                        }
                        if (contextTable.get(j).equals("a2")) {
                            contextTable.set(j, "r38");
                        }
                        if (contextTable.get(j).equals("a3")) {
                            contextTable.set(j, "r39");
                        }
                        if (contextTable.get(j).equals("t0")) {
                            contextTable.set(j, "r40");
                        }
                        if (contextTable.get(j).equals("t1")) {
                            contextTable.set(j, "r41");
                        }
                        if (contextTable.get(j).equals("t2")) {
                            contextTable.set(j, "r42");
                        }
                        if (contextTable.get(j).equals("t3")) {
                            contextTable.set(j, "r43");
                        }
                        if (contextTable.get(j).equals("t4")) {
                            contextTable.set(j, "r44");
                        }
                        if (contextTable.get(j).equals("t5")) {
                            contextTable.set(j, "r45");
                        }
                        if (contextTable.get(j).equals("t6")) {
                            contextTable.set(j, "r46");
                        }
                        if (contextTable.get(j).equals("t7")) {
                            contextTable.set(j, "r47");
                        }
                        if (contextTable.get(j).equals("s0")) {
                            contextTable.set(j, "r48");
                        }
                        if (contextTable.get(j).equals("s1")) {
                            contextTable.set(j, "r49");
                        }
                        if (contextTable.get(j).equals("s2")) {
                            contextTable.set(j, "r50");
                        }
                        if (contextTable.get(j).equals("s3")) {
                            contextTable.set(j, "r51");
                        }
                        if (contextTable.get(j).equals("s4")) {
                            contextTable.set(j, "r52");
                        }
                        if (contextTable.get(j).equals("s5")) {
                            contextTable.set(j, "r53");
                        }
                        if (contextTable.get(j).equals("s6")) {
                            contextTable.set(j, "r54");
                        }
                        if (contextTable.get(j).equals("s7")) {
                            contextTable.set(j, "r55");
                        }
                        if (contextTable.get(j).equals("t8")) {
                            contextTable.set(j, "r56");
                        }
                        if (contextTable.get(j).equals("t9")) {
                            contextTable.set(j, "r57");
                        }
                        if (contextTable.get(j).equals("k0")) {
                            contextTable.set(j, "r58");
                        }
                        if (contextTable.get(j).equals("k1")) {
                            contextTable.set(j, "r59");
                        }
                        if (contextTable.get(j).equals("gp")) {
                            contextTable.set(j, "r60");
                        }
                        if (contextTable.get(j).equals("sp")) {
                            contextTable.set(j, "r61");
                        }
                        if (contextTable.get(j).equals("fp")) {
                            contextTable.set(j, "r62");
                        }
                        if (contextTable.get(j).equals("ra")) {
                            contextTable.set(j, "r63");
                        }

                        break;
                    }

                }
            }
            contextTable = new ArrayList<>(new LinkedHashSet<>(contextTable));

            //Para a writeBitmapTable
            for (Instruction instrucao : b.getValue().Instructions()) {
                switch (instrucao.Get("type")) {
                    case "I":
                        //WT

                        if (instrucao.Get("inst") == "lw" || instrucao.Get("inst") == "sw"
                                || instrucao.Get("inst") == "lb" || instrucao.Get("inst") == "lbu" || instrucao.Get("inst") == "sh") {
                            lw_sw_Table.add(instrucao.Get("inst") + " " + instrucao.Get("rt"));

                        } else {
                            writeBitmapTable.Add(instrucao.Get("rs"), "", instrucao.Get("rt"));
                        }

                        //Gambiarra que mostra o que foi escrito e lido, para gerar a Reads
                        nome.Add("", "", instrucao.Get("rt") + "<-" + instrucao.Get("inst"));
                        readsTable.Add("", "", instrucao.Get("rs") + "->" + instrucao.Get("inst"));
                        break;

                    case "R":
                        //WT

                        if (instrucao.Get("inst") == "lw" || instrucao.Get("inst") == "sw"
                                || instrucao.Get("inst") == "lb" || instrucao.Get("inst") == "lbu" || instrucao.Get("inst") == "sh") {
                            lw_sw_Table.add(instrucao.Get("rt"));
                        } else {
                            writeBitmapTable.Add(instrucao.Get("rs"), instrucao.Get("rt"), instrucao.Get("rd"));
                        }

                        //Gambiarra que mostra o que foi escrito e lido, para gerar a Reads
                        nome.Add("", "", instrucao.Get("rd") + "<-" + instrucao.Get("inst"));
                        readsTable.Add("", "", instrucao.Get("rs") + "->" + instrucao.Get("inst"));
                        //Caso tenha RD
                        lol.Add("", "", instrucao.Get("rt") + "->" + instrucao.Get("inst"));

                        break;
                }
            }
            System.out.println("\nContextTable" + contextTable);
            System.out.println("\nWriteTable" + writeBitmapTable.Get());
            //Para saber qual o registrador trocado em WriteTable, é só olhar a ultima vez que o mesmo
            //foi escrito, com excessão das instruções load store
            System.out.println("\nTrocar" + listaTrocar);
            System.out.println("\nlw_Sw_Resource" + lw_sw_Table);
            System.out.println("\n" + "Escrito" + nome.Get());
            System.out.println("\nLido" + readsTable.Get());
            System.out.println("\nLido" + lol.Get());

            lw_sw_Table.clear();
            nome.Get().clear();
            readsTable.Get().clear();
            lol.Get().clear();
            writeBitmapTable.Get().clear();
            contextTable.clear();
            listaTrocar.clear();

            System.out.println("================================================\n");

        }
    }

    //classe das ocorrencias
    protected class Y {

        public HashMap<String, Boolean> wt;
        public ArrayList<String> ocorrences;

        Y() {
            this.wt = new HashMap<>();
            this.ocorrences = new ArrayList<>();
        }

        //para imprimir só as ocorrencias(?)
        @Override
        public String toString() {
            return this.ocorrences.toString();
        }

    }

    protected class WriteTable {

        protected int limitPerList;
        ArrayList<Y> wt;

        public WriteTable(int lpl) {
            this.limitPerList = lpl;
            this.wt = new ArrayList<>();
        }

        public ArrayList<Y> Get() {
            return this.wt;
        }

        protected int Has(String rs) {
            int pos = 0;
            for (Y map : wt) {
                if (map.wt.containsKey(rs)) {
                    return pos;
                }
                pos++;
            }
            return -1;
        }

        public void Add(String rs, String rs2, String rd) {
            int h1 = Has(rs);
            int h2 = Has(rs2);
            if (h1 < 0) {
                if (h2 < 0) {
                    this.AddNewList(rd, 0); // certo
                } else {
                    this.AddNewList(rd, h2 + 1); // certo
                }
            } else if (h2 < 0) {
                this.AddNewList(rd, h1 + 1);
            } else {
                this.AddNewList(rd, Math.max(h1, h2) + 1);
            }
        }

        protected void AddNewList(String rd, int index) {

            Y tmp = new Y();
            int next = index + 1;

            if (wt.size() > index) {
                if (wt.get(index).ocorrences.size() < this.limitPerList) {
                    tmp = wt.get(index);
                } else if (wt.size() > next) {
                    tmp = wt.get(next);
                } else {
                    wt.add(tmp);
                }
            } else {
                wt.add(tmp);
            }

            tmp.wt.put(rd, Boolean.TRUE);
            tmp.ocorrences.add(rd);
        }

    }

}
