Gen.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package target.mips.jun;
  7. import API.BuildParams;
  8. import API.Instruction;
  9. import API.Utils;
  10. import IntermediaryCode.Block;
  11. import IntermediaryCode.Code;
  12. import compiler.IvannosysTargetArch;
  13. import java.util.ArrayList;
  14. import java.util.HashMap;
  15. import java.util.LinkedList;
  16. import java.util.Map;
  17. import java.util.logging.Level;
  18. import java.util.logging.Logger;
  19. import org.json.simple.JSONArray;
  20. import org.json.simple.JSONObject;
  21. import org.json.simple.parser.JSONParser;
  22. import target.mips.Mips;
  23. import target.mips.Registers;
  24. import target.mips.TemplateMips;
  25. import target.mips.UpdateAddressProcessor;
  26. /**
  27. * MipS tranSlation
  28. *
  29. * @author EUGENIO CARVALHO
  30. */
  31. public class Gen extends target.mips.Gen {
  32. public Gen() {
  33. super();
  34. Init();
  35. }
  36. @Override
  37. public IvannosysTargetArch Export() {
  38. try {
  39. Code Target = getTarget(), newCode;
  40. System.out.println("Export MIPSJUN");
  41. // System.out.println("Data:" + Target.GData());
  42. Long stackBaseAddress = 0L,
  43. updateBaseAddress = 0L,
  44. size;
  45. String id,
  46. initFunction,
  47. blockName,
  48. format,
  49. cacheBlockSize = BuildParams.Get("cacheBlockSize").get(0),
  50. base = BuildParams.Get("outputDirectory").get(0);
  51. String[] parts;
  52. Block func;
  53. JSONObject profile;
  54. UpdateAddressProcessor uap = new UpdateAddressProcessor();
  55. ArrayList<String> p = BuildParams.Get("profile");
  56. if (!p.isEmpty()) {
  57. JSONArray pobject = (JSONArray) new JSONParser().parse(p.get(0));
  58. for (Object pro : pobject) {
  59. profile = (JSONObject) pro;
  60. id = (String) profile.get("id");
  61. initFunction = (String) profile.get("initFunction");
  62. parts = initFunction.replace(")", "").split("\\(");
  63. blockName = parts[0];
  64. // Busca o bloco inicial referenciado pelo usuario
  65. func = Target.getBlocks().get(blockName);
  66. if (profile.containsKey("stackBaseAddress")) {
  67. stackBaseAddress = (Long) profile.get("stackBaseAddress");
  68. } else {
  69. // System.out.println("stackBaseAddress:(" + stackBaseAddress + ")(" + MaxStackSize(func) + ")");
  70. size = MaxStackSize(func);
  71. updateBaseAddress = stackBaseAddress
  72. - size
  73. - fixCacheBlockSize(size, Long.parseLong(cacheBlockSize));
  74. }
  75. // Cria um novo codigo para armazenas as instruções do core
  76. newCode = NewCode(id);
  77. // Copia o bloco da funcao e todos os blocos que gerem dependencia
  78. CopyBlock(newCode,
  79. func,
  80. parts,
  81. stackBaseAddress,
  82. true);
  83. // Atualiza os enderecos de salto do codigo
  84. uap.Exec(newCode, null);
  85. format = (String) profile.get("filename");
  86. if (format == null) {
  87. throw new Exception("Arquivo de saida para o core `" + id + "` não definido!");
  88. }
  89. SaveMips(newCode, base + "\\" + String.format(format, "mips"));
  90. SaveDec(newCode, base + "\\" + String.format(format, "dec"));
  91. stackBaseAddress = updateBaseAddress;
  92. // ExecuteCode(newCode);
  93. // break;
  94. // System.out.println("value::" + code);
  95. }
  96. // System.out.println("params:" + getTac().ast.getCompileParams().GetLists());
  97. // System.out.println("params:" + p);
  98. }
  99. // } catch (ParseException ex) {
  100. // Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
  101. } catch (Exception ex) {
  102. Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
  103. }
  104. return this;
  105. // return super.Export(); //To change body of generated methods, choose Tools | Templates.
  106. }
  107. // protected void ExecuteCode(Code c) {
  108. // try {
  109. // String out = "", tmp;
  110. // for (Map.Entry<String, Block> x : c.stmts.entrySet()) {
  111. //// System.out.println(x.getValue().Data());
  112. // for (Instruction instr : x.getValue().Instructions()) {
  113. // tmp = instr.G("inst.dec");
  114. // if (tmp.equals("")) {
  115. // continue;
  116. // }
  117. // out = out.concat(tmp + "\n");
  118. // }
  119. // }
  120. //
  121. // Utils.WriteFile("\\src\\tools\\mips\\memory\\mi2.memory", out);
  122. //
  123. // out = "";
  124. // for (int i = 0, y = 0; i < 2; i++) {
  125. // for (int j = 1; j <= 400; j++, y += 4) {
  126. // out = out.concat(y + ":" + j + "\n");
  127. // }
  128. // }
  129. //
  130. // Utils.WriteFile("\\src\\tools\\mips\\memory\\md2.memory", out);
  131. //
  132. // MipsProcessor sim = new tools.mips.MipsProcessor(new tools.mips.MipsSettings() {
  133. // {
  134. // debugmode = true;
  135. //// stepByStep = true;
  136. // SetInstructionMemoryFile("\\src\\tools\\mips\\memory\\mi2.memory");
  137. // SetDataMemoryFile("\\src\\tools\\mips\\memory\\md2.memory");
  138. // }
  139. // });
  140. //
  141. // sim.SetBreak("5c,84,c8")
  142. // .Run()
  143. // .Persist();
  144. //
  145. // } catch (Exception ex) {
  146. // Logger.getLogger(target.mips.Gen.class.getName()).log(Level.SEVERE, null, ex);
  147. // }
  148. // }
  149. protected Long fixCacheBlockSize(Long size, Long sizeOfBlock) {
  150. Long t = sizeOfBlock;
  151. while (true) {
  152. if (sizeOfBlock > size) {
  153. break;
  154. }
  155. sizeOfBlock += t;
  156. }
  157. return sizeOfBlock - size;
  158. }
  159. protected void SaveMips(Code newCode, String filename) throws Exception {
  160. Utils.WriteFile(filename, newCode.getCodeStream());
  161. }
  162. protected void SaveDec(Code newCode, String filename) throws Exception {
  163. String code = "", tmp;
  164. for (Map.Entry<String, Block> x : newCode.stmts.entrySet()) {
  165. for (Instruction instr : x.getValue().Instructions()) {
  166. tmp = instr.G("inst.dec");
  167. if (tmp.equals("")) {
  168. continue;
  169. }
  170. code = code.concat(Long.parseLong(tmp) + "\n");
  171. }
  172. }
  173. Utils.WriteFile(filename, code);
  174. }
  175. protected Code CopyBlock(Code newCode, Block func, String[] funcCall, Long stackBaseAddress, boolean main) throws Exception {
  176. // Instruction Ninst;
  177. int index = 1;
  178. String blockName = funcCall[0];
  179. newCode.OpenBlock(blockName);
  180. Block block = newCode.Block();
  181. // Carrega os argumentos da chamada
  182. if (funcCall.length > 1) {
  183. // System.out.println("Tinha parametro:" + funcCall[1]);
  184. String[] args = funcCall[1].split(",");
  185. int i = 0;
  186. for (String arg : args) {
  187. // Ninst = new Instruction();
  188. // Variaveis.List();
  189. // System.out.println("Variaveis.Get(arg):" + Variaveis.get("main." + args));
  190. block.Add(Mips.Instruction("addiu")
  191. .S("rs", Registers.R_ZERO)
  192. .S("rt", "a" + (i++))
  193. .S("offset", arg));
  194. }
  195. index += args.length;
  196. }
  197. for (Instruction inst : func.Instructions()) {
  198. block.Add(inst.copy());
  199. }
  200. if (main) {
  201. LinkedList<Instruction> instructions = newCode.Block().Instructions();
  202. // Atualiza o offset da pilha
  203. Instruction first = instructions.get(index);
  204. // System.out.println("CopyBlock[" + stackBaseAddress + "||" + first.getLong("offset") + "]");
  205. first.set("offset", first.getLong("offset") + stackBaseAddress);
  206. // System.out.println("instructions.get(0);" + first);
  207. // Atualiza a ultima instrucao de um retorno para ra -> stop
  208. block.Remove(instructions.get(instructions.size() - 1));
  209. block.Add(Mips.Instruction("stop")
  210. .S("comment", "end of programa"));
  211. }
  212. newCode.CloseBlock();
  213. // Adiciona as funcoes que geram dependencias
  214. HashMap<String, Block> tb = getTarget().getBlocks();
  215. ArrayList<String> deps = tb.get(blockName).GetDependences();
  216. if (!deps.isEmpty()) {
  217. for (String dep : deps) {
  218. CopyBlock(newCode, tb.get(dep), new String[]{dep}, 0l, false);
  219. }
  220. }
  221. return newCode;
  222. }
  223. protected Code NewCode(String id) {
  224. return new Code(id)
  225. .Template(new TemplateMips())
  226. .Formats(formatMips);
  227. }
  228. protected Long MaxStackSize(Block blk) {
  229. HashMap<String, Block> tb = getTarget().getBlocks();
  230. int size = blk.Data().Size();
  231. // System.out.println("data:" + blk.Data());
  232. Long childSize = 0L, tmpChildSize;
  233. ArrayList<String> deps = blk.GetDependences();
  234. if (!deps.isEmpty()) {
  235. for (String dep : deps) {
  236. tmpChildSize = MaxStackSize(tb.get(dep));
  237. if (tmpChildSize > childSize) {
  238. childSize = tmpChildSize;
  239. }
  240. }
  241. }
  242. // System.out.println("MaxStackSize:" + size + "|" + childSize);
  243. return size + childSize;
  244. }
  245. }