Browse Source

basic blocks

eugeniucarvalho 5 years ago
parent
commit
18e329672e
100 changed files with 1578 additions and 991 deletions
  1. 1 1
      build/built-jar.properties
  2. BIN
      build/classes/API/AllocatorInterface.class
  3. BIN
      build/classes/API/Api.class
  4. BIN
      build/classes/API/Functions.class
  5. BIN
      build/classes/API/Gen.class
  6. BIN
      build/classes/API/Instruction.class
  7. BIN
      build/classes/API/RegistroBase.class
  8. BIN
      build/classes/API/Tipos.class
  9. BIN
      build/classes/API/Utils.class
  10. BIN
      build/classes/API/Variaveis.class
  11. BIN
      build/classes/IntermediaryCode/BaseTacGen$1.class
  12. BIN
      build/classes/IntermediaryCode/BaseTacGen$2.class
  13. BIN
      build/classes/IntermediaryCode/BaseTacGen.class
  14. BIN
      build/classes/IntermediaryCode/Block$1.class
  15. BIN
      build/classes/IntermediaryCode/Block.class
  16. BIN
      build/classes/IntermediaryCode/BlockOcorrences.class
  17. BIN
      build/classes/IntermediaryCode/Code.class
  18. BIN
      build/classes/IntermediaryCode/CodeClearProcessor.class
  19. BIN
      build/classes/IntermediaryCode/CodeOtimizadorProcessor.class
  20. BIN
      build/classes/IntermediaryCode/CodeProcessing.class
  21. BIN
      build/classes/IntermediaryCode/DataFrame.class
  22. BIN
      build/classes/IntermediaryCode/Filtros.class
  23. BIN
      build/classes/IntermediaryCode/OcorrenceFinderProcessor.class
  24. BIN
      build/classes/IntermediaryCode/TacGenInterface.class
  25. BIN
      build/classes/IntermediaryCode/TestInstruction.class
  26. BIN
      build/classes/Output/Mif.class
  27. BIN
      build/classes/Output/MifFactory.class
  28. BIN
      build/classes/ast/Node.class
  29. BIN
      build/classes/ast/Semantic.class
  30. BIN
      build/classes/common/Log.class
  31. BIN
      build/classes/compiler/IVANNOSYS.class
  32. BIN
      build/classes/compiler/IvannosysCompiler.class
  33. BIN
      build/classes/compiler/IvannosysTargetArch.class
  34. BIN
      build/classes/compiler/SyntaxError$SyntaxErrorItem.class
  35. BIN
      build/classes/compiler/SyntaxError.class
  36. BIN
      build/classes/grammar/visitorAndWalkers/IvannosysListener.class
  37. BIN
      build/classes/grammar/visitorAndWalkers/IvannosysVisitor.class
  38. 14 15
      build/classes/samples/program.go
  39. 1 1
      build/classes/samples/program_2.go
  40. 9 1
      build/classes/samples/program_mult.go
  41. 5 1
      build/classes/samples/program_mult_manycore.go
  42. BIN
      build/classes/target/mips/AllocatorMipsProcessor.class
  43. BIN
      build/classes/target/mips/CopyDeps.class
  44. BIN
      build/classes/target/mips/Gen$1.class
  45. BIN
      build/classes/target/mips/Gen$2.class
  46. BIN
      build/classes/target/mips/Gen$3.class
  47. BIN
      build/classes/target/mips/Gen$4.class
  48. BIN
      build/classes/target/mips/Gen.class
  49. BIN
      build/classes/target/mips/Mips$2.class
  50. BIN
      build/classes/target/mips/Mips$4.class
  51. BIN
      build/classes/target/mips/Mips.class
  52. BIN
      build/classes/target/mips/OtimizationMips.class
  53. BIN
      build/classes/target/mips/UpdateAddressProcessor.class
  54. BIN
      build/classes/target/mips/jun/Gen.class
  55. BIN
      build/classes/tools/mips/MipsProcessor.class
  56. 26 24
      build/classes/tools/mips/memory/md.memory
  57. 43 57
      build/classes/tools/mips/memory/mi.memory
  58. 3 2
      nbproject/private/private.xml
  59. 13 14
      src/API/Api.java
  60. 1 1
      src/API/Functions.java
  61. 0 267
      src/API/Gen.java
  62. 184 0
      src/API/TargetGen.java
  63. 12 12
      src/API/Tipos.java
  64. 43 0
      src/API/Utils.java
  65. 8 7
      src/API/Variaveis.java
  66. 188 0
      src/IntermediaryCode/BaseBlockProcessor.java
  67. 115 0
      src/IntermediaryCode/BlockBaseGroup.java
  68. 123 77
      src/IntermediaryCode/BlockOcorrences.java
  69. 0 45
      src/IntermediaryCode/CodeClearProcessor.java
  70. 3 1
      src/IntermediaryCode/CodeOtimizadorProcessor.java
  71. 1 0
      src/IntermediaryCode/CodeProcessing.java
  72. 70 0
      src/IntermediaryCode/DeadInstructionsProcessor.java
  73. 2 1
      src/IntermediaryCode/Filtros.java
  74. 3 2
      src/IntermediaryCode/TacGenInterface.java
  75. 176 146
      src/IntermediaryCode/BaseTacGen.java
  76. 0 83
      src/IntermediaryCode/OcorrenceFinderProcessor.java
  77. 95 0
      src/IntermediaryCode/RemoveUnusedLabelsProcessor.java
  78. 1 1
      src/IntermediaryCode/TestInstruction.java
  79. 110 0
      src/IntermediaryCode/VariablesConstantsProcessor.java
  80. 1 1
      src/Output/Mif.java
  81. 1 1
      src/Output/MifFactory.java
  82. 1 1
      src/ast/Node.java
  83. 13 13
      src/ast/Semantic.java
  84. 2 2
      src/API/AllocatorInterface.java
  85. 1 2
      src/IntermediaryCode/Block.java
  86. 77 22
      src/IntermediaryCode/Code.java
  87. 144 79
      src/IntermediaryCode/DataFrame.java
  88. 2 1
      src/API/Instruction.java
  89. 3 3
      src/compiler/IvannosysTargetArch.java
  90. 0 1
      src/common/Log.java
  91. 1 1
      src/API/RegistroBase.java
  92. 1 1
      src/compiler/SyntaxError.java
  93. 11 9
      src/compiler/IVANNOSYS.java
  94. 21 65
      src/compiler/IvannosysCompiler.java
  95. 16 0
      src/frontend/Ivannosys/IvannosysFrontEnd.java
  96. 16 12
      src/grammar/visitorAndWalkers/IvannosysListener.java
  97. 2 2
      src/grammar/visitorAndWalkers/IvannosysVisitor.java
  98. 14 15
      src/samples/program.go
  99. 1 1
      src/samples/program_2.go
  100. 0 0
      src/samples/program_jun_bit_count.go

+ 1 - 1
build/built-jar.properties

@@ -1,4 +1,4 @@
-#Thu, 31 May 2018 10:25:41 -0300
+#Thu, 14 Jun 2018 23:35:26 -0300
 
 
 C\:\\Users\\EUGENIO\ CARVALHO\\Desktop\\projects\\Ivannosys=

BIN
build/classes/API/AllocatorInterface.class


BIN
build/classes/API/Api.class


BIN
build/classes/API/Functions.class


BIN
build/classes/API/Gen.class


BIN
build/classes/API/Instruction.class


BIN
build/classes/API/RegistroBase.class


BIN
build/classes/API/Tipos.class


BIN
build/classes/API/Utils.class


BIN
build/classes/API/Variaveis.class


BIN
build/classes/IntermediaryCode/BaseTacGen$1.class


BIN
build/classes/IntermediaryCode/BaseTacGen$2.class


BIN
build/classes/IntermediaryCode/BaseTacGen.class


BIN
build/classes/IntermediaryCode/Block$1.class


BIN
build/classes/IntermediaryCode/Block.class


BIN
build/classes/IntermediaryCode/BlockOcorrences.class


BIN
build/classes/IntermediaryCode/Code.class


BIN
build/classes/IntermediaryCode/CodeClearProcessor.class


BIN
build/classes/IntermediaryCode/CodeOtimizadorProcessor.class


BIN
build/classes/IntermediaryCode/CodeProcessing.class


BIN
build/classes/IntermediaryCode/DataFrame.class


BIN
build/classes/IntermediaryCode/Filtros.class


BIN
build/classes/IntermediaryCode/OcorrenceFinderProcessor.class


BIN
build/classes/IntermediaryCode/TacGenInterface.class


BIN
build/classes/IntermediaryCode/TestInstruction.class


BIN
build/classes/Output/Mif.class


BIN
build/classes/Output/MifFactory.class


BIN
build/classes/ast/Node.class


BIN
build/classes/ast/Semantic.class


BIN
build/classes/common/Log.class


BIN
build/classes/compiler/IVANNOSYS.class


BIN
build/classes/compiler/IvannosysCompiler.class


BIN
build/classes/compiler/IvannosysTargetArch.class


BIN
build/classes/compiler/SyntaxError$SyntaxErrorItem.class


BIN
build/classes/compiler/SyntaxError.class


BIN
build/classes/grammar/visitorAndWalkers/IvannosysListener.class


BIN
build/classes/grammar/visitorAndWalkers/IvannosysVisitor.class


+ 14 - 15
build/classes/samples/program.go

@@ -48,9 +48,22 @@ func laplaciano() {
 
     for i:= 1; i < LM1; i++ {
         for j := 1; j < CM1; j++ {
-lab_1:
             l = origin[i-1][j] + origin[i][j-1] + origin[i][j+1] + origin[i+1][j] - (4 * origin[i][j])
+
+            if l > 255 { l = 255 }
+            result[i][j] = l
+        }
+    }
+}
+
+func main() {
+  preenche_matriz()
+  laplaciano()
+}
+
 /*
+lab_1:
+            l = origin[i-1][j] + origin[i][j-1] + origin[i][j+1] + origin[i+1][j] - (4 * origin[i][j])
 lab_2:
             l = l + origin[i][j-1]
 lab_3:
@@ -62,20 +75,6 @@ lab_5:
 lab_6:
 
 */
-            if l > 255 {
-              l = 255
-            }
-            result[i][j] = l
-        }
-    }
-}
-/*
-*/
-
-func main() {
-  preenche_matriz()
-  laplaciano()
-}
 
 /**
 

+ 1 - 1
build/classes/samples/program_2.go

@@ -159,7 +159,7 @@ FOR3:
       
    <main.L>:
  6:	 0:		pop_param _V2		  T< pop_param >
- 7:	 1:		_T4 := *_V2		  T< pointer_assignment >
+ 7:	 1:		_T4 := *_V2		  T< pointer_assign >
  8:	 2:		_T5 := _T4 + 1		  T< assign >
  9:	 3:		push_return _T5		  T< push_return >
 10:	 4:		return 1		  T< return >

+ 9 - 1
build/classes/samples/program_mult.go

@@ -1,4 +1,4 @@
-@target mips, mipt2
+@target: mips, mipt2
 
 package main;
 
@@ -37,6 +37,14 @@ func multiplica() {
 }
 
 func main() {
+    var (
+        x int
+    )
+
+    x = x + 2
+    x = x & 9
+    x = x | 9
     preenche()
     multiplica()
+    return x
 }

+ 5 - 1
build/classes/samples/program_mult_manycore.go

@@ -42,6 +42,7 @@
     }
 ]`
 
+
 package main;
 
 const (
@@ -57,9 +58,12 @@ var (
 )
 
 func multiplica(initial int) {
+    tmp   := 10
     aux   := 0
+    x     := tmp + 1
     limit := initial + NUM_LINHAS_MULT
-    for i := initial; i < limit; i++ {
+    for i := initial; i < x; i++ {
+    //for i := initial; i < limit; i++ {
         for j := 0; j < COL; j++ {
             for k := 0; k < LIN; k++ {
                 aux = aux + (matrizA[i][k] * matrizB[k][j])

BIN
build/classes/target/mips/AllocatorMipsProcessor.class


BIN
build/classes/target/mips/CopyDeps.class


BIN
build/classes/target/mips/Gen$1.class


BIN
build/classes/target/mips/Gen$2.class


BIN
build/classes/target/mips/Gen$3.class


BIN
build/classes/target/mips/Gen$4.class


BIN
build/classes/target/mips/Gen.class


BIN
build/classes/target/mips/Mips$2.class


BIN
build/classes/target/mips/Mips$4.class


BIN
build/classes/target/mips/Mips.class


BIN
build/classes/target/mips/OtimizationMips.class


BIN
build/classes/target/mips/UpdateAddressProcessor.class


BIN
build/classes/target/mips/jun/Gen.class


BIN
build/classes/tools/mips/MipsProcessor.class


+ 26 - 24
build/classes/tools/mips/memory/md.memory

@@ -1,27 +1,27 @@
-0000:	0
-0004:	0
-0008:	0
-0012:	0
-0016:	0
-0020:	0
-0024:	0
-0028:	0
+0000:	1
+0004:	2
+0008:	3
+0012:	4
+0016:	1
+0020:	2
+0024:	3
+0028:	4
 0032:	0
 0036:	0
 0040:	0
 0044:	0
-0048:	0
-0052:	0
-0056:	0
-0060:	0
-0064:	0
-0068:	0
-0072:	0
-0076:	0
-0080:	0
-0084:	0
-0088:	0
-0092:	0
+0048:	3
+0052:	4
+0056:	5
+0060:	6
+0064:	3
+0068:	4
+0072:	5
+0076:	6
+0080:	69
+0084:	80
+0088:	93
+0092:	108
 0096:	0
 0100:	0
 0104:	0
@@ -4089,8 +4089,10 @@
 16352:	0
 16356:	0
 16360:	0
-16364:	0
-16368:	0
-16372:	0
-16376:	0
+16364:	-37131
+16368:	-18559
+16372:	9464
+16376:	-18572
 16380:	0
+16370:	7
+16366:	2

+ 43 - 57
build/classes/tools/mips/memory/mi.memory

@@ -1,61 +1,47 @@
-0666763248
+0666763252
 0001962017
-0605028352
-0605093888
-0134217783
-0000000000
-0605159424
-0134217778
-0000000000
-0605224960
-0134217762
-0000000000
-0001138721
-0000813120
-0001273889
-0028207137
-0000882816
-0059734049
-2381578240
-0000000000
-0001359905
-0001261601
-0000542784
-0001200161
-0019548193
-0000612480
-0059463713
-2373255184
-0000000000
-0001400865
-0051146776
-0000028690
-0034504737
-0645070849
-0604962818
-0040833059
-0071368679
-0000000000
-0001130529
-0000544832
-0001198113
-0021581857
-0000678016
-0059463713
-2909798432
-0000000000
-0605028352
 2949644288
-0000000000
+0605140852
+2949709828
+2949775368
+0134217748
+2412969988
+0001253409
+0201326619
+0000153633
+2413035520
+0042704929
+2949906432
+2413101060
+0649396237
+2949971972
+2413166600
+0651558913
+2950037512
+2413232136
+0604906744
+0049156131
+0071368687
+2412773376
+0001052705
+4294967295
+0666763256
+0001962017
+2948857856
+2412773376
+2949709828
+0033558563
+0406847497
+2412904452
 0642908161
-0604897282
-0038670371
-0071368660
-0000000000
-0640745473
-0604962818
-0036638755
-0071368652
-0000000000
-0666697744
+2949775364
+2412969984
+0604700673
+0040591395
+0040671268
+0308281345
+0134217762
+2413035524
+0001314849
+0666697736
 0065011720

+ 3 - 2
nbproject/private/private.xml

@@ -28,13 +28,14 @@
     </editor-bookmarks>
     <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
         <group>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/target/mips/jun/Gen.java</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/samples/program_mult.go</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/grammar/IvannosysGrammar.g4</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/API/BuildParams.java</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/samples/program_mult_manycore.go</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/tools/mips/memory/md.memory</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/API/Utils.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/grammar/visitorAndWalkers/IvannosysListener.java</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/API/Api.java</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/target/mips/Gen.java</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/compiler/IvannosysCompiler.java</file>
             <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/compiler/IVANNOSYS.java</file>
         </group>

+ 13 - 14
src/API/Api.java

@@ -37,10 +37,10 @@ public class Api {
 //        Constantes.add("__MAX_MEM__", "int", "1024", "global");
 
         /*Inicializando tipos*/
-        Tipos._init();
+        Types._init();
 
-        Tipos.Add(Tipos.INTEGER, new Node(Tipos.INTEGER)
-                .S("type", Tipos.INTEGER)
+        Types.Add(Types.INTEGER, new Node(Types.INTEGER)
+                .S("type", Types.INTEGER)
                 .S("size", 1)
                 .S("file", "std")
                 .S("scope", "")
@@ -48,8 +48,8 @@ public class Api {
                 .S("class", "type")
                 .S("public", "true")
         );
-        Tipos.Add(Tipos.BOOLEAN, new Node(Tipos.BOOLEAN)
-                .S("type", Tipos.BOOLEAN)
+        Types.Add(Types.BOOLEAN, new Node(Types.BOOLEAN)
+                .S("type", Types.BOOLEAN)
                 .S("size", 1)
                 .S("file", "std")
                 .S("scope", "")
@@ -57,8 +57,8 @@ public class Api {
                 .S("class", "type")
                 .S("public", "true")
         );
-        Tipos.Add(Tipos.CHAR, new Node(Tipos.CHAR)
-                .S("type", Tipos.CHAR)
+        Types.Add(Types.CHAR, new Node(Types.CHAR)
+                .S("type", Types.CHAR)
                 .S("size", 1)
                 .S("file", "std")
                 .S("scope", "")
@@ -68,14 +68,13 @@ public class Api {
         );
 
         Imports._init(compiler);
-        Constantes._init();
-//
+//        Constantes._init();
 
-//        Tipos.add(Tipos.UNDEFINED, 0);
-//        Tipos.add(Tipos.VOID, 0);
-//        Tipos.add("string", 1);
-//        Tipos.add("thread", 1);
-//        Tipos.add("reference", 1);
+//        Types.add(Types.UNDEFINED, 0);
+//        Types.add(Types.VOID, 0);
+//        Types.add("string", 1);
+//        Types.add("thread", 1);
+//        Types.add("reference", 1);
         Interfaces._init();
         
         /*Inicializando funcoes*/

+ 1 - 1
src/API/Functions.java

@@ -99,7 +99,7 @@ public class Functions {
             method = matcher.group("method");
             break;
         }
-        Node T = Tipos.Get(type);
+        Node T = Types.Get(type);
 //        System.out.println("DeepGet:" + type + ":" + method + ":" + T);
         if (T != null) {
             Node def;

+ 0 - 267
src/API/Gen.java

@@ -1,267 +0,0 @@
-/*
- * 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 API;
-
-import IntermediaryCode.Block;
-import IntermediaryCode.Code;
-import IntermediaryCode.CodeProcessing;
-import compiler.IvannosysTargetArch;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-public abstract class Gen implements IvannosysTargetArch {
-
-    protected Code target;
-    protected Code tac;
-    protected LinkedHashMap<String, CodeProcessing> beforeTranslate = new LinkedHashMap<>();
-    protected LinkedHashMap<String, CodeProcessing> beforeTranslateBlock = new LinkedHashMap<>();
-    protected LinkedHashMap<String, CodeProcessing> afterTranslate = new LinkedHashMap<>();
-    protected LinkedHashMap<String, CodeProcessing> afterTranslateBlock = new LinkedHashMap<>();
-
-    public Gen(String id) {
-        BaseGenInit(id);
-    }
-
-    public void BaseGenInit(String id) {
-        target = new Code(id);
-    }
-
-    public Code getTarget() {
-        return target;
-    }
-
-    public void setTarget(Code target) {
-        this.target = target;
-    }
-
-    public Code getTac() {
-        return tac;
-    }
-
-//    public void setTac(Code tac) {
-//        this.tac = tac;
-//    }
-    public IvannosysTargetArch SetTAC(Code tac) {
-        this.tac = tac;
-        target.GData().copy(tac.GData());
-        return this;
-    }
-
-    protected Instruction Add(Instruction inst) {
-        target.Block().Add(inst);
-        return inst;
-    }
-
-    @Override
-    public IvannosysTargetArch Format() {
-        try {
-            String code = target.getCodeStream();
-            System.out.println("Target[" + target.Name() + "]:\n" + code);
-
-        } catch (Exception ex) {
-            Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
-        }
-        return this;
-    }
-
-    @Override
-    public IvannosysTargetArch Compile() {
-        try {
-            // Traduz o codigo intermediario para o alvo
-            Translate();
-
-        } catch (Exception ex) {
-            Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
-        }
-        return this;
-    }
-
-    protected void Translate() throws Exception {
-        String id;
-
-        BeforeTranslate();
-
-        for (Map.Entry<String, Block> b : tac.getBlocks().entrySet()) {
-            id = b.getKey();
-
-            tac.Use(id);
-
-            BeforeTranslateBlock();
-//            AllocatorRegister.Alloc(tac);
-            target.OpenBlock(id);
-
-            Prolog(id);
-
-            TranslateBlock(b.getValue());
-
-            Epilog(id);
-            target.CloseBlock();
-
-            target.UpdatePositions();
-            AfterTranslateBlock();
-        }
-
-        AfterTranslate();
-    }
-
-    public Gen BeforeTranslate(String id, CodeProcessing processor) {
-        beforeTranslate.put(id, processor);
-        return this;
-    }
-
-    public Gen BeforeTranslateBlock(String id, CodeProcessing processor) {
-        beforeTranslateBlock.put(id, processor);
-        return this;
-    }
-
-    public Gen AfterTranslate(String id, CodeProcessing processor) {
-        afterTranslate.put(id, processor);
-        return this;
-    }
-
-    public Gen AfterTranslateBlock(String id, CodeProcessing processor) {
-        afterTranslateBlock.put(id, processor);
-        return this;
-    }
-
-    protected Gen BeforeTranslate() throws Exception {
-        for (Map.Entry<String, CodeProcessing> codeProcessing : beforeTranslate.entrySet()) {
-            codeProcessing.getValue().Exec(tac, beforeTranslate);
-        }
-        return this;
-    }
-
-    protected Gen BeforeTranslateBlock() throws Exception {
-        for (Map.Entry<String, CodeProcessing> codeProcessing : beforeTranslateBlock.entrySet()) {
-            codeProcessing.getValue().Exec(tac, beforeTranslateBlock);
-        }
-        return this;
-    }
-
-    protected Gen AfterTranslate() throws Exception {
-//        System.out.println("AfterTranslate:" + afterTranslate.entrySet().size());
-        for (Map.Entry<String, CodeProcessing> codeProcessing : afterTranslate.entrySet()) {
-            codeProcessing.getValue().Exec(target, afterTranslate);
-        }
-        return this;
-    }
-
-    protected Gen AfterTranslateBlock() throws Exception {
-        for (Map.Entry<String, CodeProcessing> codeProcessing : afterTranslateBlock.entrySet()) {
-            codeProcessing.getValue().Exec(target, afterTranslateBlock);
-        }
-        return this;
-    }
-
-    protected void TranslateBlock(Block b) throws Exception {
-//        System.out.println("Translate block:" + b.getName() + "::" + b.Instructions().size());
-
-        for (Instruction inst : b.Instructions()) {
-//            System.out.println("Translate: " + inst.G("global.position") + "::read["
-//                    + inst.G("reg.dst.load")
-//                    + "|"
-//                    + inst.G("reg.p1.load")
-//                    + "|"
-//                    + inst.G("reg.p2.load")
-//                    + "] >> write["
-//                    + inst.G("reg.dst.store")
-//                    + "|"
-//                    + inst.G("reg.p1.store")
-//                    + "|"
-//                    + inst.G("reg.p2.store")
-//                    + "]"
-//                    + inst.G("type")
-//            );
-//            
-            switch (inst.G("type")) {
-                case "label":
-                    if (!inst.G("label").equals(getTarget().Block().getName())) {
-                        TranslateLabel(inst);
-                    }
-                    break;
-                case "assign":
-                    TranslateAssign(inst);
-                    break;
-                case "unary":
-                    TranslateUnary(inst);
-                    break;
-                case "copy":
-                    TranslateCopy(inst);
-                    break;
-                case "jump":
-                    TranslateJump(inst);
-                    break;
-                case "call":
-                    TranslateCall(inst);
-                    break;
-                case "return":
-                    TranslateReturn(inst);
-                    break;
-                case "push_param":
-                    TranslatePushParam(inst);
-                    break;
-                case "push_return":
-                    TranslatePushReturn(inst);
-                    break;
-                case "pop_return":
-                    TranslatePopReturn(inst);
-                    break;
-                case "pop_param":
-                    TranslatePopParam(inst);
-                    break;
-                case "branch":
-                    TranslateBranch(inst);
-                    break;
-                case "indexed_assign":
-                    TranslateIndexedAssignment(inst);
-                    break;
-                case "pointer_assignment":
-                    TranslatePointerAssignment(inst);
-                    break;
-                default:
-                    throw new Exception(String.format("TAC instruction type '%s' not defined", inst.G("type")));
-            }
-        }
-    }
-
-}
-//    protected void Exec() {
-//        StringBuilder S = new StringBuilder();
-//        for (Map.Entry<String, Block> entry : tac.getBlocks().entrySet()) {
-//            TranslateBlock(entry.getValue());
-//            
-//            S.append("<" + entry.getKey() + ">:\n");
-//
-//            for (Instruction registro : entry.getValue()) {
-//                String line = registro.G("line");
-//                spacer = registro.G("sentenca").equals("jump") ? "\t" : "";
-//                inst = fm.Format(registro);
-//                registro.S("mipsInstruction", inst);
-//                S += line + ". " + spacer + "\t" + inst + "\t\t-- ";
-//                S += registro.G("inst3end") + "\n";
-//            }
-//        }
-//    }
-
-//        StringBuilder S = new StringBuilder();
-//        for (Map.Entry<String, Block> entry : tac.stmts.entrySet()) {
-//            S.append("<" + entry.getKey() + ">:\n");
-//
-//            for (Instruction registro : entry.getValue()) {
-//                String line = registro.G("line");
-//                spacer = registro.G("sentenca").equals("jump") ? "\t" : "";
-//                inst = fm.Format(registro);
-//                registro.S("mipsInstruction", inst);
-//                S += line + ". " + spacer + "\t" + inst + "\t\t-- ";
-//                S += registro.G("inst3end") + "\n";
-//            }
-//        }

+ 184 - 0
src/API/TargetGen.java

@@ -0,0 +1,184 @@
+/*
+ * 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 API;
+
+import common.Instruction;
+import common.Block;
+import common.Code;
+import common.IvannosysTargetArch;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public abstract class TargetGen implements IvannosysTargetArch {
+
+    protected Code target;
+    protected Code IR;
+
+    public TargetGen(String id) {
+        BaseGenInit(id);
+    }
+
+    public void BaseGenInit(String id) {
+        target = new Code(id);
+    }
+
+    public Code getTarget() {
+        return target;
+    }
+
+    public void setTarget(Code target) {
+        this.target = target;
+    }
+
+    public Code getIR() {
+        return IR;
+    }
+
+//    public void setTac(Code IR) {
+//        this.IR = IR;
+//    }
+    public IvannosysTargetArch SetTAC(Code tac) {
+        IR = tac;
+        target.GData().copy(tac.GData());
+        return this;
+    }
+
+    protected Instruction Add(Instruction inst) {
+        target.Block().Add(inst);
+        return inst;
+    }
+
+    @Override
+    public IvannosysTargetArch Format() {
+        try {
+            String code = target.getCodeStream();
+            System.out.println("Target[" + target.Name() + "]:\n" + code);
+
+        } catch (Exception ex) {
+            Logger.getLogger(TargetGen.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        return this;
+    }
+
+    @Override
+    public IvannosysTargetArch Compile() {
+        try {
+            // Traduz o codigo intermediario para o alvo
+            Translate();
+
+        } catch (Exception ex) {
+            Logger.getLogger(TargetGen.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        return this;
+    }
+
+    protected void Translate() throws Exception {
+        String id;
+
+        IR.BeforeTranslate();
+
+        for (Map.Entry<String, Block> b : IR.getBlocks().entrySet()) {
+            id = b.getKey();
+
+            IR.Use(id);
+
+            IR.BeforeTranslateBlock();
+
+            target.OpenBlock(id);
+
+            Prolog(id);
+
+            TranslateBlock(b.getValue());
+
+            Epilog(id);
+
+            target.CloseBlock();
+
+            target.UpdatePositions();
+
+            target.AfterTranslateBlock();
+        }
+
+        target.AfterTranslate();
+    }
+
+    protected void TranslateBlock(Block b) throws Exception {
+//        System.out.println("Translate block:" + b.getName() + "::" + b.Instructions().size());
+
+        for (Instruction inst : b.Instructions()) {
+//            System.out.println("Translate: " + inst.G("global.position") + "::read["
+//                    + inst.G("reg.dst.load")
+//                    + "|"
+//                    + inst.G("reg.p1.load")
+//                    + "|"
+//                    + inst.G("reg.p2.load")
+//                    + "] >> write["
+//                    + inst.G("reg.dst.store")
+//                    + "|"
+//                    + inst.G("reg.p1.store")
+//                    + "|"
+//                    + inst.G("reg.p2.store")
+//                    + "]"
+//                    + inst.G("type")
+//            );
+//            
+            switch (inst.G("type")) {
+                case "label":
+                    if (!inst.G("label").equals(getTarget().Block().getName())) {
+                        TranslateLabel(inst);
+                    }
+                    break;
+                case "assign":
+                    TranslateAssign(inst);
+                    break;
+                case "unary":
+                    TranslateUnary(inst);
+                    break;
+                case "copy":
+                    TranslateCopy(inst);
+                    break;
+                case "jump":
+                    TranslateJump(inst);
+                    break;
+                case "call":
+                    TranslateCall(inst);
+                    break;
+                case "return":
+                    TranslateReturn(inst);
+                    break;
+                case "push_param":
+                    TranslatePushParam(inst);
+                    break;
+                case "push_return":
+                    TranslatePushReturn(inst);
+                    break;
+                case "pop_return":
+                    TranslatePopReturn(inst);
+                    break;
+                case "pop_param":
+                    TranslatePopParam(inst);
+                    break;
+                case "branch":
+                    TranslateBranch(inst);
+                    break;
+                case "indexed_assign":
+                    TranslateIndexedAssignment(inst);
+                    break;
+                case "pointer_assign":
+                    TranslatePointerAssignment(inst);
+                    break;
+                default:
+                    throw new Exception(String.format("TAC instruction type '%s' not defined", inst.G("type")));
+            }
+        }
+    }
+
+}

+ 12 - 12
src/API/Tipos.java

@@ -14,7 +14,7 @@ import java.util.HashMap;
  *
  * @author Eugenio
  */
-public class Tipos {
+public class Types {
 
     public static AbstractSyntaxTree ast;
     public static HashMap<String, Node> _types = new HashMap<>();
@@ -226,7 +226,7 @@ public class Tipos {
 //
 //    public static int size(String type) throws Exception {
 //        if (type.contains("*")) {
-//            return Tipos.SIZE_POINTER;
+//            return Types.SIZE_POINTER;
 //        }
 //
 //        if (!exist(type)) {
@@ -247,16 +247,16 @@ public class Tipos {
 //        Pattern p = Pattern.compile("(true|false)", Pattern.CASE_INSENSITIVE);
 //
 //        if (value.matches("-?[0-9]+")) {
-//            return Tipos.INTEGER;
+//            return Types.INTEGER;
 //        } else if (p.matcher(value).matches()) {
-//            return Tipos.BOOLEAN;
+//            return Types.BOOLEAN;
 //        } else if (value.matches("'.'")) {
-//            return Tipos.CHAR;
+//            return Types.CHAR;
 //        } else if (value.matches("\".*\"")) {
-//            return Tipos.STRING;
+//            return Types.STRING;
 //        }
 //
-//        return Tipos.UNDEFINED;
+//        return Types.UNDEFINED;
 //    }
 //
 //    public static int offset(String type, String prop) throws Exception {
@@ -499,7 +499,7 @@ public class Tipos {
 ////            try {
 ////                sizet = indice.getInt("value");
 ////            } catch (Exception ex) {
-////                Logger.getLogger(Tipos.class.getName()).log(Level.SEVERE, null, ex);
+////                Logger.getLogger(Types.class.getName()).log(Level.SEVERE, null, ex);
 ////            }
 ////        } else {
 ////            indValor = indice.getText();
@@ -558,7 +558,7 @@ public class Tipos {
 //////    }
 ////    public static int tamanhoVariavel(Node var) throws Exception {
 ////
-////        int size = Tipos.tamanho(var);
+////        int size = Types.tamanho(var);
 ////
 ////        if (var.igual("matrix", "true")) {
 ////            Node declaracao = ast.encontreDeclaracao(var, var.parent);
@@ -583,7 +583,7 @@ public class Tipos {
 ////     * @param current
 ////     */
 ////    public static void validarAtribuicao(Node current, String atribuicao) throws Exception {
-////        Tipos.temAtributo(null, null);
+////        Types.temAtributo(null, null);
 ////        String tipoEsperado = tipoDe(atribuicao, atribuicao);
 ////        String tipoAtribuido = porValor(atribuicao);
 ////        if (!tipoEsperado.equals(tipoAtribuido)) {
@@ -622,7 +622,7 @@ public class Tipos {
 ////        Node atributo = t.first().encontre(attr);
 ////        /*Equanto houver atributo segue com recursao, caso seja o ultimo sera avaliado*/
 ////        if (!parts.isEmpty()) {
-////            if (!Tipos.temAtributo(tipo, attr)) {
+////            if (!Types.temAtributo(tipo, attr)) {
 ////                return lista;
 ////            }
 ////            if (atributo.igual("matrix", "true")) {
@@ -733,7 +733,7 @@ public class Tipos {
 ////            if (n.igual("value", atributo)) {
 ////                break;
 ////            }
-////            base += Tipos.tamanho(n);
+////            base += Types.tamanho(n);
 ////        }
 ////        return base;
 ////    }

+ 43 - 0
src/API/Utils.java

@@ -14,6 +14,7 @@ import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.List;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -212,4 +213,46 @@ public class Utils {
         }
     }
 
+    public static Integer ResolveExpr(String op, String p1, String p2) throws Exception {
+        return ResolveExpr(op, Integer.parseInt(p1), Integer.parseInt(p2));
+    }
+
+    public static Integer ResolveExpr(String op, Integer p1, Integer p2) {
+        switch (op.substring(0, 1)) {
+            case "+":
+                return p1 + p2;
+            case "-":
+                return p1 - p2;
+            case "*":
+                return p1 * p2;
+            case "/":
+                return p1 / p2;
+            case "%":
+                return p1 % p2;
+            case "<<":
+                return p1 << p2;
+            case ">>":
+                return p1 >> p2;
+            case "&":
+                return p1 & p2;
+            case "|":
+                return p1 | p2;
+        }
+        return null;
+    }
+
+    public static String ComplementOperation(String op) {
+        return Complements.get(op);
+    }
+    protected static HashMap<String, String> Complements = new HashMap<String, String>() {
+        {
+            put("!=", "==");
+            put("==", "!=");
+            put("<", ">=");
+            put("<=", ">");
+            put(">", "<=");
+            put(">=", "<");
+        }
+    };
+
 }

+ 8 - 7
src/API/Variaveis.java

@@ -5,6 +5,7 @@
  */
 package API;
 
+import common.Instruction;
 import ast.Node;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -92,10 +93,10 @@ public class Variaveis {
                 ArrayList<String> parts = new ArrayList<>(Arrays.asList(path.split("\\.")));
                 parts.remove(0); // Remove a primaira parte que é uma string vazia
                 String typed = var.G("type"), attr;
-                t = Tipos.Get(typed);
+                t = Types.Get(typed);
 
                 while (parts.size() > 0) {
-                    if (Tipos.Primitive(typed)) {
+                    if (Types.Primitive(typed)) {
                         return typed;
                     }
 
@@ -111,7 +112,7 @@ public class Variaveis {
 
                     typed = tmp.find("type").G("type");
 
-                    t = Tipos.Get(typed);
+                    t = Types.Get(typed);
                 }
 //                System.out.println("Type:" + t + type);
 
@@ -433,8 +434,8 @@ public class Variaveis {
 //        String varpath = current.getText();
 //        existe(varpath, current.G("escopo"));
 //
-////        if (Tipos.structAcesso(varpath)) {
-////            Tipos.validarAtribuicao(current);
+////        if (Types.structAcesso(varpath)) {
+////            Types.validarAtribuicao(current);
 ////        }
 //        Node var = find(varpath, current.G("escopo"));
 //        if (!var.G("tipo").equals(tipoEsperado)) {
@@ -485,7 +486,7 @@ public class Variaveis {
 //        ArrayList<String> decIndices;
 //        boolean isAtributo = var.igual("class", "atributo");
 //        decIndices = isAtributo
-//                ? Tipos.getIndices(var) : Variaveis.getIndices(var);
+//                ? Types.getIndices(var) : Variaveis.getIndices(var);
 //        limit = decIndices.size();
 //        acesso = acessoIndices.size();
 //
@@ -613,7 +614,7 @@ public class Variaveis {
             ArrayList<String> path = new ArrayList<>(Arrays.asList(idparts[1].split("\\.")));
 
 //            System.out.println("shift:" + var.G("type") + "-" + path);
-            return Tipos.Shift(var.G("type"), path);
+            return Types.Shift(var.G("type"), path);
         }
         // Não é acesso a um atributo
         return 0;

+ 188 - 0
src/IntermediaryCode/BaseBlockProcessor.java

@@ -0,0 +1,188 @@
+package IntermediaryCode;
+
+/*
+ * 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.
+ */
+import API.Utils;
+import common.Code;
+import common.Instruction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class BaseBlockProcessor implements CodeProcessing {
+
+//    protected LinkedHashMap<String, ArrayList<ArrayList<Integer>>> basicBlocks = new LinkedHashMap<>();
+//    protected String basicBlockName;
+//    protected Integer basicBlockCount = 0;
+    protected BlockBaseGroup group;
+    protected HashMap<String, BlockBaseGroup> groups = new HashMap<>();
+    protected Integer nextLeader;
+    protected LinkedHashMap<Integer, Integer> leaders;
+
+    //OK
+//    protected HashMap<String, BlockBaseOcorrences> blocks = new HashMap<>();
+    protected BlockBaseOcorrences block;
+    public static Pattern addresspattern = Pattern.compile("\\_[VTGC].*", Pattern.CASE_INSENSITIVE);
+    private ArrayList<Integer> leadersList;
+
+    public BaseBlockProcessor() {
+    }
+
+    public BlockBaseGroup getBasicBlockGroup(String id) {
+        return groups.get(id);
+    }
+
+    public HashMap<String, BlockBaseGroup> getGroups() {
+        return groups;
+    }
+
+//    public HashMap<String, BlockBaseOcorrences> getBlocks() {
+//        return blocks;
+//    }
+//
+//    public void setBlocks(HashMap<String, BlockBaseOcorrences> blocks) {
+//        this.blocks = blocks;
+//    }
+    public BlockBaseOcorrences getBlock() {
+        return block;
+    }
+
+    public void setBlock(BlockBaseOcorrences block) {
+        this.block = block;
+    }
+
+    public static Pattern getAddresspattern() {
+        return addresspattern;
+    }
+
+    public static void setAddresspattern(Pattern addresspattern) {
+        BaseBlockProcessor.addresspattern = addresspattern;
+    }
+
+//    protected void IncrementBasicBlockCount() {
+//        basicBlockCount++;
+//    }
+    @Override
+    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
+        String name = c.Block().getName();
+        BlockBaseGroup g = new BlockBaseGroup(name);
+        group = g;
+        groups.put(name, g);
+//        block = new BlockBaseOcorrences(name);
+//        ArrayList<ArrayList<Integer>> bbs = new ArrayList<>();
+//        ArrayList<Integer> bb = null;
+
+//        basicBlockName = name;
+//        basicBlockCount = 0;
+//            protected ArrayList<ArrayList<Integer>> basicBlock = new ArrayList<>();
+//        basicBlocks.put(name, bbs);
+//        blocks.put(name, block);
+        leaders = new LinkedHashMap<>();
+
+//        block.LastPosition = c.Block().CurrentAddress - 1;
+//Step 1. Identify the leaders in the code. Leaders are instructions which come under any of the following 3 categories :
+//
+//The first instruction is a leader.
+//The target of a conditional or an unconditional goto/jump instruction is a leader.
+//The instruction that immediately follows a conditional or an unconditional goto/jump instruction is a leader.
+        Instruction x;
+        LinkedList<Instruction> instructions = c.Block().Instructions();
+        int instructionPosition = 0,
+                fix,
+                lastLeader = -1,
+                limit = instructions.size() - 2;
+
+        for (int i = 0; i < limit; i++) {
+            x = instructions.get(i);
+            fix = 0;
+            switch (x.G("type")) {
+                case "jump":
+                case "call":
+                case "branch":
+                    fix = 1;
+                case "label":
+                    if (lastLeader >= 0) {
+                        leaders.put(lastLeader, instructionPosition);
+                    }
+
+                    if (!instructions.get(i + 1).in("type", new String[]{"jump", "label"})) {
+
+                        lastLeader = instructionPosition + fix;
+                        leaders.put(lastLeader, 0);
+                    }
+            }
+
+            if (!x.eq("type", "label")) {
+                instructionPosition++;
+            }
+        }
+
+        leaders.put(lastLeader, instructionPosition);
+        // reseta a posicao da instrução
+        instructionPosition = 0;
+//        System.out.println("basicBlock:::::::::::::" + leaders);
+        leadersList = new ArrayList<Integer>();
+
+        for (Map.Entry<Integer, Integer> entry : leaders.entrySet()) {
+            leadersList.add(entry.getKey());
+        }
+
+        System.out.println("leadersList:" + leadersList);
+
+        nextLeader = leadersList.remove(0);
+
+        // Registra primeiro bloco basico
+        RegBasicBlock();
+        // Atribui o segundo leder como 
+
+//        block.LastPosition = nextLeader - 1;
+        for (Instruction inst : instructions) {
+            switch (inst.G("type")) {
+                case "label":
+                    break;
+                default:
+//                    System.out.println("Ins:(" + instructionPosition + ")(" + nextLeader + ")");
+                    // Registra 
+                    if (instructionPosition == nextLeader) {
+//                        block.CloseAllIntervals();
+//                        nextLeader = leadersList.remove(0);
+//                        block.LastPosition = nextLeader - 1;
+                        RegBasicBlock();
+                    }
+                    // Registra os acessos de leitura e escrita dos enderecos da instrucao
+                    group.ParseInstruction(inst, "dst,p1,p2");
+
+                    instructionPosition++;
+            }
+        }
+        group.Close();
+//        // Atualiza todos os encerramentos de intervalo para a ultima ocorrencia da variavel;
+//        block.CloseAllIntervals();
+
+        System.out.println("block:" + group);
+    }
+
+    protected void RegBasicBlock() {
+
+//        System.out.println("RegBasicBlock:(" + nextLeader + ")(" + ((leaders.get(nextLeader) - nextLeader) + 1) + ")");
+        group.RegisterBlock(nextLeader, (leaders.get(nextLeader) - nextLeader) + 1);
+        if (!leadersList.isEmpty()) {
+            nextLeader = leadersList.remove(0);
+        }
+    }
+
+    public static boolean IsAddress(String alias) {
+//        System.out.println("Is Address:" + alias + "::" + addresspattern.matcher(alias).matches());
+        return !Utils.Empty(alias) && addresspattern.matcher(alias).matches();
+    }
+}

+ 115 - 0
src/IntermediaryCode/BlockBaseGroup.java

@@ -0,0 +1,115 @@
+/*
+ * 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 IntermediaryCode;
+
+import common.Instruction;
+import java.util.LinkedList;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class BlockBaseGroup {
+
+    protected LinkedList<BlockBaseOcorrences> bbs = new LinkedList<>();
+    protected BlockBaseOcorrences current = null;
+    public Integer currentIndex = 0;
+    protected String name;
+
+    BlockBaseGroup(String name) {
+        this.name = name;
+    }
+
+    public void Init() {
+        current = bbs.get(0);
+    }
+
+    public void NextBlock() {
+        currentIndex++;
+        current = bbs.get(currentIndex);
+    }
+
+    public void RegisterBlock(Integer leader, Integer size) {
+        if (current != null) {
+            current.CloseAllIntervals();
+        }
+//        System.out.println("Register block:" + name + "." + bbs.size() + "/" + (size - 1));
+        BlockBaseOcorrences c = new BlockBaseOcorrences(name + "." + bbs.size(), leader);
+        c.LastPosition = (size - 1);
+        current = c;
+        bbs.add(c);
+    }
+
+    public LinkedList<BlockBaseOcorrences> getBasicBlocks() {
+        return bbs;
+    }
+
+    public BlockBaseOcorrences getCurrent() {
+        return current;
+    }
+
+    public void ParseInstruction(Instruction inst, String attrs) {
+        for (String attr : attrs.split(",")) {
+            RegisterInstruction(inst, attr);
+        }
+        current.Position++;
+    }
+
+    public BlockBaseGroup RegisterInstruction(Instruction inst, String attr) {
+//        System.out.println("RegisterInstruction:" + attr);
+        current.Register(inst, attr);
+        return this;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        for (BlockBaseOcorrences blockBaseOcorrences : bbs) {
+            sb.append(blockBaseOcorrences);
+        }
+
+        return sb.toString();
+    }
+
+    public void Close() {
+        current.CloseAllIntervals();
+    }
+
+    public BlockBaseOcorrences Current() {
+        return current;
+    }
+
+    public LinkedList<BlockBaseOcorrences> getBbs() {
+        return bbs;
+    }
+
+    public void setBbs(LinkedList<BlockBaseOcorrences> bbs) {
+        this.bbs = bbs;
+    }
+
+    public Integer getCurrentIndex() {
+        return currentIndex;
+    }
+
+    public void setCurrentIndex(Integer currentIndex) {
+        this.currentIndex = currentIndex;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public BlockBaseOcorrences getBasicBlocks(Integer i) {
+        return bbs.get(currentIndex + i);
+
+    }
+
+}

+ 123 - 77
src/IntermediaryCode/BlockOcorrences.java

@@ -5,8 +5,8 @@
  */
 package IntermediaryCode;
 
-import API.Instruction;
 import API.Utils;
+import common.Instruction;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -18,18 +18,66 @@ import java.util.regex.Pattern;
  *
  * @author EUGENIO CARVALHO
  */
-public class BlockOcorrences {
+public class BlockBaseOcorrences {
 
     protected LinkedHashMap<String, LinkedList<Integer>> ocorrences = new LinkedHashMap<>();
     protected LinkedHashMap<String, LinkedList<Interval>> intervals = new LinkedHashMap<>();
-    protected int Position = 0;
-    protected int LastPosition = 0;
+    protected Integer Position = 0;
+    protected Integer leader = 0;
+    protected Integer LastPosition = 0;
     protected Interval interval;
     protected Pattern addresspattern;
     protected String name;
 
-    public BlockOcorrences(String name) {
+    public BlockBaseOcorrences(String name, Integer leader) {
         this.name = name;
+        this.leader = leader;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Integer getLeader() {
+        return leader;
+    }
+
+    public void setLeader(Integer leader) {
+        this.leader = leader;
+    }
+
+    public LinkedHashMap<String, LinkedList<Integer>> All() {
+        return ocorrences;
+    }
+
+    protected boolean Alive(String alias) {
+        if (intervals.containsKey(alias)) {
+            return Position <= intervals.get(alias).peekLast().End;
+        }
+        return false;
+    }
+
+    public boolean Inside(String var, int i) {
+        return Get(var, i) != null;
+    }
+
+    public LinkedList<Interval> Get(String var) {
+        if (!intervals.containsKey(var)) {
+            return null;
+        }
+        return intervals.get(var);
+    }
+
+    protected void OpenInterval(String alias) {
+        if (!intervals.containsKey(alias)) {
+            intervals.put(alias, new LinkedList<Interval>());
+        }
+//        System.out.println("Open interval:(" + alias + "):" + Position + ":" + LastPosition);
+        intervals.get(alias).add(new Interval(Position, LastPosition));
     }
 
     protected void CloseAllIntervals() {
@@ -46,14 +94,13 @@ public class BlockOcorrences {
 
     }
 
-    protected void Register(Instruction x, String attr) {
+    void Register(Instruction x, String attr) {
         String alias = x.G(attr);
-        if (!OcorrenceFinderProcessor.IsAddress(alias)) {
+        if (!BaseBlockProcessor.IsAddress(alias)) {
             return;
         }
         alias = ToAliase(x, attr);
 
-//        System.out.println("Register x:" + x);
         ArrayList<String> aliases = new ArrayList<>();
 
         aliases.add(alias);
@@ -65,79 +112,11 @@ public class BlockOcorrences {
             if (!ocorrences.containsKey(a)) {
                 ocorrences.put(a, new LinkedList<Integer>());
             }
-
             ocorrences.get(a).add(Position);
             if (!Alive(a)) {
                 OpenInterval(a);
             }
         }
-
-    }
-
-    protected boolean Alive(String alias) {
-        if (intervals.containsKey(alias)) {
-            return Position <= intervals.get(alias).peekLast().End;
-        }
-        return false;
-    }
-
-    protected void OpenInterval(String alias) {
-        if (!intervals.containsKey(alias)) {
-            intervals.put(alias, new LinkedList<Interval>());
-        }
-//        System.out.println("Open interval:(" + alias + "):" + Position + ":" + LastPosition);
-        intervals.get(alias).add(new Interval(Position, LastPosition));
-    }
-
-    @Override
-    public String toString() {
-        StringBuilder buffer = new StringBuilder("Block: " + name + "\n");
-        buffer.append("Inst/Var   ");
-        for (int i = 0; i <= LastPosition; i++) {
-            buffer.append(Utils.Pad(i + "", " ", "-", 3));
-        }
-        buffer.append("\n");
-        String append, var, reg;
-        Interval inter;
-
-        for (Map.Entry<String, LinkedList<Integer>> x : ocorrences.entrySet()) {
-            var = x.getKey();
-            buffer.append(Utils.Pad(var, " ", "-", 11));
-
-            for (int i = 0; i <= LastPosition; i++) {
-//                System.out.println("OCOR:" +);
-                reg = "";
-                append = "---";
-                if (x.getValue().contains(i)) {
-//                    append = Get(var, i).getRegister() + "##"; // Ocorrencia da variavel
-                    append = "###"; // Ocorrencia da variavel
-                } else if (Inside(var, i)) {
-                    append = "+++"; // dentro do intervalo
-                }
-
-                inter = Get(x.getKey(), i);
-                if (inter != null) {
-                    reg = inter.getRegister();
-                }
-
-                buffer.append(reg + append.substring(0, append.length() - reg.length()));
-            }
-
-            buffer.append("\n");
-        }
-
-        return buffer.toString();
-    }
-
-    public boolean Inside(String var, int i) {
-        return Get(var, i) != null;
-    }
-
-    public LinkedList<Interval> Get(String var) {
-        if (!intervals.containsKey(var)) {
-            return null;
-        }
-        return intervals.get(var);
     }
 
     public Interval Last(String addr) {
@@ -222,11 +201,78 @@ public class BlockOcorrences {
         if (isdst && x.Has("dst.pointer")) {
 //            System.out.println("Has Pointer:");
             alias = "*" + alias;
-        } else if (!isdst && operators.matcher(op).matches() && x.eq("type", "pointer_assignment")) {
+        } else if (!isdst && operators.matcher(op).matches() && x.eq("type", "pointer_assign")) {
             alias = op + alias;
         }
 //        System.out.println("Aliase:" + alias + ":" + attr + ":" + x);
         return alias;
     }
 
+    @Override
+    public String toString() {
+        StringBuilder buffer = new StringBuilder("Block: " + name + "\n");
+        buffer.append("Inst/Var   ");
+        for (int i = 0; i <= LastPosition; i++) {
+            buffer.append(Utils.Pad(i + "", " ", "-", 3));
+        }
+        buffer.append("\n");
+        String append, var, reg;
+        Interval inter;
+
+        for (Map.Entry<String, LinkedList<Integer>> x : ocorrences.entrySet()) {
+            var = x.getKey();
+            buffer.append(Utils.Pad(var, " ", "-", 11));
+
+            for (int i = 0; i <= LastPosition; i++) {
+//                System.out.println("OCOR:" +);
+                reg = "";
+                append = "---";
+                if (x.getValue().contains(i)) {
+//                    append = Get(var, i).getRegister() + "##"; // Ocorrencia da variavel
+                    append = "###"; // Ocorrencia da variavel
+                } else if (Inside(var, i)) {
+                    append = "+++"; // dentro do intervalo
+                }
+
+                inter = Get(x.getKey(), i);
+                if (inter != null) {
+                    reg = inter.getRegister();
+                }
+
+                buffer.append(reg + append.substring(0, append.length() - reg.length()));
+            }
+
+            buffer.append("\n");
+        }
+
+        return buffer.toString();
+    }
+
 }
+
+//    protected void Register(Instruction x, String attr) {
+//        String alias = x.G(attr);
+//        if (!BaseBlockProcessor.IsAddress(alias)) {
+//            return;
+//        }
+//        alias = ToAliase(x, attr);
+//
+////        System.out.println("Register x:" + x);
+//        ArrayList<String> aliases = new ArrayList<>();
+//
+//        aliases.add(alias);
+//        String index = attr + ".indice";
+//        if (x.Has(index) && !x.isNumber(index)) {
+//            aliases.add(x.G(index));
+//        }
+//        for (String a : aliases) {
+//            if (!ocorrences.containsKey(a)) {
+//                ocorrences.put(a, new LinkedList<Integer>());
+//            }
+//
+//            ocorrences.get(a).add(Position);
+//            if (!Alive(a)) {
+//                OpenInterval(a);
+//            }
+//        }
+//    }

+ 0 - 45
src/IntermediaryCode/CodeClearProcessor.java

@@ -1,45 +0,0 @@
-/*
- * 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 IntermediaryCode;
-
-import API.Instruction;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-class CodeClearProcessor implements CodeProcessing {
-
-    public CodeClearProcessor() {
-    }
-
-    @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
-        String label;
-        Instruction instruction;
-        Block block = c.Block();
-        HashMap<String, Integer> rc = c.labelsReferenceCount;
-        Iterator<Instruction> interator = block.Instructions().iterator();
-        String[] ignore = new String[]{"block", "user"};
-        // Remove todos os labels não referenciados
-        while (interator.hasNext()) {
-            instruction = interator.next();
-
-//            System.out.println("instruction:" + instruction);
-            if (!instruction.eq("type", "label") || instruction.in("label_type", ignore)) {
-                continue;
-            }
-
-            label = instruction.G("label");
-            if (!rc.containsKey(label) || rc.get(label) == 0) {
-                interator.remove();
-            }
-        }
-    }
-}

+ 3 - 1
src/IntermediaryCode/CodeOtimizadorProcessor.java

@@ -1,6 +1,8 @@
 package IntermediaryCode;
 
-import API.Instruction;
+import common.Block;
+import common.Code;
+import common.Instruction;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.LinkedHashMap;

+ 1 - 0
src/IntermediaryCode/CodeProcessing.java

@@ -5,6 +5,7 @@
  */
 package IntermediaryCode;
 
+import common.Code;
 import java.util.LinkedHashMap;
 
 /**

+ 70 - 0
src/IntermediaryCode/DeadInstructionsProcessor.java

@@ -0,0 +1,70 @@
+/*
+ * 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 IntermediaryCode;
+
+import common.Block;
+import common.Code;
+import common.Instruction;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.regex.Pattern;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+class DeadInstructionsProcessor implements CodeProcessing {
+
+    public static Pattern varPattern = Pattern.compile("\\_[VT].*", Pattern.CASE_INSENSITIVE);
+
+    public DeadInstructionsProcessor() {
+    }
+
+    @Override
+    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
+        String dst;
+        Instruction instruction;
+        Block block = c.Block();
+        HashMap<String, Boolean> referenced = new HashMap<>();
+        LinkedList<Instruction> instructions = block.Instructions();
+
+//        System.out.println("instruction:" + instructions.get(2));
+//        throw new Exception("xxxxx");
+
+        String[] params = new String[]{"p1", "p2"};
+        Iterator<Instruction> interator = instructions.descendingIterator();
+        // Remove instrucoes mortas 
+        while (interator.hasNext()) {
+            instruction = interator.next();
+
+//            System.out.println("ClearCode:" + instruction);
+            dst = instruction.G("dst");
+            // Remove a instrucao se:
+            // * A instrucao não esta dentro de um loop
+            // * Tem destino
+            // * É uma variavel local (Variavel ou temporaria)
+            // * E não foi referenciada por instruções seguintes
+
+            if (!instruction.eq("inloop", "true")
+                    && !dst.equals("")
+                    && varPattern.matcher(dst).matches()
+                    && !referenced.containsKey(dst)) {
+
+                interator.remove();
+                continue;
+            }
+
+            for (String param : params) {
+                if (!instruction.eq(param + "value", "true")) {
+                    referenced.put(instruction.G(param), Boolean.TRUE);
+                }
+            }
+        }
+    }
+
+}

+ 2 - 1
src/IntermediaryCode/Filtros.java

@@ -5,7 +5,8 @@
  */
 package IntermediaryCode;
 
-import API.Instruction;
+import common.Code;
+import common.Instruction;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;

+ 3 - 2
src/IntermediaryCode/TacGenInterface.java

@@ -7,6 +7,7 @@ package IntermediaryCode;
 //    sync    recebe  mandando
 //    exec    recebe  mandando
 
+import common.Code;
 import ast.AbstractSyntaxTree;
 import java.util.HashMap;
 
@@ -15,7 +16,7 @@ import java.util.HashMap;
  *
  * @author Eugenio
  */
-public interface TacGenInterface {
+public interface IRGenInterface {
 
     /**
      *
@@ -26,6 +27,6 @@ public interface TacGenInterface {
      */
     public Code Create(AbstractSyntaxTree ast, HashMap<String, String> settings) throws Exception;
 
-//    public TacGenInterface AfterCreate(CodeProcessing p);
+//    public IRGenInterface AfterCreate(CodeProcessing p);
 
 }

+ 176 - 146
src/IntermediaryCode/BaseTacGen.java

@@ -1,18 +1,14 @@
-/*
- * 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 IntermediaryCode;
 
 import API.Api;
 import API.Functions;
-import API.Instruction;
-import API.Tipos;
+import API.Types;
 import API.Utils;
 import API.Variaveis;
 import ast.AbstractSyntaxTree;
 import ast.Node;
+import common.Code;
+import common.Instruction;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -20,27 +16,20 @@ import java.util.LinkedList;
 import java.util.Map;
 import java.util.Stack;
 import java.util.regex.Pattern;
-//            a0      a1
-//    sync    recebe  mandando
-//    exec    recebe  mandando 
-//    synexec recebe  mandando
-
 // Atualizei as labels mas não atualizei as referencias por isso esta sendo removida quando faz a limpeza
+
 /**
  *
  * @author Eugenio
  */
-public final class BaseTacGen implements TacGenInterface {
+public final class IRGenerator implements IRGenInterface {
 
     protected boolean inicializado = false;
     protected int incLabel = 0;
     protected int tmpVarCount = 1;
-//    protected int OrTestAndOccurrence = 0;
-
     protected AbstractSyntaxTree ast;
     protected Code code;
     protected Node calEndAtt;
-    protected Node compileParams;
     protected String label;
     protected String calEndVar;
     protected String calEndSize;
@@ -54,26 +43,32 @@ public final class BaseTacGen implements TacGenInterface {
     protected HashMap<String, Integer> systemCalls = new HashMap<>();
     protected ArrayList<String> currentMatrixvalues = new ArrayList<>();
     protected HashMap<String, ArrayList<String>> matrixValues = new HashMap<>();
-//    protected ArrayList<CodeProcessing> afterCreate = new ArrayList<CodeProcessing>();
-    protected HashMap<String, String> Complements = new HashMap<String, String>() {
+
+    protected LinkedHashMap<String, Long> power2 = new LinkedHashMap<String, Long>() {
         {
-            put("!=", "==");
-            put("==", "!=");
-            put("<", ">=");
-            put("<=", ">");
-            put(">", "<=");
-            put(">=", "<");
+            for (long i = 0; i < 31; i++) {
+                put(Long.toString(Long.valueOf(1 << i)), Long.valueOf(i));
+            }
         }
     };
+
     public static Pattern AddressOperator = Pattern.compile("(\\&|\\*)");
     protected boolean enableOtimization = true;
     protected HashMap<String, String> ArrayShiftMap = new HashMap<>();
-    private int jb = 0;
+    protected int jb = 0;
 
-    public BaseTacGen() throws Exception {
-        for (long i = 0; i < 31; i++) {
-            power2.put(Long.toString(Long.valueOf(1 << i)), Long.valueOf(i));
+    protected Stack<Boolean> loopScope = new Stack<Boolean>() {
+        {
+            push(false);
         }
+    };
+
+    public IRGenerator() throws Exception {
+
+    }
+
+    public IRGenerator(AbstractSyntaxTree ast) {
+        Ast(ast);
     }
 
     protected int calc(ArrayList<Integer> data) {
@@ -104,31 +99,29 @@ public final class BaseTacGen implements TacGenInterface {
         }
     }
 
-    public BaseTacGen(AbstractSyntaxTree ast) {
-        for (long i = 0; i < 31; i++) {
-            power2.put(Long.toString(Long.valueOf(1 << i)), Long.valueOf(i));
-        }
-        Ast(ast);
-    }
-
     public void Ast(AbstractSyntaxTree ast) {
         this.ast = ast;
-        code = new Code("TAC", ast);
-        code.AfterClose("clear.1", new CodeClearProcessor());
-        code.AfterClose("oti.1", new CodeOtimizadorProcessor(enableOtimization));
-//        code.AfterClose("oti.1", new CodeOtimizadorProcessor(false));
-        compileParams = ast.BuildParams();
-
-        code.Template(new template.Template())
+        code = new Code("IR", ast);
+        code
+                // Remove labels não referenciadas
+                .AfterClose("ot.UnusedLabels", new RemoveUnusedLabelsProcessor())
+                // Remove instrucoes mortas
+                // Remove variaveis que são escrias apenas uma vez. Transformando em constantes
+                //                .AfterClose("ot.VariablesConstants", new VariablesConstantsProcessor())
+                //                .AfterClose("ot.DeadInstructions", new DeadInstructionsProcessor())
+                //                // Remove copias
+                .AfterClose("oti.1", new CodeOtimizadorProcessor(enableOtimization))
+                // Especifica o template engine
+                .Template(new template.Template())
+                // Especifica os templates das instruções
                 .Formats(new HashMap<String, String>() {
                     {
-
                         String base = "{[PAD(global.position,_addressLen,' ')]':'}{[T(1)]}{[PAD(block.position,_addressLen,' ')]':'}{[T(2)]}";
-                        String end = "{[T(2)]}{'  T< '[type]' >'}";
+                        String end = "{[T(2)]}{'  T< '[type]' >'} {[T(2)]}{[basicBlock]}";
 
                         put("label", "{[PAD(global.position,_addressLen,' ')]':'}{[T(2)]}{'<'[label]'>'}':'");
                         put("assign", base + "{[dst]}' := '{[p1]}{' '[op]' '}{[p2]}{' --'[comment]}" + end);
-                        put("pointer_assignment", base + "{[dst.pointer]}{[dst]' := '}{[op]}{[p1]}{' --'[comment]}" + end);
+                        put("pointer_assign", base + "{[dst.pointer]}{[dst]' := '}{[op]}{[p1]}{' --'[comment]}" + end);
                         put("unary", base + " {[dst]} ' := '{[op]' '}{[p1]} {' --'[comment]}" + end);
                         put("copy", base + " {[dst]} ' := '{[p1]} {' --'[comment]}" + end);
                         put("jump", base + " 'goto ' {'<'[label]'>'} {' --'[comment]}" + end);
@@ -159,13 +152,11 @@ public final class BaseTacGen implements TacGenInterface {
 //        setOtimizacao(settings.G("clearCode").equals("true"));
         Code code = run();
         // Executa todos os tratametos definidos apos geracao do codigo
-//        AfterCreate();
 
         printVarMap();
 
-//        code.PrintData();
         code.Print();
-        code.printOcorrences();
+
         return code;
     }
 
@@ -188,8 +179,7 @@ public final class BaseTacGen implements TacGenInterface {
             case "dec.var":
 //                Log.PrintInfo("TAC", new Instruction().S("msg", "DECVAR." + n));
                 if (n.find("exprs") != null) {
-                    n.S("class", "dec.var.short")
-                            .S("value", "dec.var.short");
+                    n.S("class", "dec.var.short").S("value", "dec.var.short");
                     genAssign(n);
                     break;
                 }
@@ -262,7 +252,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("p1value", "" + Api.IsValue(dst))
                 .S("p2value", "true")
                 .S("op", n.findByClass("operator").eq("value", "++") ? "+" : "-");
-        code.Add(operacao);
+        Add(operacao);
     }
 
     protected void Selector(Node n) throws Exception {
@@ -352,8 +342,6 @@ public final class BaseTacGen implements TacGenInterface {
         return ret;
     }
 
-    protected LinkedHashMap<String, Long> power2 = new LinkedHashMap<String, Long>();
-
     protected void FindShiftPath(int size, ArrayList<Integer> path) {
         size = Math.abs(size);
         ArrayList<Integer> shift = ShiftInterval(size);
@@ -404,7 +392,7 @@ public final class BaseTacGen implements TacGenInterface {
     }
 
     protected int Size(String type) {
-        return Tipos.Size(type) * 4;
+        return Types.Size(type) * 4;
     }
 
     protected String ArrayShift(Node n) throws Exception {
@@ -761,11 +749,16 @@ public final class BaseTacGen implements TacGenInterface {
             Node stmts = main.find("stmts");
 
             if (stmts.childrens().size() > 0 && code.OpenBlock("main")) {
+//                basicBlock.push("main");
+//                basicBlockCount.push(0);
 
                 PushLabel("main", "block");
                 visit(stmts);
 
                 PushLabel("main-end", "block");
+
+//                basicBlock.pop();
+//                basicBlockCount.pop();
                 code.CloseBlock();
                 return true;
             }
@@ -787,7 +780,6 @@ public final class BaseTacGen implements TacGenInterface {
             }
         }
         code.UpdatePositions();
-
         return code;
     }
 
@@ -836,12 +828,22 @@ public final class BaseTacGen implements TacGenInterface {
      * @throws Exception
      */
     protected void IfCaseStmt(Node n, Node _if, boolean ifChain) throws Exception {
-        Node test = _if.first().first();
+        Node test = _if.first();
+        String testType = "jb";
+
+        if (test.childrens().size() > 1) {
+            visit(test.childrens().get(0));
+            test = test.last();
+        } else {
+            test = test.first();
+        }
+
         Node stmts = _if.find("stmts");
 
         // Se o teste falha deve saltar o bloco 
         n.S("start", gerarLabel());
-        test.S("test.type", "jb").copy("next,start,end", n);
+
+        test.S("test.type", testType).copy("next,start,end", n);
 
         Branch(test, 0);
         // marca com um label o inicio do bloco do if
@@ -882,10 +884,10 @@ public final class BaseTacGen implements TacGenInterface {
     }
 
     protected void _visitExpr(Node n) throws Exception {
-//        System.out.println("VisitExpr:" + n);
         visit(n.childrens().get(0));
         visit(n.childrens().get(1));
 
+//        System.out.println("VisitExpr:" + n);
         switch (n.G("subclass")) {
             case "arith":// ( + | - | * | / ) integer
                 genExpArith(n);
@@ -916,7 +918,7 @@ public final class BaseTacGen implements TacGenInterface {
         if (instruction != null) {
             switch (type) {
                 case "jtb":
-                    instruction.S("op", Complement(instruction.G("op")));
+                    instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
 
                     if (n.parent != null && n.parent.eq("value", "||")) {
                         if (index == 1) {
@@ -937,7 +939,7 @@ public final class BaseTacGen implements TacGenInterface {
                             UpdateLabel(instruction, n.parent.G("skip.test"));
 
                         } else if (index == 2) {
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("next"));
                         }
                     }
@@ -958,7 +960,7 @@ public final class BaseTacGen implements TacGenInterface {
                 case "jtb":
                     if (n.parent != null && n.parent.eq("value", "||")) {
                         if (index == 1) { // teste 1 do parametro 2 com pai ||
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("end"));
                         } else if (index == 2) {  // teste 2 do parametro 2
                             UpdateLabel(instruction, n.G("next"));
@@ -968,12 +970,12 @@ public final class BaseTacGen implements TacGenInterface {
 ////                            throw new Exception("// teste 1 do parametro 2 com pai &&");
 //
 //                        } else if (index == 2) {  // teste 2 do parametro 2 com pai && 
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
 //                            UpdateLabel(instruction, n.G("end"));
 //                        }
                     } else {
                         if (index == 1) {  // teste 1 do parametro 2 geral
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("end"));
                         } else if (index == 2) {
 //                            throw new Exception("teste 2 do parametro 2 geral");
@@ -987,11 +989,11 @@ public final class BaseTacGen implements TacGenInterface {
                     if (n.parent != null && n.parent.eq("value", "||")) {
                         if (index <= 1) {
 //                            UpdateLabel(instruction, n.parent.G("skip.test"));
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("start"));
 
                         } else if (index == 2) {
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("next"));
 
                         }
@@ -1050,20 +1052,20 @@ public final class BaseTacGen implements TacGenInterface {
 //                    if (n.parent != null) {
                     if (n.parent != null && n.parent.eq("value", "||")) {
 //                        if (index == 2) {
-                        instruction.S("op", Complement(instruction.G("op")));
+                        instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                         UpdateLabel(instruction, n.G("start"));
 //                        }
                     } else if (n.parent != null && n.parent.eq("value", "&&")) {
                         if (index <= 1) {
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.parent.G("skip.test"));
                         } else if (index == 2) {
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.parent.G("start"));
                         }
 //                        }
                     } else {
-                        instruction.S("op", Complement(instruction.G("op")));
+                        instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                         if (index <= 1) {
                             UpdateLabel(instruction, n.G("start"));
                         } else if (index == 2) {
@@ -1083,7 +1085,7 @@ public final class BaseTacGen implements TacGenInterface {
                 case "jtb":
                     if (n.parent != null && n.parent.eq("value", "&&")) {
                         if (index == 1) {
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.parent.G("end"));
                         }
                     }
@@ -1093,25 +1095,25 @@ public final class BaseTacGen implements TacGenInterface {
                     if (n.parent != null && n.parent.eq("value", "||")) {
                         if (index <= 1) {
 
-                            instruction.S("op", Complement(instruction.G("op")));
+                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("start"));
 
                         } else if (index == 2) {
 //
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
                             UpdateLabel(instruction, n.G("next"));
                         }
                     } else if (n.parent != null && n.parent.eq("value", "&&")) {
                         if (index == 1) {
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
 //                            UpdateLabel(instruction, n.parent.G("start"));
                         } else if (index == 2) {
-//                            instruction.S("op", Complement(instruction.G("op")));
+//                            instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
 //                            UpdateLabel(instruction, n.parent.G("start"));
                         }
 //                        }
                     } else {
-//                        instruction.S("op", Complement(instruction.G("op")));
+//                        instruction.S("op", Utils.ComplementOperation(instruction.G("op")));
 //                        UpdateLabel(instruction, n.G("next"));
                     }
             }
@@ -1149,7 +1151,7 @@ public final class BaseTacGen implements TacGenInterface {
 
         // Inverte o teste e salta o bloco
         if (invert) {
-            op = Complement(op);
+            op = Utils.ComplementOperation(op);
         }
 //        return Branch(op, p0, p1, next);
         Instruction r1 = new Instruction();
@@ -1164,13 +1166,30 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("label", n.G("next"));
 
 //        System.out.println("Add branch:" + branckInvert.peek() + branckInvert + ">>" + (!branckInvert.isEmpty() && branckInvert.peek()) + "\n" + r1);
-        code.Add(r1);
+        Add(r1);
         return r1;
     }
 
+    protected Instruction Add(Instruction i) throws Exception {
+
+        return code.Add(
+                i.S("inloop", "" + loopScope.peek())
+        //                .S("basicBlock", basicBlock.peek() + "." + basicBlockCount.peek())
+        );
+    }
+
     protected Instruction Branch(Node n, int index) throws Exception {
         Instruction instruction = null;
 
+//        System.out.println("test:" + n);
+//        ArrayList<Node> childrens = n.parent.childrens();
+//        if (childrens.size() > 1) {
+////            visit(childrens.get(0));
+//            Node c = n;
+//            n = childrens.get(1);
+//            n.copy("test.type,next,start,end", c);
+//        }
+//        System.out.println("n:" + n);
         switch (n.getText()) {
             case "&&":
                 BranchAnd(n, index);
@@ -1184,10 +1203,6 @@ public final class BaseTacGen implements TacGenInterface {
         return instruction;
     }
 
-    protected String Complement(String op) {
-        return Complements.get(op);
-    }
-
     /**
      * Cria uma linha de Salto para PuShLabel eSpecificado no parametro.
      *
@@ -1200,7 +1215,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("type", "jump")
                 .S("format", "jump")
                 .set("locker", getIdMaster());
-        code.Add(r);
+        Add(r);
 
     }
 
@@ -1223,10 +1238,10 @@ public final class BaseTacGen implements TacGenInterface {
                     .S("p1value", "" + Api.IsValue(ret.getText()))
                     .S("p1", ret.G("_return"));
             nreg.set("locker", getIdMaster());
-            code.Add(nreg);
+            Add(nreg);
         }
 
-        code.Add(new Instruction()
+        Add(new Instruction()
                 .S("type", "return")
                 .S("format", "return")
                 .set("p1", returns.size())
@@ -1243,7 +1258,8 @@ public final class BaseTacGen implements TacGenInterface {
      */
     protected void genFor(Node n) throws Exception {
         String attrs = "next,end,inc,test";
-        Node test = n.find("test").first();
+
+        loopScope.push(true);
 
         setMaster(n);
 
@@ -1261,13 +1277,22 @@ public final class BaseTacGen implements TacGenInterface {
         Node stmt = n.find("stmts");
 
         stmt.copy(attrs, n);
-        test.copy(attrs, n).S("test.type", "jtb");
+
+        boolean hasTest = false;
+        Node t = n.find("test"), test = null;
+
+        if (t.childrens().size() > 0) {
+            hasTest = true;
+            test = t.first();
+            test.copy(attrs, n).S("test.type", "jtb");
+        }
 
         /*Inicializacoes e atribuicoes*/
         visit(n.find("initialization"));
-
-        /*Salta para o teste do laco*/
-        _goto(testLabel);
+        if (hasTest) {
+            /*Salta para o teste do laco*/
+            _goto(testLabel);
+        }
 
         /*Marca o inicio do bloco do laco*/
         PushLabel(next, "branch");
@@ -1280,22 +1305,24 @@ public final class BaseTacGen implements TacGenInterface {
 
         /*Executa os incrementos*/
         visit(n.find("increment"));
-
-        /*Label que marca o teste do laco*/
-        PushLabel(testLabel, "branch");
-
         // test.type = ((JumpToBlock in LOOP) | (JumpBlock in IF || SWITCH))
         // test.type = JumpToBlock 
 //        test.S("test.type", "for").S("next", next).S("end", end).S("or", next);
 //        System.out.println("Teste:" + test);
-        Branch(test, 0);
+        if (hasTest) {
+            /*Label que marca o teste do laco*/
+            PushLabel(testLabel, "branch");
+
+            Branch(test, 0);
+        } else {
+            _goto(next);
+        }
 
-//        if (n.Has("set.end_label")) {
-//        PushLabel(n.G("end"), "branch");
         PushLabel(end, "branch");
-//        }
 
         setNullMaster();
+
+        loopScope.pop();
     }
 //    protected void genFor(Node n) throws Exception {
 //        setMaster(n);
@@ -1345,6 +1372,7 @@ public final class BaseTacGen implements TacGenInterface {
         Node op2 = n.childrens.get(1);
 
         String _op = n.getText();
+//        System.out.println("Gen genExpArith:" + _op);
 //
 //        
 
@@ -1374,13 +1402,10 @@ public final class BaseTacGen implements TacGenInterface {
         Instruction instruction = __exp(_op, _p1, _p2, _return);
 
         if (instruction.eq("type", "copy")) {
-            n.S("_p1", instruction.G("p1"));
-            n.S("value", instruction.G("p1"));
-        } else {
 
-            n.S("_op", _op);
-            n.S("_p1", _p1);
-            n.S("_p2", _p2);
+            n.S("_p1", instruction.G("p1")).S("value", instruction.G("p1"));
+        } else {
+            n.S("_op", _op).S("_p1", _p1).S("_p2", _p2);
         }
     }
 
@@ -1654,6 +1679,10 @@ public final class BaseTacGen implements TacGenInterface {
      * @throws Exception
      */
     protected void genAssign(Node n) throws Exception {
+
+//        System.out.println("GENAssign :" + n);
+        ArrayList<Node> localExpr = new ArrayList<>();
+
         ArrayList<String> localAttribs = new ArrayList<>(),
                 //                copymode = new ArrayList<>(),
                 //                operators = new ArrayList<>(),
@@ -1669,8 +1698,9 @@ public final class BaseTacGen implements TacGenInterface {
         if (n.in("value", new String[]{"dec.var.short", "def.assign"})) {
 
             for (Node attrib : n.childrens().get(1).childrens()) {
+//                System.out.println(">n:" + attrib);
                 visit(attrib);
-//        System.out.println("n:" + n);
+//                System.out.println("n:" + attrib);
 
 //                System.out.println("genAssign:" + attrib.G("class") + ":" + attrib.G("value"));
                 if (attrib.eq("class", "call")) {
@@ -1703,12 +1733,14 @@ public final class BaseTacGen implements TacGenInterface {
                     copyaddress.add(attrib.eq("subclass", "address"));
                     localAttribs.add(attrib.G("_return"));
                 }
+                localExpr.add(attrib);
             }
         }
 
 //        System.out.println("Copy::" + localAttribs);
 //        System.out.println("Lista de atribuicoes locais:\n" + dsts + "\n>>\n" + n);
 //        System.out.println("Lista de atribuicoes locais:\n" + dsts + "\n>>\n" + localAttribs);
+        Node attrib;
         // Executa a copia dos valores
         for (int dstPosition = 0, i = 0; i < localAttribs.size(); dstPosition++) {
 
@@ -1716,13 +1748,12 @@ public final class BaseTacGen implements TacGenInterface {
             d.S("declare", declare);
             visit(d);
 
-//            System.out.println("D:" + d.childrens());
+//            System.out.println("D:" + d);
             if (d.eq("class", "unary") && d.eq("dst.pointer", "*")) {
-
                 p1 = localAttribs.get(i);
-                code.Add(new Instruction()
-                        .S("format", "pointer_assignment")
-                        .S("type", "pointer_assignment")
+                Add(new Instruction()
+                        .S("format", "pointer_assign")
+                        .S("type", "pointer_assign")
                         .S("dst", d.childrens().get(1).G("_return"))
                         .S("p1", p1)
                         .S("p1value", "" + Api.IsValue(p1))
@@ -1738,12 +1769,20 @@ public final class BaseTacGen implements TacGenInterface {
                 }
             } else {
                 // Copia valor para endereco
-//                System.out.println("Attrib:" + d.G("_return") + "<" + localAttribs.get(i));
-                if (!modify.equals("")) {
+//                System.out.println("Attrib[" + modify + ":" + (modify.equals("")) + "]:" + d.G("_return") + "<" + localAttribs.get(i));
 
+                if (!modify.equals("")) {
                     __exp(modify, d.G("_return"), localAttribs.get(i), d.G("_return")).S("comment", "");
+
                 } else {
+                    attrib = localExpr.get(i);
+
+//                    if (attrib.eq("class", "expr")) {
+////                        System.out.println("Attrib:" + attrib);
+//                        __exp(attrib.G("_op"), attrib.G("_p1"), attrib.G("_p2"), d.G("_return")).S("comment", "");
+//                    } else {
                     Copy(d.G("_return"), localAttribs.get(i), copyaddress.get(i));
+//                    }
                 }
                 i++;
             }
@@ -1757,7 +1796,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("p1", param)
                 .S("p1value", "" + Api.IsValue(param))
                 .set("locker", getIdMaster());
-        code.Add(r);
+        Add(r);
     }
 
     protected void genFunction(String id, Node func) throws Exception {
@@ -1766,6 +1805,8 @@ public final class BaseTacGen implements TacGenInterface {
 
             Node block = func.find("stmts");
 
+//            basicBlock.push(id);
+//            basicBlockCount.push(0);
             code.OpenBlock(id);
             /*Cria a PushLabel inicial da funcao*/
             PushLabel(id, "block");
@@ -1782,6 +1823,8 @@ public final class BaseTacGen implements TacGenInterface {
             /*Cria a PushLabel final da funcao*/
             PushLabel(id + "-end", "block");
             code.CloseBlock();
+//            basicBlock.pop();
+//            basicBlockCount.pop();
         }
     }
 
@@ -1794,7 +1837,7 @@ public final class BaseTacGen implements TacGenInterface {
             Node var = Variaveis.Get(n.G("ctx"));
 //            System.out.println("");
 //            __genParam("&" + gerarVariavel(var));
-//            code.Add(new Instruction()
+//            Add(new Instruction()
 //                    .S("", PushLabel));
 //            gerarVariavel(var)
             __genParam(gerarVariavel(var));
@@ -1871,7 +1914,7 @@ public final class BaseTacGen implements TacGenInterface {
 //            System.out.println("Unary:" + n.childrens().G(1));
             String type;
             if (AddressOperator.matcher(op).matches()) {
-                type = "pointer_assignment";
+                type = "pointer_assign";
             } else {
                 type = "unary";
             }
@@ -1885,7 +1928,7 @@ public final class BaseTacGen implements TacGenInterface {
                     .S("copymode", "unary")
                     .S("p1value", "" + Api.IsValue(_val))
                     .set("locker", getIdMaster());
-            code.Add(r);
+            Add(r);
 //            System.out.println("N:" + n);
 //            throw new Exception("Unary Stmt not defined");
         }
@@ -1894,38 +1937,25 @@ public final class BaseTacGen implements TacGenInterface {
 //        System.out.println("UnaryStmt:[" + _val + ":" + op + "]" + n);
     }
 
-    protected Integer _ExprResolve(String op, String p1, String p2) throws Exception {
-        int p1v = Integer.parseInt(p1),
-                p2v = Integer.parseInt(p2);
-        switch (op.substring(0, 1)) {
-            case "+":
-                return p1v + p2v;
-            case "-":
-                return p1v - p2v;
-            case "*":
-                return p1v * p2v;
-            case "/":
-                return p1v / p2v;
-            case "%":
-                return p1v % p2v;
-        }
-        return null;
-    }
-
     protected Instruction __exp(String op, String p1, String p2, String ret) throws Exception {
+
         boolean p1value = Api.IsValue(p1),
                 p2value = Api.IsValue(p2);
+
         String unsigned = "false";
+
         if (op.contains("u")) {
             op = op.replace("u", "");
             unsigned = "true";
         }
+
         Instruction r = new Instruction();
+
         if (p1value && p2value) {
             r.S("type", "copy")
                     .S("format", "copy")
                     .S("p1value", "true")
-                    .S("p1", "" + _ExprResolve(op, p1, p2));
+                    .S("p1", "" + Utils.ResolveExpr(op, p1, p2));
 
         } else {
             r.S("type", "assign")
@@ -1936,14 +1966,14 @@ public final class BaseTacGen implements TacGenInterface {
                     .S("copymode", "assign")
                     .S("p1value", "" + p1value)
                     .S("p2value", "" + p2value);
-//            System.out.println("__EXP:"+p1value+":"+p2value);
+//            System.out.println("__EXP:" + r);
         }
         r.S("dst", ret)
                 .S("op", op)
                 .S("op.unsigned", unsigned)
                 .set("locker", getIdMaster());
 
-        return code.Add(r);
+        return Add(r);
     }
 
     /**
@@ -2060,7 +2090,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("p1value", "false")
                 .S("_return", varname);
         r.set("locker", getIdMaster());
-        code.Add(r);
+        Add(r);
         return r;
     }
 
@@ -2113,7 +2143,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("p1", src)
                 .S("p1value", Api.IsValue(src) + "")
                 .set("locker", getIdMaster());
-        code.Add(r);
+        Add(r);
         return r;
     }
 
@@ -2147,7 +2177,7 @@ public final class BaseTacGen implements TacGenInterface {
                 .S("format", "label")
                 .set("locker", getIdMaster());
 
-        return code.Add(r);
+        return Add(r);
     }
 
     /**
@@ -2217,7 +2247,7 @@ public final class BaseTacGen implements TacGenInterface {
             varGenMap.put(varname, alias);
 //            vn = var.G("scope");
 
-            int size = Tipos.Size(var.G("type")), elementCount = 1;
+            int size = Types.Size(var.G("type")), elementCount = 1;
             var.set("size", size);
 
 //            System.out.println("gerarVariavelSetVAR:" + var);
@@ -2297,7 +2327,7 @@ public final class BaseTacGen implements TacGenInterface {
             for (Node r : returns.childrens()) {
                 t = gerarVariavel("T");
                 rts.add(t);
-                code.Add(new Instruction()
+                Add(new Instruction()
                         .S("type", "pop_return")
                         .S("format", "pop_return")
                         .S("p1value", "false")
@@ -2328,7 +2358,7 @@ public final class BaseTacGen implements TacGenInterface {
 //        if (!variavelRetorno.equals("")) {
 //            r.S("dst", variavelRetorno);
 //        }
-        code.Add(r);
+        Add(r);
         return r;
     }
 
@@ -2349,7 +2379,7 @@ public final class BaseTacGen implements TacGenInterface {
 //
 ////                if (!loop && branckInvert.size() == 1) {
 ////                    Instruction last = code.Last();
-////                    last.S("op", Complement(last.G("op"))).S("label", n.G("next"));
+////                    last.S("op", Utils.ComplementOperation(last.G("op"))).S("label", n.G("next"));
 ////                }
 //                if (!x.get(0).Has("and")) {
 //                    n.remove("and");
@@ -2385,12 +2415,12 @@ public final class BaseTacGen implements TacGenInterface {
 //            //                }
 
 //    @Override
-//    public TacGenInterface AfterCreate(CodeProcessing p) {
+//    public IRGenInterface AfterCreate(CodeProcessing p) {
 //        this.afterCreate.add(p);
 //        return this;
 //    }
 //
-//    public TacGenInterface AfterCreate() throws Exception {
+//    public IRGenInterface AfterCreate() throws Exception {
 //        for (CodeProcessing x : afterCreate) {
 //            x.Exec(code);
 //        }
@@ -2409,7 +2439,7 @@ public final class BaseTacGen implements TacGenInterface {
 //                .S("label", label);
 //
 ////        System.out.println("Add branch:" + branckInvert.peek() + branckInvert + ">>" + (!branckInvert.isEmpty() && branckInvert.peek()) + "\n" + r1);
-//        code.Add(r1);
+//        Add(r1);
 //        return r1;
 //    }
 //    /**

+ 0 - 83
src/IntermediaryCode/OcorrenceFinderProcessor.java

@@ -1,83 +0,0 @@
-package IntermediaryCode;
-
-/*
- * 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.
- */
-import API.Instruction;
-import API.Utils;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.regex.Pattern;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-public class OcorrenceFinderProcessor implements CodeProcessing {
-
-    protected HashMap<String, BlockOcorrences> blocks = new HashMap<>();
-    protected BlockOcorrences block;
-    public static Pattern addresspattern = Pattern.compile("\\_[VTGC].*", Pattern.CASE_INSENSITIVE);
-
-    public HashMap<String, BlockOcorrences> getBlocks() {
-        return blocks;
-    }
-
-    public void setBlocks(HashMap<String, BlockOcorrences> blocks) {
-        this.blocks = blocks;
-    }
-
-    public BlockOcorrences getBlock() {
-        return block;
-    }
-
-    public void setBlock(BlockOcorrences block) {
-        this.block = block;
-    }
-
-    public static Pattern getAddresspattern() {
-        return addresspattern;
-    }
-
-    public static void setAddresspattern(Pattern addresspattern) {
-        OcorrenceFinderProcessor.addresspattern = addresspattern;
-    }
-
-    public OcorrenceFinderProcessor() {
-    }
-
-    @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
-        String name = c.Block().getName();
-        block = new BlockOcorrences(name);
-        blocks.put(name, block);
-
-        block.LastPosition = c.Block().CurrentAddress - 1;
-
-        for (Instruction x : c.Block().Instructions()) {
-            switch (x.G("type")) {
-                case "label":
-                    break;
-                case "call":
-                    block.CloseAllIntervals();
-                default:
-                    block.Register(x, "dst");
-                    block.Register(x, "p1");
-                    block.Register(x, "p2");
-                    block.Position++;
-            }
-        }
-        // Retorna para o ultimo endereco;
-        block.Position--;
-        // Atualiza todos os encerramentos de intervalo para a ultima ocorrencia da variavel;
-        block.CloseAllIntervals();
-
-    }
-
-    public static boolean IsAddress(String alias) {
-//        System.out.println("Is Address:" + alias + "::" + addresspattern.matcher(alias).matches());
-        return !Utils.Empty(alias) && addresspattern.matcher(alias).matches();
-    }
-}

+ 95 - 0
src/IntermediaryCode/RemoveUnusedLabelsProcessor.java

@@ -0,0 +1,95 @@
+/*
+ * 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 IntermediaryCode;
+
+import API.Utils;
+import common.Block;
+import common.Code;
+import common.Instruction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+class RemoveUnusedLabelsProcessor implements CodeProcessing {
+
+    public RemoveUnusedLabelsProcessor() {
+    }
+
+    @Override
+    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
+        String label;
+        Instruction instruction = null;
+        Block block = c.Block();
+
+        HashMap<String, Integer> rc = c.labelsReferenceCount;
+        LinkedList<Instruction> instructions = block.Instructions();
+        ArrayList<Instruction> remover = new ArrayList();
+        Iterator<Instruction> interator = instructions.iterator();
+        String[] ignore = new String[]{"block", "user"};
+        Instruction branch = null, last;
+        int position = 0;
+
+        System.out.println("block:" + block.getName() + "-------------------------------");
+
+        // Remove todos os labels não referenciados
+        while (interator.hasNext()) {
+            position++;
+            last = instruction;
+            instruction = interator.next();
+
+//            System.out.println("instruction:" + instruction);
+            if (instruction.eq("type", "branch")) {
+                branch = instruction;
+                position = 0;
+            }
+
+            if (position == 3 && branch != null && last.eq("type", "jump")) {
+                System.out.println(":" + branch + last);
+                branch.S("op", Utils.ComplementOperation(branch.G("op")))
+                        .S("label", last.G("label"));
+                branch = null;
+//                instructions.remove(last);
+//                interator.remove();
+
+//                interator.remove(last);
+                remover.add(last);
+                remover.add(instruction);
+                
+//                System.out.println("'ERA UMA LABEL:" + instruction);
+                continue;
+            }
+//            if (position == 1 //                    && instruction.eq("type", "label") //                    && (last != null && last.eq("type", "jump"))
+//                    ) {
+//
+////
+////                instructions.remove(last);
+////                instructions.remove(instruction);
+////
+////                continue;
+//            }
+
+            if (!instruction.eq("type", "label") || instruction.in("label_type", ignore)) {
+                continue;
+            }
+
+            label = instruction.G("label");
+            if (!rc.containsKey(label) || rc.get(label) == 0) {
+                interator.remove();
+            }
+        }
+
+//        System.out.println("Remover:" + remover);
+        for (Instruction r : remover) {
+            instructions.remove(r);
+        }
+    }
+}

+ 1 - 1
src/IntermediaryCode/TestInstruction.java

@@ -5,7 +5,7 @@
  */
 package IntermediaryCode;
 
-import API.Instruction;
+import common.Instruction;
 
 /**
  *

+ 110 - 0
src/IntermediaryCode/VariablesConstantsProcessor.java

@@ -0,0 +1,110 @@
+/*
+ * 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 IntermediaryCode;
+
+import API.Utils;
+import common.Block;
+import common.Code;
+import common.Instruction;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+class VariablesConstantsProcessor implements CodeProcessing {
+
+    private Block block;
+    private Iterator<Instruction> interator;
+    private Instruction instruction;
+
+    public VariablesConstantsProcessor() {
+    }
+
+    @Override
+    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
+//        String label, dst;
+        String dst;
+
+        block = c.Block();
+        HashMap<String, Integer> varUpdate = new HashMap<>();
+//        HashMap<String, Integer> rc = c.labelsReferenceCount;
+        interator = block.Instructions().iterator();
+        // Remove todos os labels não referenciados
+        while (interator.hasNext()) {
+            instruction = interator.next();
+            dst = instruction.G("dst");
+            if (!dst.equals("")) {
+                if (!varUpdate.containsKey(dst)) {
+                    varUpdate.put(dst, 0);
+                }
+                varUpdate.put(dst, varUpdate.get(dst) + 1);
+            }
+        }
+
+//        System.out.println("varUpdate:" + varUpdate);
+        interator = block.Instructions().iterator();
+        int i = 0, value;
+        while (interator.hasNext()) {
+            instruction = interator.next();
+            dst = instruction.G("dst");
+            // Se a variavel foi escrita apenas uma vez e o valor atribuido não for uma variavel
+            if (!dst.equals("")
+                    && varUpdate.get(dst) == 1
+                    && instruction.eq("p1value", "true")) {
+
+//                    && ) {
+//                if (instruction.eq("type", "assign")) {
+//
+//                }
+                ReplaceConstant(dst, Resolve(instruction), i);
+
+                interator.remove();
+            }
+            i++;
+        }
+    }
+
+    protected String Resolve(Instruction instruction) throws Exception {
+        System.out.println("instruction:"+ instruction);
+        int value = instruction.getInt("p1");
+        
+        switch (instruction.G("cat")) {
+            case "exp":
+                if (instruction.eq("p2value", "true")) {
+                    value = Utils.ResolveExpr(
+                            instruction.G("op"),
+                            value,
+                            instruction.getInt("p2"));
+
+                }
+        }
+
+        return "" + value;
+    }
+
+    private void ReplaceConstant(String dst, String value, int i) {
+        LinkedList<Instruction> instructions = block.Instructions();
+        int size = instructions.size();
+        String[] fields = new String[]{"p1", "p2"};
+
+        for (; i < size; i++) {
+            instruction = instructions.get(i);
+            for (String field : fields) {
+
+                if (instruction.eq(field, dst)) {
+                    instruction.S(field, value);
+                    instruction.S(field + "value", "true");
+                }
+            }
+        }
+
+    }
+
+}

+ 1 - 1
src/Output/Mif.java

@@ -6,7 +6,7 @@
 package Output;
 
 import API.Api;
-import API.Instruction;
+import common.Instruction;
 import API.Utils;
 import java.io.File;
 import java.io.FileWriter;

+ 1 - 1
src/Output/MifFactory.java

@@ -10,7 +10,7 @@ import API.Traps;
 import remove.FormatadorMips;
 import remove.MipsCodeGen;
 import IntermediaryCode.TestInstruction;
-import API.Instruction;
+import common.Instruction;
 import API.Utils;
 import java.io.IOException;
 import java.util.ArrayList;

+ 1 - 1
src/ast/Node.java

@@ -5,7 +5,7 @@
  */
 package ast;
 
-import API.RegistroBase;
+import common.RegistroBase;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Map;

+ 13 - 13
src/ast/Semantic.java

@@ -6,8 +6,8 @@
 package ast;
 
 import API.Functions;
-import API.Instruction;
-import API.Tipos;
+import common.Instruction;
+import API.Types;
 import API.Variaveis;
 import static ast.Semantic.current;
 import common.Log;
@@ -129,7 +129,7 @@ public class Semantic extends Log {
 
         String type = current.G("type");
 
-        if (!Tipos.Primitive(type) && !Tipos.Defined(type)) {
+        if (!Types.Primitive(type) && !Types.Defined(type)) {
             AddError(new Instruction()
                     .S("class", "Type")
                     .S("msg", String.format("Tipo '%s' não definido", type))
@@ -436,7 +436,7 @@ public class Semantic extends Log {
 ////        
 //        String eTipo = parent.G("tipo"), aTipo = tipo(value);
 //
-//        if (var.igual("tipo", Tipos.REFERENCE)) {
+//        if (var.igual("tipo", Types.REFERENCE)) {
 //            if (isDeclaracao && value.diferente("acessoEndereco", "true")) {
 //                AddError(Api.getFormatedPosition(value) + " Atribuição invalida. Reference ainda não aponta para uma área de memoria valida!");
 //            }
@@ -786,7 +786,7 @@ public class Semantic extends Log {
 //     */
 //    protected boolean _testeTipoValido(Node n) throws Exception {
 //        String tipo = n.G("tipo");
-//        boolean exit = Tipos.existe(tipo);
+//        boolean exit = Types.existe(tipo);
 //        if (!exit) {
 //            AddError(Api.getFormatedPosition(n) + " Tipo invalido. Tipo {" + tipo + "} não definido.");
 //        }
@@ -828,7 +828,7 @@ public class Semantic extends Log {
 //        String tipoEsperado = parent.G("tipo"),
 //                tipoAtribuido = tipo(current.first());
 //
-//        if (!tipoAtribuido.equals(tipoEsperado) && !tipoAtribuido.equals(Tipos.REFERENCE)) {
+//        if (!tipoAtribuido.equals(tipoEsperado) && !tipoAtribuido.equals(Types.REFERENCE)) {
 //            AddErrorWithPosition(" Tipo de retorno invalido. Retornando {" + tipoAtribuido + "} enquanto o esperador é {" + tipoEsperado + "}");
 //        }
 //    }
@@ -885,7 +885,7 @@ public class Semantic extends Log {
 //            return false;
 //        }
 //
-//        Node pTipo = Tipos.G(tipoParent);
+//        Node pTipo = Types.G(tipoParent);
 //        String atributo = Variaveis.clearName(current.getText());
 //        Node dec = pTipo.first().encontre(atributo);
 //        /*Verifica se o atributo existe*/
@@ -1037,11 +1037,11 @@ public class Semantic extends Log {
 //            for (Node param : parampas) {
 //                param = param.first();
 //
-//                tipoAtrib = Tipos.tipoDe(param, param.G("tipo"));
+//                tipoAtrib = Types.tipoDe(param, param.G("tipo"));
 //                tipoEsper = paramdec.G(i++).G("tipo");
 //
 //                if (tipoEsper.equals(tipoAtrib)
-//                        || tipoEsper.equals(Tipos.REFERENCE)) {
+//                        || tipoEsper.equals(Types.REFERENCE)) {
 //                    continue;
 //                }
 //
@@ -1171,7 +1171,7 @@ public class Semantic extends Log {
 //        for (Node node : current.childrens()) {
 //            type = tipo(node);
 //
-//            if (testExist(node, false) && (!type.equals(Tipos.REFERENCE) && !type.equals("int"))) {
+//            if (testExist(node, false) && (!type.equals(Types.REFERENCE) && !type.equals("int"))) {
 //
 //                AddError(Api.getFormatedPosition(node) + " Tipo esperado {int}. "
 //                        + " Operando {" + i + "}  é do tipo {" + node.getText() + " | " + type + "}");
@@ -1206,13 +1206,13 @@ public class Semantic extends Log {
 //            case "expr::and":
 //            case "expr::comp":
 //            case "value.boolean":
-//                return Tipos.BOOLEAN;
+//                return Types.BOOLEAN;
 //
 //            case "expr::unary":
 //            case "expr::negative":
 //            case "expr::arithmetic":
 //            case "value.integer":
-//                return Tipos.INTEGER;
+//                return Types.INTEGER;
 //        }
-//        return Tipos.UNDEFINED;
+//        return Types.UNDEFINED;
 //    }

+ 2 - 2
src/API/AllocatorInterface.java

@@ -3,9 +3,9 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package API;
+package common;
 
-import IntermediaryCode.Code;
+import common.Code;
 
 /**
  *

+ 1 - 2
src/IntermediaryCode/Block.java

@@ -3,9 +3,8 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package IntermediaryCode;
+package common;
 
-import API.Instruction;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedList;

+ 77 - 22
src/IntermediaryCode/Code.java

@@ -3,9 +3,10 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package IntermediaryCode;
+package common;
 
-import API.Instruction;
+import IntermediaryCode.CodeProcessing;
+import IntermediaryCode.Ocorrence;
 import ast.AbstractSyntaxTree;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -51,6 +52,10 @@ public class Code {
     protected LinkedHashMap<String, CodeProcessing> afterClose = new LinkedHashMap<>();
     protected LinkedHashMap<String, CodeProcessing> afterOpen = new LinkedHashMap<>();
 //    protected DataFrame gdata;
+    protected LinkedHashMap<String, CodeProcessing> beforeTranslate = new LinkedHashMap<>();
+    protected LinkedHashMap<String, CodeProcessing> beforeTranslateBlock = new LinkedHashMap<>();
+    protected LinkedHashMap<String, CodeProcessing> afterTranslate = new LinkedHashMap<>();
+    protected LinkedHashMap<String, CodeProcessing> afterTranslateBlock = new LinkedHashMap<>();
 
     public Code(String id, AbstractSyntaxTree arvore) {
         name = id;
@@ -83,7 +88,7 @@ public class Code {
         System.out.println("Blocks:" + stmts.keySet());
     }
 
-    protected void setOtimizacao(boolean lc) {
+    public void setOtimizacao(boolean lc) {
         limparCodigo = lc;
     }
 
@@ -143,12 +148,14 @@ public class Code {
         }
     }
 
-    public void BeforeOpen(String id, CodeProcessing c) {
+    public Code OnOpenBlock(String id, CodeProcessing c) {
         afterOpen.put(id, c);
+        return this;
     }
 
-    public void AfterClose(String id, CodeProcessing c) {
+    public Code AfterClose(String id, CodeProcessing c) {
         afterClose.put(id, c);
+        return this;
     }
 
     public void Use(String id) {
@@ -227,7 +234,7 @@ public class Code {
         return templates.get(template);
     }
 
-    void RemoveLabelReference(String label) {
+    public void RemoveLabelReference(String label) {
         if (!labelsReferenceCount.containsKey(label)) {
             return;
         }
@@ -237,7 +244,7 @@ public class Code {
         }
     }
 
-    void AddLabelReference(String label) {
+    public void AddLabelReference(String label) {
         int count = 0;
         if (labelsReferenceCount.containsKey(label)) {
             count = labelsReferenceCount.get(label);
@@ -245,7 +252,7 @@ public class Code {
         labelsReferenceCount.put(label, count + 1);
     }
 
-    protected Instruction Add(Instruction nr) throws Exception {
+    public Instruction Add(Instruction nr) throws Exception {
         boolean add = true;
 
         // Se for um acesso ao label registra. a informação é utilizada para remover labels não referenciadas;
@@ -407,19 +414,18 @@ public class Code {
 //        this.commentPrefix = cp;
 //        return this;
 //    }
-    public void printOcorrences() {
-//        System.out.println("VARIABLES OCORRENCES ...................");
-//        for (Map.Entry<String, HashMap<String, Ocorrence>> entry : ocorrenciasGerais.entrySet()) {
-        //todo
-//        for (Map.Entry<String, HashMap<String, Ocorrence>> o : ocorrencesPerBlocks.entrySet()) {
-//            System.out.println("Block: " + o.getKey());
-//            for (Map.Entry<String, Ocorrence> x : o.getValue().entrySet()) {
-//                System.out.println(x);
-//            }
-//        }
-//        }
-    }
-
+//    public void printOcorrences() {
+////        System.out.println("VARIABLES OCORRENCES ...................");
+////        for (Map.Entry<String, HashMap<String, Ocorrence>> entry : ocorrenciasGerais.entrySet()) {
+//        //todo
+////        for (Map.Entry<String, HashMap<String, Ocorrence>> o : ocorrencesPerBlocks.entrySet()) {
+////            System.out.println("Block: " + o.getKey());
+////            for (Map.Entry<String, Ocorrence> x : o.getValue().entrySet()) {
+////                System.out.println(x);
+////            }
+////        }
+////        }
+//    }
     public String Name() {
         return this.name;
     }
@@ -436,7 +442,7 @@ public class Code {
     public void UpdatePositions() throws Exception {
         // Reseta a posicao inicial;
         PosicaoLabel = 0;
-        for (Map.Entry<String, IntermediaryCode.Block> x : stmts.entrySet()) {
+        for (Map.Entry<String, common.Block> x : stmts.entrySet()) {
             x.getValue().Update();
         }
     }
@@ -455,4 +461,53 @@ public class Code {
 //        return gdata;
 //    }
 
+    public Code BeforeTranslate(String id, CodeProcessing processor) {
+        beforeTranslate.put(id, processor);
+        return this;
+    }
+
+    public Code BeforeTranslateBlock(String id, CodeProcessing processor) {
+        beforeTranslateBlock.put(id, processor);
+        return this;
+    }
+
+    public Code AfterTranslate(String id, CodeProcessing processor) {
+        afterTranslate.put(id, processor);
+        return this;
+    }
+
+    public Code AfterTranslateBlock(String id, CodeProcessing processor) {
+        afterTranslateBlock.put(id, processor);
+        return this;
+    }
+
+    public Code BeforeTranslate() throws Exception {
+        for (Map.Entry<String, CodeProcessing> codeProcessing : beforeTranslate.entrySet()) {
+            codeProcessing.getValue().Exec(this, beforeTranslate);
+        }
+        return this;
+    }
+
+    public Code BeforeTranslateBlock() throws Exception {
+        for (Map.Entry<String, CodeProcessing> codeProcessing : beforeTranslateBlock.entrySet()) {
+            codeProcessing.getValue().Exec(this, beforeTranslateBlock);
+        }
+        return this;
+    }
+
+    public Code AfterTranslate() throws Exception {
+//        System.out.println("AfterTranslate:" + afterTranslate.entrySet().size());
+        for (Map.Entry<String, CodeProcessing> codeProcessing : afterTranslate.entrySet()) {
+            codeProcessing.getValue().Exec(this, afterTranslate);
+        }
+        return this;
+    }
+
+    public Code AfterTranslateBlock() throws Exception {
+        for (Map.Entry<String, CodeProcessing> codeProcessing : afterTranslateBlock.entrySet()) {
+            codeProcessing.getValue().Exec(this, afterTranslateBlock);
+        }
+        return this;
+    }
+
 }

+ 144 - 79
src/IntermediaryCode/DataFrame.java

@@ -3,17 +3,15 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package IntermediaryCode;
+package common;
 
 import API.Utils;
-import ast.AbstractSyntaxTree;
 import ast.Node;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -24,34 +22,50 @@ import java.util.regex.Pattern;
 public class DataFrame {
 
     protected String name;
-    protected LinkedHashMap<String, Node> values = new LinkedHashMap<>();//Map< String, String> copy = new TreeMap<>();
+    protected LinkedHashMap<String, Node> values = new LinkedHashMap<>();
+    // address guarda o endereço de cada variavel
+    protected LinkedHashMap<String, Integer> address = new LinkedHashMap<>();
 //    protected LinkedList<Node> values = new LinkedList<>();//Map< String, String> copy = new TreeMap<>();
 //    protected HashMap<String, Integer> size = new LinkedHashMap<>();
 //    protected HashMap<String, Integer> type = new LinkedHashMap<>();
 //    protected HashMap<String, Integer> _offset_ = new LinkedHashMap<>();
     protected boolean initialized = false;
-    protected static AbstractSyntaxTree ast;
+    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
 
+//    protected static AbstractSyntaxTree ast;
     public static int TYPE_ARGUMENT = 0;
     public static int TYPE_VAR = 1;
     public static int TYPE_RETURN = 2;
     public static int TYPE_STACK = 3;
 
     public int offsetctrl = 0;
-    protected DataFrame data;
+    protected DataFrame global;
+    // Guarda o tamanho do frame
+    // É atualizado sempre que o mapeamento dos endereços sofre alteração.
+
+    private int frameSize;
 
     public DataFrame(String name, DataFrame data) {
         this.name = name;
-        this.data = data;
-
+        this.global = data;
     }
 
-    public void setInicializar(boolean init) {
+    public void SetInitialized(boolean init) {
         initialized = init;
     }
 
-    public DataFrame Add(String alias, Node var, int elements) {
-        //        System.out.println("Add data to frame:" + var);
+    public void Set(String vname, Node copy) throws Exception {
+        values.put(
+                vname,
+                copy
+        );
+
+        address.put(vname, frameSize);
+        frameSize += copy.getInt("size");
+    }
+
+    public DataFrame Add(String alias, Node var, int elements) throws Exception {
+        //        System.out.println("Add global to frame:" + var);
 //        int vSize = 1;
 //        int size = var.getInt("size"), vSize = 1;
 //        boolean isArray = var.eq("array", "true");
@@ -59,63 +73,54 @@ public class DataFrame {
 //            vSize = Tipos.Size(var.G("type"));
 //        }
         ArrayList<String> defaults = var.getList("default.values");
-        Integer size = defaults.size();
 
+        Integer defSize = defaults.size();
+        String vname;
+        Node copy;
         for (int i = 0; i < elements; i++) {
-
-            values.put(
-                    alias + "." + i,
-                    var.copy().S("default.value", (i < size ? defaults.get(i) : "0"))
-            );
+            vname = alias + "." + i;
+            copy = var.copy().S("default.value", (i < defSize ? defaults.get(i) : "0"));
+            Set(vname, copy);
+//            values.put(
+//                    vname,
+//                    copy
+//            );
+//
+//            address.put(vname, frameSize);
+//            frameSize += copy.getInt("size");
         }
 
         return this;
     }
 
-//    public DataFrame Add(String alias, Node var) throws Exception {
-////        System.out.println("Add data to frame:" + var);
-//        int size = var.getInt("size"), vSize = 1;
-////        boolean isArray = var.eq("array", "true");
-//
-////        if (isArray) {
-////            vSize = Tipos.Size(var.G("type"));
-////        }
-//        for (int i = 0; i < size; i++) {
-//            values.put(
-//                    alias + "." + i,
-//                    var.copy().S("size", vSize)
-//            );
-//        }
-//
-//        return this;
-//    }
     public LinkedHashMap<String, Node> values() {
         return values;
     }
 
     public boolean has(String id) {
-        for (Map.Entry<String, Node> x : values.entrySet()) {
-            if (x.getKey().equals(id)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    public static void setAbstractSyntaxTree(AbstractSyntaxTree ast) {
-        DataFrame.ast = ast;
+        return values.containsKey(id);
+//        for (Map.Entry<String, Node> x : values.entrySet()) {
+//            if (x.getKey().equals(id)) {
+//                return true;
+//            }
+//        }
+//        return false;
     }
 
+//    public static void setAbstractSyntaxTree(AbstractSyntaxTree ast) {
+//        DataFrame.ast = ast;
+//    }
     public int Size() {
-        int val = 0;
-        for (Map.Entry<String, Node> v : values.entrySet()) {
-            try {
-                val += v.getValue().getInt("size");
-            } catch (Exception ex) {
-                Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
-            }
-        }
-        return val;
+        return frameSize;
+//        int val = 0;
+//        for (Map.Entry<String, Node> v : values.entrySet()) {
+//            try {
+//                val += v.getValue().getInt("size");
+//            } catch (Exception ex) {
+//                Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
+//            }
+//        }
+//        return val;
     }
 
     @Override
@@ -141,7 +146,7 @@ public class DataFrame {
     }
 
     /**
-     * Formata oS haSh para a impreSSão no metodatao toString
+     * Formata oS haSh para a impreSSão no metoglobalo toString
      *
      * @param hash
      * @return
@@ -157,31 +162,42 @@ public class DataFrame {
         return r;
     }
 
-    public int Offset(String id) {
-        if (id.contains("_G") && data != null) {
-            return data.Offset(id);
-        }
+    public int Offset(String id) throws Exception {
         int offset = 0;
+        if (id.contains("_G") && global != null) {
+            return global.Offset(id);
+        }
+        id = normalize(id);
         try {
-//            String cp = id;
-            id = normalize(id);
-
-            for (Map.Entry<String, Node> x : values.entrySet()) {
-//                System.out.println("Offset:(" + id + ")" + x.getKey());
-
-                if (!x.getKey().equals(id)) {
-                    offset += x.getValue().getInt("size");
-                    continue;
-                }
-                break;
-            }
-        } catch (Exception ex) {
-            Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
+            offset = address.get(id);
+        } catch (Exception e) {
+            System.out.println("address(" + id + ")[" + frameSize + "].:"
+                    + address
+                    + values
+            );
+            throw new Exception("Invalid offset!");
         }
         return offset;
-    }
 
-    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
+//        int offset = 0;
+//        try {
+////            String cp = id;
+//            id = normalize(id);
+//
+//            for (Map.Entry<String, Node> x : values.entrySet()) {
+////                System.out.println("Offset:(" + id + ")" + x.getKey());
+//
+//                if (!x.getKey().equals(id)) {
+//                    offset += x.getValue().getInt("size");
+//                    continue;
+//                }
+//                break;
+//            }
+//        } catch (Exception ex) {
+//            Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
+//        }
+//        return offset;
+    }
 
     protected String normalize(String id) {
         String shift = "0", index;
@@ -202,21 +218,27 @@ public class DataFrame {
     }
 
     public DataFrame copy(DataFrame data) {
+        String k;
         for (Map.Entry<String, Node> x : data.values().entrySet()) {
-//            System.out.println("Copy:" + x.getKey() + "-" + x.getValue());
-            this.values.put(x.getKey(), x.getValue());
+            System.out.println("Copy:" + x.getKey() + "-" + x.getValue());
+            k = x.getKey();
+            values.put(k, x.getValue());
+            address.put(k, data.address.get(x));
         }
+        frameSize = data.frameSize;
         return this;
     }
 
-    void Replace(String dst, String p1) {
+    public void Replace(String dst, String p1) {
         String rest;
 //        System.out.println("Replace >> " + this.values);
 
         LinkedHashMap<String, Node> add = new LinkedHashMap<>();
 
         for (Map.Entry<String, Node> x : this.values.entrySet()) {
+
             rest = x.getKey().replace(dst, "");
+
             if (rest.equals("") || rest.substring(0, 1).equals(".")) {
                 add.put(p1 + rest, x.getValue());
             } else {
@@ -224,8 +246,51 @@ public class DataFrame {
             }
         }
         this.values = add;
-
 //        System.out.println("Replace << " + this.values);
     }
 
+    void Remove(String dst) throws Exception {
+        boolean init = false;
+        Iterator<String> it = values.keySet().iterator();
+        String next;
+        int diff = 0;
+        while (it.hasNext()) {
+            next = it.next();
+            if (next.contains(dst)) {
+                if (!init) {
+                    init = true;
+                }
+                diff += values().get(next).getInt("size");
+                it.remove();
+                continue;
+            }
+
+            if (init) {
+                address.put(next, address.get(next) - diff);
+            }
+        }
+
+        frameSize -= diff;
+
+        System.out.println("Remove:" + dst + "\n" + values);
+    }
+
 }
+
+//    public DataFrame Add(String alias, Node var) throws Exception {
+////        System.out.println("Add global to frame:" + var);
+//        int size = var.getInt("size"), vSize = 1;
+////        boolean isArray = var.eq("array", "true");
+//
+////        if (isArray) {
+////            vSize = Tipos.Size(var.G("type"));
+////        }
+//        for (int i = 0; i < size; i++) {
+//            values.put(
+//                    alias + "." + i,
+//                    var.copy().S("size", vSize)
+//            );
+//        }
+//
+//        return this;
+//    }

+ 2 - 1
src/API/Instruction.java

@@ -3,8 +3,9 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package API;
+package common;
 
+import common.RegistroBase;
 import java.util.Map;
 
 /**

+ 3 - 3
src/compiler/IvannosysTargetArch.java

@@ -3,10 +3,10 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package compiler;
+package common;
 
-import API.Instruction;
-import IntermediaryCode.Code;
+import common.Instruction;
+import common.Code;
 
 /**
  *

+ 0 - 1
src/common/Log.java

@@ -5,7 +5,6 @@
  */
 package common;
 
-import API.Instruction;
 import java.util.ArrayList;
 import java.util.List;
 

+ 1 - 1
src/API/RegistroBase.java

@@ -3,7 +3,7 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package API;
+package common;
 
 import java.util.ArrayList;
 import java.util.HashMap;

+ 1 - 1
src/compiler/SyntaxError.java

@@ -3,7 +3,7 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package compiler;
+package common;
 
 import common.ErrorReport;
 import java.io.PrintWriter;

+ 11 - 9
src/compiler/IVANNOSYS.java

@@ -6,7 +6,7 @@ package compiler;
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-import IntermediaryCode.BaseTacGen;
+import IntermediaryCode.IRGenerator;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
@@ -36,11 +36,14 @@ public class IVANNOSYS {
                     compiler = new IvannosysCompiler(
                             //                            "src\\samples\\program.go",
                             //                            "src\\samples\\program.go",
-                            "src\\samples\\program_mult_manycore.go",
+                            //                            "src\\samples\\program_mult_manycore.go",
+                            //                            "src\\samples\\program_mult_jon.go",
+                            //                            "src\\samples\\program_mult.go",
+                            "src\\samples\\program_jun_bit_count.go",
                             "UTF-8",
                             IvannosysCompiler.INPUT_FILE)
                             // Especifica a classe de geração de codigo de tres enderecos
-                            .TacGen(new BaseTacGen())
+                            .TacGen(new IRGenerator())
                             // Especifica a classe de geração de codigo alvo mips
                             .RegisterTarget("mips", new target.mips.Gen())
                             .RegisterTarget("mipsjun", new target.mips.jun.Gen())
@@ -49,14 +52,13 @@ public class IVANNOSYS {
                             .EnvPathVar("IVANPATH")
                             // Extensao dos arquivos 
                             .setExtensionLibrary(".go")
-                            .setSetting("developement", "true")
-                            .setSetting("displayAst", "true")
-                            .setSetting("displayTac", "true")
-                            .setSetting("clearCode", "false")
+                            .SetOption("developement", "true")
+                            .SetOption("displayAst", "true")
+                            .SetOption("displayTac", "true")
+                            .SetOption("clearCode", "false")
                             .setDisplayParserTree(false)
                             .setDisplayErros(true)
-                            .Compile()
-                            .Simulate();
+                            .Compile();
             }
 
         } catch (Exception ex) {

+ 21 - 65
src/compiler/IvannosysCompiler.java

@@ -5,19 +5,21 @@
  */
 package compiler;
 
+import common.SyntaxError;
+import common.IvannosysTargetArch;
 import API.Api;
 import API.BuildParams;
-import API.Instruction;
-import IntermediaryCode.Code;
-import IntermediaryCode.TacGenInterface;
+import common.Instruction;
+import common.Code;
+import IntermediaryCode.IRGenInterface;
 import ast.AbstractSyntaxTree;
 import ast.Semantic;
 import common.ErrorReport;
 import common.Log;
 import grammar.IvannosysGrammarLexer;
 import grammar.IvannosysGrammarParser;
-import grammar.visitorAndWalkers.IvannosysListener;
-import grammar.visitorAndWalkers.IvannosysVisitor;
+import frontend.Ivannosys.IvannosysListener;
+import frontend.Ivannosys.IvannosysVisitor;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
@@ -36,7 +38,7 @@ import org.antlr.v4.runtime.tree.ParseTreeWalker;
  *
  * @author Eugenio
  */
-public class IvannosysCompiler {
+public final class IvannosysCompiler {
 
     public static final int INPUT_FILE = 0;
     public static final int INPUT_STREAM = 1;
@@ -60,7 +62,7 @@ public class IvannosysCompiler {
     protected String EnvPathVarName = "IVANPATH";
     protected String EnvBinVarName = "IVANBIN";
     protected String EnvRootVarName = "IVANROOT";
-    protected TacGenInterface tac;
+    protected IRGenInterface IR;
 
     IvannosysCompiler(String srcinputprogram, String enc, int inputType) throws Exception {
         settings = new HashMap<>();
@@ -76,8 +78,8 @@ public class IvannosysCompiler {
         }
         encType = enc;
 
-        inicializarSrcPath();
-        inicializarSettings();
+        initSrcPath();
+        initOptions();
     }
 
     protected IvannosysCompiler RegisterTarget(String id, IvannosysTargetArch target) {
@@ -89,7 +91,7 @@ public class IvannosysCompiler {
         return targets.containsKey(id);
     }
 
-    protected void inicializarSrcPath() throws Exception {
+    protected void initSrcPath() throws Exception {
         String[] variavies = new String[]{this.EnvPathVarName, this.EnvRootVarName};
         for (String variavel : variavies) {
             variavel = System.getenv(variavel);
@@ -109,7 +111,7 @@ public class IvannosysCompiler {
      *
      * @return
      */
-    public IvannosysCompiler inicializarSettings() {
+    public IvannosysCompiler initOptions() {
         settings.put("clearCode", "true");
         settings.put("developement", "false");
         settings.put("displayAst", "false");
@@ -118,12 +120,12 @@ public class IvannosysCompiler {
         return this;
     }
 
-    public IvannosysCompiler setSetting(String prop, String valor) {
+    public IvannosysCompiler SetOption(String prop, String valor) {
         settings.put(prop, valor);
         return this;
     }
 
-    public IvannosysCompiler setLimparCodigo(String lc) {
+    public IvannosysCompiler SetClearCode(String lc) {
         settings.put("clearCode", lc);
         return this;
     }
@@ -188,8 +190,8 @@ public class IvannosysCompiler {
 
             DisplayAST(parser);
 
-//            Variaveis.List();
             Semantic semantic = new Semantic(ast);
+
             if (semantic.Execute().HasError()) {
                 abortarPorErro(semantic, "semantic");
             }
@@ -197,10 +199,11 @@ public class IvannosysCompiler {
             /**
              * Etapa de geração de codigo de 3 enderecos
              */
+
             Log.PrintInfo("TAC", new Instruction().S("msg", "Gerando código de três endereços"));
 
-            Code code = tac.Create(ast, settings);
-//            return this;
+            Code code = IR.Create(ast, settings);
+
             for (String arch : BuildParams.Get("target")) {
                 Log.PrintInfo("TAC → TARGET", new Instruction().S("msg", "Gerando código " + arch));
                 Generate(arch, code);
@@ -346,56 +349,9 @@ public class IvannosysCompiler {
         return this;
     }
 
-    public IvannosysCompiler TacGen(TacGenInterface tac) {
-        this.tac = tac;
-        return this;
-    }
-
-    public IvannosysCompiler Simulate() {
-
+    public IvannosysCompiler TacGen(IRGenInterface tac) {
+        this.IR = tac;
         return this;
     }
 
 }
-
-//    protected MifFactory execEtapaGeracaoMif(MipsCodeGen mc) throws Exception {
-//        System.out.println("...................Executando Conversão para binario");
-//        Mif mif = null;
-//
-//        MifFactory mf = new MifFactory(mc);
-//        mc.getBlocks();
-////        mf.criarTraps(true);
-//        HashMap<String, ArrayList<Instruction>> blocos = mc.getBlocks();
-//        ArrayList<Instruction> funcoes = new ArrayList<>();
-//        for (Map.Entry<String, ArrayList<Instruction>> bloco : blocos.entrySet()) {
-//            String nomeBloco = bloco.getKey();
-//            ArrayList<Instruction> b = bloco.getValue();
-//            if (nomeBloco.equals("main")) {
-//                mf.gerarMif(b, new Mif(1024), "mifs\\main");
-//            } else {
-//                funcoes.addAll(b);
-//            }
-//        }
-//        mf.gerarMif(funcoes, new Mif(1024), "mifs\\funcoes");
-//        mif = mf.criarDataStream();
-//        mif.save("mifs\\data");
-//
-//        System.out.println("..................................................ok\n");
-//        return mf;
-//    }
-//    protected void loadInputStream(String path) throws IOException, Exception {
-//        System.out.println("Carregando biblioteca ......................... " + path);
-//
-//        ANTLRInputStream input = new ANTLRFileStream(path, encType);
-//        IvannosysGrammarLexer lexer = new IvannosysGrammarLexer(input);
-//        CommonTokenStream tokens = new CommonTokenStream(lexer);
-//        IvannosysGrammarParser parser = new IvannosysGrammarParser((TokenStream) tokens);
-//        IvannosysGrammarParser.InitContext ltree = parser.init(); // begin parsing at init rule
-//
-//        if (settings.G("displaParserTree").equals("true")) {
-////            ((ParserRuleContext) ltree).inspect(parser); //mostra a arvore grafica
-//            displayTree(parser);//mostra a arvore grafica
-//            System.out.println(ltree.toStringTree(parser)); // print LISP-style tree
-//        }
-//        walker.walk(getListener(), ltree); // walk parse tree
-//    }

+ 16 - 0
src/frontend/Ivannosys/IvannosysFrontEnd.java

@@ -0,0 +1,16 @@
+/*
+ * 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 frontend.Ivannosys;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class IvannosysFrontEnd {
+
+    
+}

+ 16 - 12
src/grammar/visitorAndWalkers/IvannosysListener.java

@@ -3,18 +3,18 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package grammar.visitorAndWalkers;
+package frontend.Ivannosys;
 
 import API.BuildParams;
 import API.Functions;
 import API.Imports;
-import API.Instruction;
 import API.Interfaces;
-import API.Tipos;
+import API.Types;
 import API.Utils;
 import API.Variaveis;
 import ast.AbstractSyntaxTree;
 import ast.Node;
+import common.Instruction;
 import common.Log;
 import compiler.IvannosysCompiler;
 import grammar.IvannosysGrammarBaseListener;
@@ -145,7 +145,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         if (packageNames.peek().equals("main")) {
 //            ExtractMeta();
 
-            Tipos.List();
+            Types.List();
 //            Constantes.List();
             BuildParams.List();
             Variaveis.List();
@@ -427,11 +427,11 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 
     public String getTypeOfPrimitive(IvannosysGrammarParser.Primitive_valueContext ctx) {
         if (ctx.T_BOOL_FALSE() != null || ctx.T_BOOL_TRUE() != null) {
-            return Tipos.BOOLEAN;
+            return Types.BOOLEAN;
         } else if (ctx.T_CHAR() != null) {
-            return Tipos.CHAR;
+            return Types.CHAR;
         } else if (ctx.T_INTEIRO() != null) {
-            return Tipos.INTEGER;
+            return Types.INTEGER;
         }
         return "undefined";
     }
@@ -444,16 +444,16 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         String classe = "", type = "", subclasse = "";
 
         if (ctx.T_BOOL_FALSE() != null || ctx.T_BOOL_TRUE() != null) {
-            type = Tipos.BOOLEAN;
+            type = Types.BOOLEAN;
             classe = "value";
             subclasse = "boolean";
 
         } else if (ctx.T_CHAR() != null) {
-            type = Tipos.CHAR;
+            type = Types.CHAR;
             classe = "value";
             subclasse = "char";
         } else if (ctx.T_INTEIRO() != null) {
-            type = Tipos.INTEGER;
+            type = Types.INTEGER;
             classe = "value";
             subclasse = "integer";
         } else {
@@ -529,7 +529,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         String typename = ctx.ltype;
         // Adiciona o pacote local se não for um tipo primitivo e não possui um pacote
 
-        if (!Tipos.Primitive(typename)) {
+        if (!Types.Primitive(typename)) {
             // local type
             if (typename.indexOf(".") < 0) {
                 typename = packageNames.peek() + "." + typename;
@@ -622,7 +622,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         Node defType = astCurrent();
         try {
 
-            Tipos.Add(packageNames.peek() + "." + defType.getText(), defType);
+            Types.Add(packageNames.peek() + "." + defType.getText(), defType);
 
         } catch (Exception e) {
             errors.AddError((Instruction) new Instruction()
@@ -1067,6 +1067,10 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 
     @Override
     public void exitTest(IvannosysGrammarParser.TestContext ctx) {
+//        if (astCurrent().childrens().size() == 0) {
+//            astCurrent().parent.removeFilho(astCurrent());
+//        }
+
         astReturnLevel();
         super.exitTest(ctx); //To change body of generated methods, choose Tools | Templates.
     }

+ 2 - 2
src/grammar/visitorAndWalkers/IvannosysVisitor.java

@@ -1,7 +1,7 @@
-package grammar.visitorAndWalkers;
+package frontend.Ivannosys;
 
 import API.Imports;
-import API.Instruction;
+import common.Instruction;
 import common.Log;
 import compiler.IvannosysCompiler;
 import grammar.IvannosysGrammarBaseVisitor;

+ 14 - 15
src/samples/program.go

@@ -48,9 +48,22 @@ func laplaciano() {
 
     for i:= 1; i < LM1; i++ {
         for j := 1; j < CM1; j++ {
-lab_1:
             l = origin[i-1][j] + origin[i][j-1] + origin[i][j+1] + origin[i+1][j] - (4 * origin[i][j])
+
+            if l > 255 { l = 255 }
+            result[i][j] = l
+        }
+    }
+}
+
+func main() {
+  preenche_matriz()
+  laplaciano()
+}
+
 /*
+lab_1:
+            l = origin[i-1][j] + origin[i][j-1] + origin[i][j+1] + origin[i+1][j] - (4 * origin[i][j])
 lab_2:
             l = l + origin[i][j-1]
 lab_3:
@@ -62,20 +75,6 @@ lab_5:
 lab_6:
 
 */
-            if l > 255 {
-              l = 255
-            }
-            result[i][j] = l
-        }
-    }
-}
-/*
-*/
-
-func main() {
-  preenche_matriz()
-  laplaciano()
-}
 
 /**
 

+ 1 - 1
src/samples/program_2.go

@@ -159,7 +159,7 @@ FOR3:
       
    <main.L>:
  6:	 0:		pop_param _V2		  T< pop_param >
- 7:	 1:		_T4 := *_V2		  T< pointer_assignment >
+ 7:	 1:		_T4 := *_V2		  T< pointer_assign >
  8:	 2:		_T5 := _T4 + 1		  T< assign >
  9:	 3:		push_return _T5		  T< push_return >
 10:	 4:		return 1		  T< return >

+ 0 - 0
src/samples/program_jun_bit_count.go


Some files were not shown because too many files changed in this diff