TranslateJun.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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 targets.mips;
  7. import API.Utils;
  8. import common.Code;
  9. import common.DataLayout;
  10. import common.Instruction;
  11. import common.IvannosysTargetArch;
  12. import common.Offset;
  13. import java.util.ArrayList;
  14. import java.util.HashMap;
  15. import java.util.LinkedList;
  16. /**
  17. * MipS tranSlation
  18. *
  19. * @author EUGENIO CARVALHO
  20. */
  21. public class Translate extends API.TargetGen {
  22. protected String[] registersKeys = "reg.p1,reg.p2".split(",");
  23. protected ArrayList<String> returnRegisters;
  24. protected HashMap<String, String> AddressCalculated = new HashMap<>();
  25. protected HashMap<String, String> comments = new HashMap<String, String>() {
  26. {
  27. put("beq", "branch if equals");
  28. put("bne", "branch if not equals");
  29. put("blez", "branch if register <= 0");
  30. put("bltz", "branch if register < 0");
  31. put("bgez", "branch if register >= 0");
  32. put("bgtz", "branch if register > 0");
  33. }
  34. };
  35. protected HashMap<String, Boolean> ctrlDataUpdate = new HashMap<>();
  36. public Translate() {
  37. super("mips");
  38. }
  39. @Override
  40. public void TranslateLabel(Instruction inst) throws Exception {
  41. Add(new Instruction()
  42. .Set("type", "label")
  43. .Set("format", "norender")
  44. .Set("label", inst.Get("label")));
  45. getTarget().RegisterLabelAddress(inst.Get("label"));
  46. }
  47. @Override
  48. public void TranslateCopy(Instruction inst) throws Exception {
  49. Instruction c = Copy(inst, inst.Get("reg.dst"));
  50. if (c != null) {
  51. c.Set("comment", F("copy %s ← %s", inst.Get("dst"), inst.Get("p1")));
  52. }
  53. }
  54. @Override
  55. public void TranslateAssign(Instruction inst) throws Exception {
  56. String instruction = Descriprion.InstructionByOperator(inst);
  57. String rd = inst.Get("reg.dst"),
  58. dst = inst.Get("dst"),
  59. op = inst.Get("op"),
  60. rs,
  61. offset;
  62. Instruction ninst = new Instruction(instruction);
  63. switch (Descriprion.Codops.get(instruction).Get("type")) {
  64. //addi, addiu, slti, sltiu
  65. case "I":
  66. ninst.Set("rt", rd);
  67. // System.out.println("Assign:" + inst);
  68. // LoadParam(inst, "p1,p2", true);
  69. if (inst.eq("p2value", "true")) {
  70. // LoadParam(inst, "p1");
  71. // ninst.Set("offset", (op.equals("-") ? "-" : "") + inst.Get("p2"))
  72. // .Set("rs", inst.Get("reg.p1"));
  73. offset = inst.Get("p2");
  74. rs = inst.Get("reg.p1");
  75. } else {
  76. offset = inst.Get("p1");
  77. rs = inst.Get("reg.p2");
  78. // LoadParam(inst, "p2");
  79. // ninst.Set("offset", inst.Get("p1"))
  80. // .Set("rs", inst.Get("reg.p2"));
  81. }
  82. ninst.Set("offset", (op.equals("-") ? "-" : "") + offset)
  83. .Set("rs", rs);
  84. break;
  85. // mult, divu, sgtu ,sltu
  86. // sra, srl, sll
  87. case "R":
  88. LoadParam(inst, "p1,p2", true);
  89. //
  90. if (ninst.in("inst", "sll,srl,sra".split(","))) {
  91. rd = inst.Get("reg.dst");
  92. ninst.Set("sa", inst.Get("p2"))
  93. .Set("rt", inst.Get("reg.p1"));
  94. } else {
  95. ninst.Set("rs", inst.Get("reg.p1"))
  96. .Set("rt", inst.Get("reg.p2"));
  97. }
  98. ninst.Set("rd", rd);
  99. // System.out.println("inst["+rd+"]" + inst + ":" + ninst);
  100. break;
  101. default:
  102. throw new Exception("Invalid instruction type");
  103. }
  104. Add(ninst).Set("comment", F(
  105. "%s = %s %s %s",
  106. dst,
  107. inst.Get("p1"),
  108. inst.Get("op"),
  109. inst.Get("p2")
  110. ));
  111. // Verifica se a expr possui overflow
  112. String overflow = Descriprion.Instruction(instruction).Get("overflow");
  113. if (!overflow.equals("")) {
  114. Add(new Instruction("R", overflow)
  115. .Set("rd", rd)
  116. );
  117. }
  118. // StoreResult(inst, rd, dst);
  119. }
  120. @Override
  121. public void TranslateJump(Instruction inst) throws Exception {
  122. Add(new Instruction("J", "j")
  123. .copy("label", inst)
  124. .Set("comment", F("jump to %s", inst.Get("label")))
  125. );
  126. Nop(false);
  127. }
  128. @Override
  129. public void TranslateCall(Instruction inst) throws Exception {
  130. // allocation.registers.ResetArgs();
  131. // Before load params
  132. // Copy(inst, returnRegisters.remove(2))
  133. // .Set("IR.position", inst.Get("block.position"))
  134. // .Set("comment", "push param");
  135. // System.out.println("Call" + inst);
  136. ResetReturnArgs();
  137. Instruction retur;
  138. LinkedList<Instruction> intructions = getIR().Block().Instructions();
  139. int base = intructions.indexOf(inst);
  140. for (int i = inst.GetInt("numParams"); i > 0; i--) {
  141. retur = intructions.get(base - i);
  142. Copy(retur, returnRegisters.remove(2))
  143. .Set("comment", "push param");
  144. }
  145. Add(new Instruction("J", "jal")
  146. .Set("label", inst.Get("funcname"))
  147. .Set("comment", F("jump to <%s>", inst.Get("funcname")))
  148. );
  149. // After store results
  150. // Restaura o array de registradores de retorno para fazer o pop dos returns
  151. ResetReturnArgs();
  152. Nop(false);
  153. }
  154. @Override
  155. public void TranslateReturn(Instruction inst) throws Exception {
  156. // Restaura o array de registradores de retorno
  157. ResetReturnArgs();
  158. Instruction retur;
  159. LinkedList<Instruction> intructions = getIR().Block().Instructions();
  160. int base = intructions.indexOf(inst);
  161. for (int i = inst.GetInt("p1"); i > 0; i--) {
  162. retur = intructions.get(base - i);
  163. // System.out.println("Return:" + retur);
  164. Copy(retur, returnRegisters.remove(0))
  165. .Set("comment", "push return ");
  166. }
  167. }
  168. @Override
  169. public void TranslatePopReturn(Instruction inst) throws Exception {
  170. String p1 = inst.Get("p1"), reg = returnRegisters.remove(0);
  171. // Se for uma variavel temporaria
  172. if (p1.contains("_T")) {
  173. CopyReg(reg, inst.Get("reg.p1"));
  174. } else {
  175. StoreWord(
  176. target.DEFAULT_WORD_TYPE,
  177. reg,
  178. FrameRegister(p1),
  179. Offset(p1)
  180. );
  181. }
  182. // System.out.println("Translate pop return" + inst);
  183. }
  184. @Override
  185. public void TranslatePopParam(Instruction inst) throws Exception {
  186. // todo - resetar args
  187. System.out.println("PopParam:" + inst);
  188. String dst = inst.Get("p1");
  189. // O indice é 2 por conta dos dois primeiros registradores {v0, v1}
  190. // System.out.println("PopParams:" + inst);
  191. StoreWord(
  192. target.DEFAULT_WORD_TYPE,
  193. returnRegisters.remove(2),
  194. FrameRegister(dst),
  195. Offset(dst)
  196. ).Set("comment", "pop param");
  197. // System.out.println("POPpARAM:" + inst);
  198. // LoadWord(inst.Get("reg.p1"), "fp", offset);
  199. }
  200. @Override
  201. public void TranslateBranch(Instruction inst) throws Exception {
  202. String instruction = Descriprion.InstructionByOperator(inst);
  203. LoadParam(inst, "p1,p2", true);
  204. String rs = inst.Get("reg.p1"),
  205. rt = inst.Get("reg.p2");
  206. Instruction branch = Descriprion.Instruction(instruction);
  207. switch (instruction) {
  208. case "beq": // == {[inst]}' ' {[rt]},{[rs]},{immediate}
  209. case "bne": // !=
  210. branch.Set("rs", rs).Set("rt", rt);
  211. break;
  212. case "blez": // <= 0{[inst]}' ' {[rs]},{immediate}
  213. case "bltz": // < 0
  214. case "bgez": // >= 0
  215. case "bgtz": // > 0
  216. Add(new Instruction("R", "subu")// Rd <-- [Rs] - [Rt];
  217. .Set("rs", rs)
  218. .Set("rt", rt)
  219. .Set("rd", "v0")
  220. .Set("comment", "")
  221. );
  222. branch.Set("rs", "v0");
  223. break;
  224. }
  225. Add(branch)
  226. .Set("label", inst.Get("label"))
  227. .Set("comment", comments.get(instruction));
  228. Nop(false);
  229. }
  230. protected void Nop(Boolean checkDependence) throws Exception {
  231. if (checkDependence) {
  232. Instruction n = Next();
  233. Integer dep = 0;
  234. // Se existe uma proxima intrucao
  235. if (n != null) {
  236. String dst = currentIrInstruction.Get(
  237. currentIrInstruction.Has("reg.dst")
  238. ? "reg.dst" : "reg.p1"
  239. );
  240. for (String reg : registersKeys) {
  241. if (n.eq(reg, dst)) {
  242. dep++;
  243. break;
  244. }
  245. }
  246. if (dep == 0) {
  247. return;
  248. }
  249. }
  250. }
  251. Add(Descriprion.Instruction("nop"));
  252. }
  253. @Override
  254. public void Prolog(String id) throws Exception {
  255. DataLayout data = Context();
  256. // Adiciona o label
  257. Add(new Instruction()
  258. .Set("type", "label")
  259. .Set("format", "label")
  260. .Set("label", id)
  261. );
  262. // Aloca o espaco da pilha
  263. Instruction alloc = Copy("sp", "sp", "-" + data.Size())
  264. .Set("comment", "prolog| push stack frame");
  265. if (!getTarget().Block().getName().equals("main")) {
  266. // Restaura o fp
  267. // Restaura o ra
  268. // boolean call = getIR().Block().HasCall();
  269. if (getIR().Block().HasCall()) {
  270. // int newvars = 0;
  271. for (String reg : new String[]{"fp", "ra"}) {
  272. data.Add(reg, "int32", 1);
  273. StoreWord(
  274. target.DEFAULT_WORD_TYPE,
  275. reg,
  276. "sp",
  277. data.Offset(reg)
  278. ).Set("comment", F("prolog| backup %s", reg));
  279. }
  280. alloc.Set("offset", (data.Size() - 0));
  281. }
  282. }
  283. if (alloc.getInt("offset", 0) != 0) {
  284. // Copia o sp para o fp
  285. CopyReg("sp", "fp").Prepend("comment", "prolog|");
  286. ResetReturnArgs();
  287. } else {
  288. getTarget().Block().Remove(alloc);
  289. }
  290. }
  291. /**
  292. * Encerra a chamada de uma funcao
  293. *
  294. * @param id
  295. * @throws Exception
  296. */
  297. @Override
  298. public void Epilog(String id) throws Exception {
  299. DataLayout data = Context();
  300. if (!getTarget().Block().getName().equals("main")) {
  301. // Restaura o fp
  302. // Restaura o ra
  303. boolean call = getIR().Block().HasCall();
  304. for (String reg : new String[]{"fp", "ra"}) {
  305. if (call) {
  306. LoadWord(
  307. target.DEFAULT_WORD_TYPE,
  308. reg,
  309. "sp",
  310. data.Offset(reg)
  311. ).Set("comment", F("epilog| restore ", reg));
  312. }
  313. }
  314. // Desaloca a pilha
  315. Copy("sp", "sp", Long.valueOf(data.Size()).toString())
  316. .Set("comment", "epilog| pop stack frame");
  317. CopyReg("sp", "fp")
  318. .Set("comment", "epilog| pop stack frame");
  319. Add(new Instruction("jr")
  320. .Set("rs", "ra")
  321. .Set("comment", "epilog| return"));
  322. } else {
  323. Add(Descriprion.Instruction("stop").copy());
  324. }
  325. }
  326. @Override
  327. public void TranslateIndexedAssignment(Instruction inst) throws Exception {
  328. // //Fase de leitura
  329. // IndexedRead(inst);
  330. // //Fase de atribuicao
  331. // IndexedDest(inst);
  332. }
  333. @Override
  334. public void TranslateUnary(Instruction inst) throws Exception {
  335. // Carrega o valor se nao esta em registrador
  336. // System.out.println("Translate Unary:" + inst);
  337. switch (inst.Get("op")) {
  338. case "-": // Retorna o valor negado 10 -> -10
  339. Add(new Instruction("subu")// Rd <-- [Rs] - [Rt];
  340. .Set("rd", inst.Get("reg.dst"))
  341. .Set("rs", "zero")
  342. .Set("rt", inst.Get("reg.p1"))
  343. .Set("comment", "negation arith")
  344. );
  345. break;
  346. case "!": // XOR ( 0 1 -> 1) XOR( 1 1 -> 0)
  347. Add(new Instruction("xori") // Rt <-- [Rs] AND (016 || [I15..0]); ;
  348. .Set("rt", inst.Get("reg.dst"))
  349. .Set("rs", inst.Get("reg.p1"))
  350. .Set("offset", "1")
  351. .Set("comment", "negation bool")
  352. );
  353. break;
  354. // case "*": // Copia do conteudo do ponteiro
  355. //
  356. // case "&": // Copia do endereco da variavel
  357. // break;// case "*": // Copia do conteudo do ponteiro
  358. //
  359. // case "&": // Copia do endereco da variavel
  360. // break;// case "*": // Copia do conteudo do ponteiro
  361. //
  362. // case "&": // Copia do endereco da variavel
  363. // break;// case "*": // Copia do conteudo do ponteiro
  364. //
  365. // case "&": // Copia do endereco da variavel
  366. // break;// case "*": // Copia do conteudo do ponteiro
  367. //
  368. // case "&": // Copia do endereco da variavel
  369. // break;// case "*": // Copia do conteudo do ponteiro
  370. //
  371. // case "&": // Copia do endereco da variavel
  372. // break;// case "*": // Copia do conteudo do ponteiro
  373. //
  374. // case "&": // Copia do endereco da variavel
  375. // break;// case "*": // Copia do conteudo do ponteiro
  376. //
  377. // case "&": // Copia do endereco da variavel
  378. // break;
  379. }
  380. }
  381. @Override
  382. public void TranslateLoad(Instruction inst) throws Exception {
  383. if (inst.eq("block.position", "12")) {
  384. System.out.println("Translate load:" + inst);
  385. }
  386. String addr = inst.Get("p1"),
  387. rd = inst.Get("reg.dst");
  388. String rs = inst.Has("reg.p1.indice")
  389. ? inst.Get("reg.p1.indice") : FrameRegister(addr);
  390. Instruction lw = LoadWord(
  391. target.DEFAULT_WORD_TYPE,
  392. rd,
  393. rs,
  394. Offset(addr)
  395. ).Set("comment", F("load content from %s in %s", addr, rd));
  396. if (inst.eq("block.position", "12")) {
  397. System.out.println("Translate load >> :" + lw);
  398. }
  399. }
  400. @Override
  401. public void TranslateStore(Instruction inst) throws Exception {
  402. // System.out.println("Translate store>> :" + inst);
  403. // // Carrega o parametro p1 se constante
  404. // // Caso a constante seja 0 a instrução não carrega o valor e atualiza o registrador fonte para zero
  405. // LoadParam(inst, "p1", true);
  406. //
  407. // String addr = inst.Get("dst"),
  408. // rt = inst.Get("reg.dst");
  409. //
  410. // String rs = inst.Has("reg.dst.indice")
  411. // ? inst.Get("reg.dst.indice") : FrameRegister(addr);
  412. //
  413. // StoreWord(
  414. // target.DEFAULT_WORD_TYPE,
  415. // rt,
  416. // rs,
  417. // Offset(addr)
  418. // ).Set("comment", F("store content of %s in %s", rt, addr));
  419. // Carrega o parametro p1 se constante
  420. // Caso a constante seja 0 a instrução não carrega o valor e atualiza o registrador fonte para zero
  421. LoadParam(inst, "p1", true);
  422. String addr = inst.Get("dst"),
  423. rt = inst.Get("reg.p1");
  424. String rs = inst.Has("reg.dst.indice")
  425. ? inst.Get("reg.dst.indice") : FrameRegister(addr);
  426. StoreWord(
  427. target.DEFAULT_WORD_TYPE,
  428. rt,
  429. rs,
  430. Offset(addr)
  431. ).Set("comment", F("store content of %s in %s", rt, addr));
  432. }
  433. /**
  434. * Traducao de intrucoeS do tipo
  435. *
  436. * - x = &a - copia do endereco de uma varaivel <br>
  437. * - x = *b - x recebe o conteudo da variavel referenciada por b<br>
  438. * - *x = y - conpia o conteudo de y para o endereco armazenado em x
  439. *
  440. * @param inst
  441. * @throws Exception
  442. */
  443. @Override
  444. public void TranslatePointerAssignment(Instruction inst) throws Exception {
  445. String p1 = inst.Get("p1"),
  446. dst = inst.Get("dst"),
  447. regdst = inst.Get("reg.dst"),
  448. regp1 = inst.Get("reg.p1");
  449. switch (inst.Get("op")) {
  450. case "&": // Lendo o endereco de um ponteiro
  451. Copy(regp1,
  452. FrameRegister(p1),
  453. Offset(p1)
  454. ).Set("comment", F("copy address of ", p1));
  455. System.out.println("PointerAssi&:" + inst);
  456. // Se nao fez o store
  457. // if (StoreResult(inst, regp1, dst) == null) {
  458. // CopyReg(regp1, regdst);
  459. // .Set("comment", "store content of " + regdst + " in " + dst);
  460. // }
  461. break;
  462. case "*": // Lendo o conteudo de um ponteiro
  463. /**
  464. * Carrega o valor contido no ponteiro<br>
  465. * Utiliza o valor como endereço em um segundo load que carrega
  466. * o dado<br>
  467. * lw ${p1},12($fp)<br>
  468. * lw ${dst},0(${p1}) $s<br>
  469. */
  470. LoadWord(
  471. target.DEFAULT_WORD_TYPE,
  472. regp1,
  473. FrameRegister(p1),
  474. Offset(p1)
  475. ).Set("comment", F("load address stored in %s", p1));
  476. LoadWord(
  477. target.DEFAULT_WORD_TYPE,
  478. regdst,
  479. regp1,
  480. "0"
  481. ).Set("comment", F("load content of address stored in %s", regp1));
  482. /*Se for a ultima operacao de escrita nessa variavel salva em memoria*/
  483. // Instruction store = StoreResult(inst, regdst, dst);
  484. // if (store != null) {
  485. // store.Set("comment", "store content of " + regdst + " in " + dst);
  486. // }
  487. break;
  488. default: // Atribuicao a um ponteiro
  489. LoadParam(inst, "p1,p2", true);
  490. /**
  491. * Carrega o valor dentro do endereco do ponteiro <br>
  492. * lw ${p1},12(${fp|gp})<br>
  493. * lw ${dst},0(${p1}) $s<br>
  494. * conteudo da variavel referenciada
  495. */
  496. LoadWord(
  497. target.DEFAULT_WORD_TYPE,
  498. regdst,
  499. FrameRegister(dst),
  500. Offset(dst)
  501. ).Set("comment", F("load address stored in %s", dst));
  502. // Grava o valor do registrador na memoria
  503. StoreWord(
  504. target.DEFAULT_WORD_TYPE,
  505. regp1,
  506. regdst,
  507. "0"
  508. ).Set("comment", F("store content of %s in *%s", regp1, dst));
  509. }
  510. }
  511. @Override
  512. public void TranslatePushReturn(Instruction inst) {
  513. // Tratado no metodo 'TranslateReturn'
  514. }
  515. @Override
  516. public void TranslatePushParam(Instruction inst) {
  517. // Tratado no metodo 'TranslateCall'
  518. }
  519. @Override
  520. public IvannosysTargetArch Init(Code tac) throws Exception {
  521. this.IR = tac;
  522. getTarget()
  523. .setAddressIncrement(4)
  524. .Template(new MipsTemplateDescription());
  525. return this;
  526. }
  527. /**
  528. * Criar uma inStrucao que copia o valor ou conteudo do regiStrador para o
  529. * regiStrador 'r'
  530. *
  531. * @param inst
  532. * @param rt
  533. * @return
  534. */
  535. protected Instruction Copy(Instruction inst, String rt) throws Exception {
  536. Instruction c = null;
  537. LoadParam(inst, "p1", false);
  538. if (inst.eq("load.large.constante", "true")) {
  539. System.out.println("COPY LARGE:" + currentTargetInstruction);
  540. } else {
  541. if (inst.IsValue("p1")) {
  542. // andi Rt,Rs,immediate | Rt <-- [Rs] + ([I15]16 || [I15..0]);
  543. c = Copy(rt, "zero", inst.Get("p1"));
  544. } else {
  545. // addu Rd,Rs,Rt | Rd <-- [Rs] + [Rt];
  546. c = CopyReg(inst.Get("reg.p1"), rt);
  547. }
  548. }
  549. return c;
  550. }
  551. /**
  552. * @param inst
  553. * @return
  554. */
  555. protected Instruction LoadParam(Instruction inst, String params, boolean copy) throws Exception {
  556. return LoadParam(inst, params.split(","), copy);
  557. }
  558. protected Instruction LoadParam(Instruction inst, String[] params, boolean copy) throws Exception {
  559. String offset, bin, reg, r;
  560. // boolean loaded = false;
  561. Long value;
  562. Integer lower, upper;
  563. Instruction loaded = null;
  564. for (String param : params) {
  565. if (inst.IsValue(param) && inst.Has("reg." + param)) {
  566. // loaded = true;
  567. offset = inst.Get(param);
  568. value = Long.parseLong(offset);
  569. bin = Utils.Pad(32, Long.toBinaryString(value));
  570. // System.out.println("bin:"
  571. // + "\n" + bin
  572. // + "\n" + offset
  573. // + "\n" + Long.toBinaryString(Integer.parseInt(bin.substring(0, 16), 2))
  574. // + "\n" + Long.toBinaryString(Integer.parseInt(bin.substring(16), 2)));
  575. if (bin.substring(0, 16).contains("1")) {
  576. upper = Integer.parseInt(bin.substring(0, 16), 2);
  577. lower = Integer.parseInt(bin.substring(16), 2);
  578. inst.Set("load.large.constante", "true");
  579. // System.out.println("Load param:" + inst);
  580. // r = inst.Get("reg.dst");
  581. r = inst.Get("reg." + param);
  582. // System.out.println("upper:" + upper);
  583. //clui $s0, upper(big)
  584. Add(Descriprion.Instruction("lui"))
  585. .Set("rt", r)
  586. .Set("offset", upper)
  587. .Set("comment", "load param upper(" + param + ")");
  588. //ori $s0, $s0, lower(big)
  589. loaded = Add(Descriprion.Instruction("ori"))
  590. .Set("rs", r)
  591. .Set("rt", r)
  592. .Set("offset", lower)
  593. .Set("comment", "load param lower(" + param + ")");
  594. } else if (copy) {
  595. reg = "reg." + param;
  596. r = inst.Get(reg);
  597. if (offset.equals("0")) {
  598. inst.Set(reg, "zero");
  599. continue;
  600. }
  601. loaded = Copy(r, "zero", offset).Set("comment", "load param (" + param + ")");
  602. }
  603. }
  604. }
  605. // for (String param : params) {
  606. // if (inst.IsValue(param) && inst.Has("reg." + param)) {
  607. //
  608. // offset = inst.Get(param);
  609. //
  610. // if (offset.equals("0")) {
  611. // inst.Set("reg." + param, "zero");
  612. // continue;
  613. // }
  614. //
  615. // Copy(inst.Get("reg." + param), "zero", offset);
  616. // }
  617. // }
  618. // return loaded;
  619. return loaded;
  620. }
  621. /**
  622. * Copia o valor do regiStrador Src para o dSt
  623. *
  624. * @param src
  625. *
  626. * @param dst
  627. * @return
  628. */
  629. protected Instruction CopyReg(String src, String dst) throws Exception {
  630. return Add(new Instruction("addu")
  631. .Set("rs", "zero")
  632. .Set("rt", src)
  633. .Set("rd", dst)
  634. .Set("comment", F("copy %s ← %s", dst, src)));
  635. }
  636. protected Instruction Copy(String rt, String rs, Offset offset) throws Exception {
  637. return Copy(rt, rs, "" + offset);
  638. }
  639. protected Instruction Copy(String rt, String rs, String offset) throws Exception {
  640. return Add(new Instruction("addiu") // lw $rt, imm($rs)
  641. .Set("rt", rt)
  642. .Set("rs", rs)
  643. .Set("offset", offset)
  644. .Set("comment", F("copy %s ← %s", rs, rt))
  645. );
  646. }
  647. protected Instruction StoreWord(String type, String rt, String rs, Offset offset) throws Exception {
  648. Instruction n = Next();
  649. String inst;
  650. switch (type) {
  651. case "byte":
  652. case "int8":
  653. case "uint8":
  654. case "bool":
  655. inst = "sb"; // Load byte
  656. break;
  657. case "int16":
  658. case "uint16":
  659. inst = "sh"; //Load half
  660. break;
  661. default:
  662. inst = "sw"; // Load word
  663. }
  664. Instruction sw = Add(new Instruction(inst)
  665. .Set("rt", rt)
  666. .Set("rs", rs)
  667. .Set("offset", offset.getAddress() + offset.getShift()));
  668. return sw;
  669. }
  670. protected Instruction StoreWord(String type, String rt, String rs, String offset) throws Exception {
  671. return StoreWord(type, rt, rs, new Offset(Long.parseLong(offset), 0L));
  672. }
  673. protected Instruction LoadWord(String type, String rt, String rs, Offset offset) throws Exception {
  674. Instruction n = Next();
  675. String inst;
  676. switch (type) {
  677. case "byte":
  678. case "int8":
  679. case "uint8":
  680. case "bool":
  681. // LB -- Load byte 8 bits
  682. // Operation:$t = MEM[$s + offset]; advance_pc (4);
  683. // Syntax: lb $t, offset($s)
  684. // Offset é o endereço base da variavel
  685. // Shift é o byte a ser lido
  686. inst = "lb";
  687. break;
  688. case "int16":
  689. case "uint16":
  690. // LW -- Load half 16 bits
  691. // Operation:$t = MEM[$s + offset]; advance_pc (4);
  692. // Syntax: lw $t, offset($s)
  693. inst = "lh";
  694. break;
  695. default:
  696. // LW -- Load word 32 bits
  697. // Operation:$t = MEM[$s + offset]; advance_pc (4);
  698. // Syntax: lw $t, offset($s)
  699. inst = "lw"; // Load word
  700. }
  701. Instruction lw = Add(new Instruction(inst) // lw $rt, imm($rs)
  702. .Set("rt", rt)
  703. .Set("rs", rs)
  704. .Set("offset", offset.getAddress() + offset.getShift())
  705. );
  706. Nop(true);
  707. return lw;
  708. }
  709. protected Instruction LoadWord(String type, String rt, String rs, String offset) throws Exception {
  710. return LoadWord(type, rt, rs, new Offset(Long.parseLong(offset), 0L));
  711. }
  712. @Override
  713. protected Instruction Add(Instruction inst) throws Exception {
  714. if (!inst.eq("type", "label")) {
  715. getTarget().PositionInc();
  716. Instruction definiction = Descriprion.Instruction(inst.Get("inst"));
  717. inst.Merge("sa,type,inst,codop,func,format", definiction);
  718. }
  719. if (currentIrInstruction != null) {
  720. inst.Set("inloop", currentIrInstruction.Get("inloop"));
  721. }
  722. // System.out.println("Add:" + inst);
  723. return super.Add(inst); //To change body of generated methods, choose Tools | Templates.
  724. }
  725. protected String FrameRegister(String var) {
  726. return var.contains("_G") ? "gp" : "fp";
  727. }
  728. private void ResetReturnArgs() {
  729. returnRegisters = new ArrayList<String>() {
  730. {
  731. add("v0");
  732. add("v1");
  733. add("a0");
  734. add("a1");
  735. add("a2");
  736. add("a3");
  737. }
  738. };
  739. }
  740. }
  741. // protected void IndexedRead(Instruction inst) throws Exception {
  742. // // Se a fonte é indexada
  743. // if (inst.eq("src_indexed", "true")) {
  744. // try {
  745. // String p1 = inst.Get("p1"),
  746. // rt = inst.Get("reg.p1"),
  747. // rs = FrameRegister(p1);
  748. //
  749. //// System.out.println("Indexed read:" + inst);
  750. // if (!inst.isNumber("p1.indice")) {
  751. //
  752. // String rd = inst.Get("reg.p1.indice");
  753. // if (!AddressCalculated.containsKey(p1)) {
  754. // Add(new Instruction("addu")
  755. // .Set("rd", rd)
  756. // .Set("rs", rs)
  757. // .Set("rt", rd));
  758. // AddressCalculated.put(p1, rs);
  759. // }
  760. // rs = rd;
  761. // }
  762. // // Carrega o conteudo enderecado em rt para rt
  763. // LoadWord(
  764. // target.DEFAULT_WORD_TYPE,
  765. // rt,
  766. // rs,
  767. // Offset(p1)
  768. // );
  769. //
  770. // } catch (Exception ex) {
  771. // Logger.getLogger(Translate.class.getName()).log(Level.SEVERE, null, ex);
  772. // }
  773. //
  774. // } else {
  775. // // Se não é indexada carrega o parametro normalmente
  776. // LoadParam(inst);
  777. // }
  778. // }
  779. //
  780. // /**
  781. // * FaSe de atribuicao
  782. // *
  783. // * @param inst
  784. // */
  785. // protected void IndexedDest(Instruction inst) throws Exception {
  786. //// System.out.println("Indexeds:" + inst);
  787. //
  788. // String regp1 = inst.Get("reg.p1"),
  789. // regdst = inst.Get("reg.dst");
  790. //
  791. // // Valor atribuido é indexado
  792. // // 1 - Verificar se deve ser armazenado ou copiado
  793. //// boolean dstIndexed = inst.eq("dst.indexed", "true");
  794. // if (inst.eq("dst.indexed", "true")) {
  795. //// if (dstIndexed || inst.eq("reg.dst.store", "true")) {
  796. // // deve ser armazenado
  797. // String dst = inst.Get("dst"),
  798. // rs = FrameRegister(dst);
  799. //// if (dstIndexed) {
  800. // if (!inst.isNumber("dst.indice")) {
  801. // // Offset agora deve ser 0 pois o registrador conterá o endereco completo
  802. //// offset = 0;
  803. // String rd = inst.Get("reg.dst.indice");
  804. // if (!AddressCalculated.containsKey(dst)) {
  805. // Add(new Instruction("addu")
  806. // .Set("rd", rd)
  807. // .Set("rs", rs)
  808. // .Set("rt", rd)
  809. // );
  810. // AddressCalculated.put(dst, rs);
  811. // }
  812. // rs = rd;
  813. // }
  814. //// comment = "store in loaded address";
  815. //// } else {
  816. //// comment = "store in " + dst;
  817. //// }// System.out.println("Inst:" + inst);
  818. // StoreWord(
  819. // target.DEFAULT_WORD_TYPE,
  820. // regp1,
  821. // rs,
  822. // Offset(dst)
  823. // ).Set("comment", F("store content of %s in %s", rs, dst));
  824. //
  825. // } else { // deve ser copiado
  826. // CopyReg(regp1, regdst);
  827. // }
  828. // }
  829. // public void CopyData(LinkedHashMap<String, Node> dst, LinkedHashMap<String, Node> src) throws Exception {
  830. // public void CopyData(DataLayout dst, DataLayout src) throws Exception {
  831. // Node value;
  832. // LinkedHashMap<String, Node> svalues = src.values(),
  833. // dvalues = dst.values();
  834. //
  835. // for (Map.Entry<String, Node> x : svalues.entrySet()) {
  836. // value = x.getValue().copy();
  837. // value.S("size", value.GetInt("size") * WORD_INC);
  838. //// System.out.println("Copy:[" + x.getKey() + "][" + value.Get("id") + "]" + value.Get("size") + "\n" + value);
  839. //// dvalues.put(x.getKey(), value);
  840. //
  841. // dst.Set(x.getKey(), value);
  842. // }
  843. // }