Merge pull request #750 from pcercuei/lightrec-update-20230826
[pcsx_rearmed.git] / deps / lightrec / optimizer.c
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  * Copyright (C) 2014-2021 Paul Cercueil <paul@crapouillou.net>
4  */
5
6 #include "constprop.h"
7 #include "lightrec-config.h"
8 #include "disassembler.h"
9 #include "lightrec.h"
10 #include "memmanager.h"
11 #include "optimizer.h"
12 #include "regcache.h"
13
14 #include <errno.h>
15 #include <stdbool.h>
16 #include <stdlib.h>
17 #include <string.h>
18
19 #define IF_OPT(opt, ptr) ((opt) ? (ptr) : NULL)
20
21 struct optimizer_list {
22         void (**optimizers)(struct opcode *);
23         unsigned int nb_optimizers;
24 };
25
26 static bool is_nop(union code op);
27
28 bool is_unconditional_jump(union code c)
29 {
30         switch (c.i.op) {
31         case OP_SPECIAL:
32                 return c.r.op == OP_SPECIAL_JR || c.r.op == OP_SPECIAL_JALR;
33         case OP_J:
34         case OP_JAL:
35                 return true;
36         case OP_BEQ:
37         case OP_BLEZ:
38                 return c.i.rs == c.i.rt;
39         case OP_REGIMM:
40                 return (c.r.rt == OP_REGIMM_BGEZ ||
41                         c.r.rt == OP_REGIMM_BGEZAL) && c.i.rs == 0;
42         default:
43                 return false;
44         }
45 }
46
47 bool is_syscall(union code c)
48 {
49         return (c.i.op == OP_SPECIAL && c.r.op == OP_SPECIAL_SYSCALL) ||
50                 (c.i.op == OP_CP0 && (c.r.rs == OP_CP0_MTC0 ||
51                                         c.r.rs == OP_CP0_CTC0) &&
52                  (c.r.rd == 12 || c.r.rd == 13));
53 }
54
55 static u64 opcode_read_mask(union code op)
56 {
57         switch (op.i.op) {
58         case OP_SPECIAL:
59                 switch (op.r.op) {
60                 case OP_SPECIAL_SYSCALL:
61                 case OP_SPECIAL_BREAK:
62                         return 0;
63                 case OP_SPECIAL_JR:
64                 case OP_SPECIAL_JALR:
65                 case OP_SPECIAL_MTHI:
66                 case OP_SPECIAL_MTLO:
67                         return BIT(op.r.rs);
68                 case OP_SPECIAL_MFHI:
69                         return BIT(REG_HI);
70                 case OP_SPECIAL_MFLO:
71                         return BIT(REG_LO);
72                 case OP_SPECIAL_SLL:
73                         if (!op.r.imm)
74                                 return 0;
75                         fallthrough;
76                 case OP_SPECIAL_SRL:
77                 case OP_SPECIAL_SRA:
78                         return BIT(op.r.rt);
79                 default:
80                         return BIT(op.r.rs) | BIT(op.r.rt);
81                 }
82         case OP_CP0:
83                 switch (op.r.rs) {
84                 case OP_CP0_MTC0:
85                 case OP_CP0_CTC0:
86                         return BIT(op.r.rt);
87                 default:
88                         return 0;
89                 }
90         case OP_CP2:
91                 if (op.r.op == OP_CP2_BASIC) {
92                         switch (op.r.rs) {
93                         case OP_CP2_BASIC_MTC2:
94                         case OP_CP2_BASIC_CTC2:
95                                 return BIT(op.r.rt);
96                         default:
97                                 break;
98                         }
99                 }
100                 return 0;
101         case OP_J:
102         case OP_JAL:
103         case OP_LUI:
104                 return 0;
105         case OP_BEQ:
106                 if (op.i.rs == op.i.rt)
107                         return 0;
108                 fallthrough;
109         case OP_BNE:
110         case OP_LWL:
111         case OP_LWR:
112         case OP_SB:
113         case OP_SH:
114         case OP_SWL:
115         case OP_SW:
116         case OP_SWR:
117                 return BIT(op.i.rs) | BIT(op.i.rt);
118         case OP_META:
119                 return BIT(op.m.rs);
120         default:
121                 return BIT(op.i.rs);
122         }
123 }
124
125 static u64 mult_div_write_mask(union code op)
126 {
127         u64 flags;
128
129         if (!OPT_FLAG_MULT_DIV)
130                 return BIT(REG_LO) | BIT(REG_HI);
131
132         if (op.r.rd)
133                 flags = BIT(op.r.rd);
134         else
135                 flags = BIT(REG_LO);
136         if (op.r.imm)
137                 flags |= BIT(op.r.imm);
138         else
139                 flags |= BIT(REG_HI);
140
141         return flags;
142 }
143
144 u64 opcode_write_mask(union code op)
145 {
146         switch (op.i.op) {
147         case OP_META_MULT2:
148         case OP_META_MULTU2:
149                 return mult_div_write_mask(op);
150         case OP_META:
151                 return BIT(op.m.rd);
152         case OP_SPECIAL:
153                 switch (op.r.op) {
154                 case OP_SPECIAL_JR:
155                 case OP_SPECIAL_SYSCALL:
156                 case OP_SPECIAL_BREAK:
157                         return 0;
158                 case OP_SPECIAL_MULT:
159                 case OP_SPECIAL_MULTU:
160                 case OP_SPECIAL_DIV:
161                 case OP_SPECIAL_DIVU:
162                         return mult_div_write_mask(op);
163                 case OP_SPECIAL_MTHI:
164                         return BIT(REG_HI);
165                 case OP_SPECIAL_MTLO:
166                         return BIT(REG_LO);
167                 case OP_SPECIAL_SLL:
168                         if (!op.r.imm)
169                                 return 0;
170                         fallthrough;
171                 default:
172                         return BIT(op.r.rd);
173                 }
174         case OP_ADDI:
175         case OP_ADDIU:
176         case OP_SLTI:
177         case OP_SLTIU:
178         case OP_ANDI:
179         case OP_ORI:
180         case OP_XORI:
181         case OP_LUI:
182         case OP_LB:
183         case OP_LH:
184         case OP_LWL:
185         case OP_LW:
186         case OP_LBU:
187         case OP_LHU:
188         case OP_LWR:
189                 return BIT(op.i.rt);
190         case OP_JAL:
191                 return BIT(31);
192         case OP_CP0:
193                 switch (op.r.rs) {
194                 case OP_CP0_MFC0:
195                 case OP_CP0_CFC0:
196                         return BIT(op.i.rt);
197                 default:
198                         return 0;
199                 }
200         case OP_CP2:
201                 if (op.r.op == OP_CP2_BASIC) {
202                         switch (op.r.rs) {
203                         case OP_CP2_BASIC_MFC2:
204                         case OP_CP2_BASIC_CFC2:
205                                 return BIT(op.i.rt);
206                         default:
207                                 break;
208                         }
209                 }
210                 return 0;
211         case OP_REGIMM:
212                 switch (op.r.rt) {
213                 case OP_REGIMM_BLTZAL:
214                 case OP_REGIMM_BGEZAL:
215                         return BIT(31);
216                 default:
217                         return 0;
218                 }
219         default:
220                 return 0;
221         }
222 }
223
224 bool opcode_reads_register(union code op, u8 reg)
225 {
226         return opcode_read_mask(op) & BIT(reg);
227 }
228
229 bool opcode_writes_register(union code op, u8 reg)
230 {
231         return opcode_write_mask(op) & BIT(reg);
232 }
233
234 static int find_prev_writer(const struct opcode *list, unsigned int offset, u8 reg)
235 {
236         union code c;
237         unsigned int i;
238
239         if (op_flag_sync(list[offset].flags))
240                 return -1;
241
242         for (i = offset; i > 0; i--) {
243                 c = list[i - 1].c;
244
245                 if (opcode_writes_register(c, reg)) {
246                         if (i > 1 && has_delay_slot(list[i - 2].c))
247                                 break;
248
249                         return i - 1;
250                 }
251
252                 if (op_flag_sync(list[i - 1].flags) ||
253                     has_delay_slot(c) ||
254                     opcode_reads_register(c, reg))
255                         break;
256         }
257
258         return -1;
259 }
260
261 static int find_next_reader(const struct opcode *list, unsigned int offset, u8 reg)
262 {
263         unsigned int i;
264         union code c;
265
266         if (op_flag_sync(list[offset].flags))
267                 return -1;
268
269         for (i = offset; ; i++) {
270                 c = list[i].c;
271
272                 if (opcode_reads_register(c, reg))
273                         return i;
274
275                 if (op_flag_sync(list[i].flags)
276                     || (op_flag_no_ds(list[i].flags) && has_delay_slot(c))
277                     || is_delay_slot(list, i)
278                     || opcode_writes_register(c, reg))
279                         break;
280         }
281
282         return -1;
283 }
284
285 static bool reg_is_dead(const struct opcode *list, unsigned int offset, u8 reg)
286 {
287         unsigned int i;
288
289         if (op_flag_sync(list[offset].flags) || is_delay_slot(list, offset))
290                 return false;
291
292         for (i = offset + 1; ; i++) {
293                 if (opcode_reads_register(list[i].c, reg))
294                         return false;
295
296                 if (opcode_writes_register(list[i].c, reg))
297                         return true;
298
299                 if (has_delay_slot(list[i].c)) {
300                         if (op_flag_no_ds(list[i].flags) ||
301                             opcode_reads_register(list[i + 1].c, reg))
302                                 return false;
303
304                         return opcode_writes_register(list[i + 1].c, reg);
305                 }
306         }
307 }
308
309 static bool reg_is_read(const struct opcode *list,
310                         unsigned int a, unsigned int b, u8 reg)
311 {
312         /* Return true if reg is read in one of the opcodes of the interval
313          * [a, b[ */
314         for (; a < b; a++) {
315                 if (!is_nop(list[a].c) && opcode_reads_register(list[a].c, reg))
316                         return true;
317         }
318
319         return false;
320 }
321
322 static bool reg_is_written(const struct opcode *list,
323                            unsigned int a, unsigned int b, u8 reg)
324 {
325         /* Return true if reg is written in one of the opcodes of the interval
326          * [a, b[ */
327
328         for (; a < b; a++) {
329                 if (!is_nop(list[a].c) && opcode_writes_register(list[a].c, reg))
330                         return true;
331         }
332
333         return false;
334 }
335
336 static bool reg_is_read_or_written(const struct opcode *list,
337                                    unsigned int a, unsigned int b, u8 reg)
338 {
339         return reg_is_read(list, a, b, reg) || reg_is_written(list, a, b, reg);
340 }
341
342 bool opcode_is_mfc(union code op)
343 {
344         switch (op.i.op) {
345         case OP_CP0:
346                 switch (op.r.rs) {
347                 case OP_CP0_MFC0:
348                 case OP_CP0_CFC0:
349                         return true;
350                 default:
351                         break;
352                 }
353
354                 break;
355         case OP_CP2:
356                 if (op.r.op == OP_CP2_BASIC) {
357                         switch (op.r.rs) {
358                         case OP_CP2_BASIC_MFC2:
359                         case OP_CP2_BASIC_CFC2:
360                                 return true;
361                         default:
362                                 break;
363                         }
364                 }
365
366                 break;
367         default:
368                 break;
369         }
370
371         return false;
372 }
373
374 bool opcode_is_load(union code op)
375 {
376         switch (op.i.op) {
377         case OP_LB:
378         case OP_LH:
379         case OP_LWL:
380         case OP_LW:
381         case OP_LBU:
382         case OP_LHU:
383         case OP_LWR:
384         case OP_LWC2:
385                 return true;
386         default:
387                 return false;
388         }
389 }
390
391 static bool opcode_is_store(union code op)
392 {
393         switch (op.i.op) {
394         case OP_SB:
395         case OP_SH:
396         case OP_SW:
397         case OP_SWL:
398         case OP_SWR:
399         case OP_SWC2:
400                 return true;
401         default:
402                 return false;
403         }
404 }
405
406 static u8 opcode_get_io_size(union code op)
407 {
408         switch (op.i.op) {
409         case OP_LB:
410         case OP_LBU:
411         case OP_SB:
412                 return 8;
413         case OP_LH:
414         case OP_LHU:
415         case OP_SH:
416                 return 16;
417         default:
418                 return 32;
419         }
420 }
421
422 bool opcode_is_io(union code op)
423 {
424         return opcode_is_load(op) || opcode_is_store(op);
425 }
426
427 /* TODO: Complete */
428 static bool is_nop(union code op)
429 {
430         if (opcode_writes_register(op, 0)) {
431                 switch (op.i.op) {
432                 case OP_CP0:
433                         return op.r.rs != OP_CP0_MFC0;
434                 case OP_LB:
435                 case OP_LH:
436                 case OP_LWL:
437                 case OP_LW:
438                 case OP_LBU:
439                 case OP_LHU:
440                 case OP_LWR:
441                         return false;
442                 default:
443                         return true;
444                 }
445         }
446
447         switch (op.i.op) {
448         case OP_SPECIAL:
449                 switch (op.r.op) {
450                 case OP_SPECIAL_AND:
451                         return op.r.rd == op.r.rt && op.r.rd == op.r.rs;
452                 case OP_SPECIAL_ADD:
453                 case OP_SPECIAL_ADDU:
454                         return (op.r.rd == op.r.rt && op.r.rs == 0) ||
455                                 (op.r.rd == op.r.rs && op.r.rt == 0);
456                 case OP_SPECIAL_SUB:
457                 case OP_SPECIAL_SUBU:
458                         return op.r.rd == op.r.rs && op.r.rt == 0;
459                 case OP_SPECIAL_OR:
460                         if (op.r.rd == op.r.rt)
461                                 return op.r.rd == op.r.rs || op.r.rs == 0;
462                         else
463                                 return (op.r.rd == op.r.rs) && op.r.rt == 0;
464                 case OP_SPECIAL_SLL:
465                 case OP_SPECIAL_SRA:
466                 case OP_SPECIAL_SRL:
467                         return op.r.rd == op.r.rt && op.r.imm == 0;
468                 case OP_SPECIAL_MFHI:
469                 case OP_SPECIAL_MFLO:
470                         return op.r.rd == 0;
471                 default:
472                         return false;
473                 }
474         case OP_ORI:
475         case OP_ADDI:
476         case OP_ADDIU:
477                 return op.i.rt == op.i.rs && op.i.imm == 0;
478         case OP_BGTZ:
479                 return (op.i.rs == 0 || op.i.imm == 1);
480         case OP_REGIMM:
481                 return (op.i.op == OP_REGIMM_BLTZ ||
482                                 op.i.op == OP_REGIMM_BLTZAL) &&
483                         (op.i.rs == 0 || op.i.imm == 1);
484         case OP_BNE:
485                 return (op.i.rs == op.i.rt || op.i.imm == 1);
486         default:
487                 return false;
488         }
489 }
490
491 static void lightrec_optimize_sll_sra(struct opcode *list, unsigned int offset,
492                                       struct constprop_data *v)
493 {
494         struct opcode *ldop = NULL, *curr = &list[offset], *next;
495         struct opcode *to_change, *to_nop;
496         int idx, idx2;
497
498         if (curr->r.imm != 24 && curr->r.imm != 16)
499                 return;
500
501         if (is_delay_slot(list, offset))
502                 return;
503
504         idx = find_next_reader(list, offset + 1, curr->r.rd);
505         if (idx < 0)
506                 return;
507
508         next = &list[idx];
509
510         if (next->i.op != OP_SPECIAL || next->r.op != OP_SPECIAL_SRA ||
511             next->r.imm != curr->r.imm || next->r.rt != curr->r.rd)
512                 return;
513
514         if (curr->r.rd != curr->r.rt && next->r.rd != next->r.rt) {
515                 /* sll rY, rX, 16
516                  * ...
517                  * sra rZ, rY, 16 */
518
519                 if (!reg_is_dead(list, idx, curr->r.rd) ||
520                     reg_is_read_or_written(list, offset, idx, next->r.rd))
521                         return;
522
523                 /* If rY is dead after the SRL, and rZ is not used after the SLL,
524                  * we can change rY to rZ */
525
526                 pr_debug("Detected SLL/SRA with middle temp register\n");
527                 curr->r.rd = next->r.rd;
528                 next->r.rt = curr->r.rd;
529         }
530
531         /* We got a SLL/SRA combo. If imm #16, that's a cast to s16.
532          * If imm #24 that's a cast to s8.
533          *
534          * First of all, make sure that the target register of the SLL is not
535          * read after the SRA. */
536
537         if (curr->r.rd == curr->r.rt) {
538                 /* sll rX, rX, 16
539                  * ...
540                  * sra rY, rX, 16 */
541                 to_change = next;
542                 to_nop = curr;
543
544                 /* rX is used after the SRA - we cannot convert it. */
545                 if (curr->r.rd != next->r.rd && !reg_is_dead(list, idx, curr->r.rd))
546                         return;
547         } else {
548                 /* sll rY, rX, 16
549                  * ...
550                  * sra rY, rY, 16 */
551                 to_change = curr;
552                 to_nop = next;
553         }
554
555         idx2 = find_prev_writer(list, offset, curr->r.rt);
556         if (idx2 >= 0) {
557                 /* Note that PSX games sometimes do casts after
558                  * a LHU or LBU; in this case we can change the
559                  * load opcode to a LH or LB, and the cast can
560                  * be changed to a MOV or a simple NOP. */
561
562                 ldop = &list[idx2];
563
564                 if (next->r.rd != ldop->i.rt &&
565                     !reg_is_dead(list, idx, ldop->i.rt))
566                         ldop = NULL;
567                 else if (curr->r.imm == 16 && ldop->i.op == OP_LHU)
568                         ldop->i.op = OP_LH;
569                 else if (curr->r.imm == 24 && ldop->i.op == OP_LBU)
570                         ldop->i.op = OP_LB;
571                 else
572                         ldop = NULL;
573
574                 if (ldop) {
575                         if (next->r.rd == ldop->i.rt) {
576                                 to_change->opcode = 0;
577                         } else if (reg_is_dead(list, idx, ldop->i.rt) &&
578                                    !reg_is_read_or_written(list, idx2 + 1, idx, next->r.rd)) {
579                                 /* The target register of the SRA is dead after the
580                                  * LBU/LHU; we can change the target register of the
581                                  * LBU/LHU to the one of the SRA. */
582                                 v[ldop->i.rt].known = 0;
583                                 v[ldop->i.rt].sign = 0;
584                                 ldop->i.rt = next->r.rd;
585                                 to_change->opcode = 0;
586                         } else {
587                                 to_change->i.op = OP_META;
588                                 to_change->m.op = OP_META_MOV;
589                                 to_change->m.rd = next->r.rd;
590                                 to_change->m.rs = ldop->i.rt;
591                         }
592
593                         if (to_nop->r.imm == 24)
594                                 pr_debug("Convert LBU+SLL+SRA to LB\n");
595                         else
596                                 pr_debug("Convert LHU+SLL+SRA to LH\n");
597
598                         v[ldop->i.rt].known = 0;
599                         v[ldop->i.rt].sign = 0xffffff80 << (24 - curr->r.imm);
600                 }
601         }
602
603         if (!ldop) {
604                 pr_debug("Convert SLL/SRA #%u to EXT%c\n",
605                          curr->r.imm, curr->r.imm == 24 ? 'C' : 'S');
606
607                 to_change->m.rs = curr->r.rt;
608                 to_change->m.op = to_nop->r.imm == 24 ? OP_META_EXTC : OP_META_EXTS;
609                 to_change->i.op = OP_META;
610         }
611
612         to_nop->opcode = 0;
613 }
614
615 static void
616 lightrec_remove_useless_lui(struct block *block, unsigned int offset,
617                             const struct constprop_data *v)
618 {
619         struct opcode *list = block->opcode_list,
620                       *op = &block->opcode_list[offset];
621         int reader;
622
623         if (!op_flag_sync(op->flags) && is_known(v, op->i.rt) &&
624             v[op->i.rt].value == op->i.imm << 16) {
625                 pr_debug("Converting duplicated LUI to NOP\n");
626                 op->opcode = 0x0;
627                 return;
628         }
629
630         if (op->i.imm != 0 || op->i.rt == 0 || offset == block->nb_ops - 1)
631                 return;
632
633         reader = find_next_reader(list, offset + 1, op->i.rt);
634         if (reader <= 0)
635                 return;
636
637         if (opcode_writes_register(list[reader].c, op->i.rt) ||
638             reg_is_dead(list, reader, op->i.rt)) {
639                 pr_debug("Removing useless LUI 0x0\n");
640
641                 if (list[reader].i.rs == op->i.rt)
642                         list[reader].i.rs = 0;
643                 if (list[reader].i.op == OP_SPECIAL &&
644                     list[reader].i.rt == op->i.rt)
645                         list[reader].i.rt = 0;
646                 op->opcode = 0x0;
647         }
648 }
649
650 static void lightrec_lui_to_movi(struct block *block, unsigned int offset)
651 {
652         struct opcode *ori, *lui = &block->opcode_list[offset];
653         int next;
654
655         if (lui->i.op != OP_LUI)
656                 return;
657
658         next = find_next_reader(block->opcode_list, offset + 1, lui->i.rt);
659         if (next > 0) {
660                 ori = &block->opcode_list[next];
661
662                 switch (ori->i.op) {
663                 case OP_ORI:
664                 case OP_ADDI:
665                 case OP_ADDIU:
666                         if (ori->i.rs == ori->i.rt && ori->i.imm) {
667                                 ori->flags |= LIGHTREC_MOVI;
668                                 lui->flags |= LIGHTREC_MOVI;
669                         }
670                         break;
671                 }
672         }
673 }
674
675 static void lightrec_modify_lui(struct block *block, unsigned int offset)
676 {
677         union code c, *lui = &block->opcode_list[offset].c;
678         bool stop = false, stop_next = false;
679         unsigned int i;
680
681         for (i = offset + 1; !stop && i < block->nb_ops; i++) {
682                 c = block->opcode_list[i].c;
683                 stop = stop_next;
684
685                 if ((opcode_is_store(c) && c.i.rt == lui->i.rt)
686                     || (!opcode_is_load(c) && opcode_reads_register(c, lui->i.rt)))
687                         break;
688
689                 if (opcode_writes_register(c, lui->i.rt)) {
690                         if (c.i.op == OP_LWL || c.i.op == OP_LWR) {
691                                 /* LWL/LWR only partially write their target register;
692                                  * therefore the LUI should not write a different value. */
693                                 break;
694                         }
695
696                         pr_debug("Convert LUI at offset 0x%x to kuseg\n",
697                                  (i - 1) << 2);
698                         lui->i.imm = kunseg(lui->i.imm << 16) >> 16;
699                         break;
700                 }
701
702                 if (has_delay_slot(c))
703                         stop_next = true;
704         }
705 }
706
707 static int lightrec_transform_branches(struct lightrec_state *state,
708                                        struct block *block)
709 {
710         struct opcode *op;
711         unsigned int i;
712         s32 offset;
713
714         for (i = 0; i < block->nb_ops; i++) {
715                 op = &block->opcode_list[i];
716
717                 switch (op->i.op) {
718                 case OP_J:
719                         /* Transform J opcode into BEQ $zero, $zero if possible. */
720                         offset = (s32)((block->pc & 0xf0000000) >> 2 | op->j.imm)
721                                 - (s32)(block->pc >> 2) - (s32)i - 1;
722
723                         if (offset == (s16)offset) {
724                                 pr_debug("Transform J into BEQ $zero, $zero\n");
725                                 op->i.op = OP_BEQ;
726                                 op->i.rs = 0;
727                                 op->i.rt = 0;
728                                 op->i.imm = offset;
729
730                         }
731                         fallthrough;
732                 default:
733                         break;
734                 }
735         }
736
737         return 0;
738 }
739
740 static inline bool is_power_of_two(u32 value)
741 {
742         return popcount32(value) == 1;
743 }
744
745 static void lightrec_patch_known_zero(struct opcode *op,
746                                       const struct constprop_data *v)
747 {
748         switch (op->i.op) {
749         case OP_SPECIAL:
750                 switch (op->r.op) {
751                 case OP_SPECIAL_JR:
752                 case OP_SPECIAL_JALR:
753                 case OP_SPECIAL_MTHI:
754                 case OP_SPECIAL_MTLO:
755                         if (is_known_zero(v, op->r.rs))
756                                 op->r.rs = 0;
757                         break;
758                 default:
759                         if (is_known_zero(v, op->r.rs))
760                                 op->r.rs = 0;
761                         fallthrough;
762                 case OP_SPECIAL_SLL:
763                 case OP_SPECIAL_SRL:
764                 case OP_SPECIAL_SRA:
765                         if (is_known_zero(v, op->r.rt))
766                                 op->r.rt = 0;
767                         break;
768                 case OP_SPECIAL_SYSCALL:
769                 case OP_SPECIAL_BREAK:
770                 case OP_SPECIAL_MFHI:
771                 case OP_SPECIAL_MFLO:
772                         break;
773                 }
774                 break;
775         case OP_CP0:
776                 switch (op->r.rs) {
777                 case OP_CP0_MTC0:
778                 case OP_CP0_CTC0:
779                         if (is_known_zero(v, op->r.rt))
780                                 op->r.rt = 0;
781                         break;
782                 default:
783                         break;
784                 }
785                 break;
786         case OP_CP2:
787                 if (op->r.op == OP_CP2_BASIC) {
788                         switch (op->r.rs) {
789                         case OP_CP2_BASIC_MTC2:
790                         case OP_CP2_BASIC_CTC2:
791                                 if (is_known_zero(v, op->r.rt))
792                                         op->r.rt = 0;
793                                 break;
794                         default:
795                                 break;
796                         }
797                 }
798                 break;
799         case OP_BEQ:
800         case OP_BNE:
801                 if (is_known_zero(v, op->i.rt))
802                         op->i.rt = 0;
803                 fallthrough;
804         case OP_REGIMM:
805         case OP_BLEZ:
806         case OP_BGTZ:
807         case OP_ADDI:
808         case OP_ADDIU:
809         case OP_SLTI:
810         case OP_SLTIU:
811         case OP_ANDI:
812         case OP_ORI:
813         case OP_XORI:
814         case OP_META_MULT2:
815         case OP_META_MULTU2:
816         case OP_META:
817                 if (is_known_zero(v, op->m.rs))
818                         op->m.rs = 0;
819                 break;
820         case OP_SB:
821         case OP_SH:
822         case OP_SWL:
823         case OP_SW:
824         case OP_SWR:
825                 if (is_known_zero(v, op->i.rt))
826                         op->i.rt = 0;
827                 fallthrough;
828         case OP_LB:
829         case OP_LH:
830         case OP_LWL:
831         case OP_LW:
832         case OP_LBU:
833         case OP_LHU:
834         case OP_LWR:
835         case OP_LWC2:
836         case OP_SWC2:
837                 if (is_known(v, op->i.rs)
838                     && kunseg(v[op->i.rs].value) == 0)
839                         op->i.rs = 0;
840                 break;
841         default:
842                 break;
843         }
844 }
845
846 static void lightrec_reset_syncs(struct block *block)
847 {
848         struct opcode *op, *list = block->opcode_list;
849         unsigned int i;
850         s32 offset;
851
852         for (i = 0; i < block->nb_ops; i++)
853                 list[i].flags &= ~LIGHTREC_SYNC;
854
855         for (i = 0; i < block->nb_ops; i++) {
856                 op = &list[i];
857
858                 if (has_delay_slot(op->c)) {
859                         if (op_flag_local_branch(op->flags)) {
860                                 offset = i + 1 - op_flag_no_ds(op->flags) + (s16)op->i.imm;
861                                 list[offset].flags |= LIGHTREC_SYNC;
862                         }
863
864                         if (op_flag_emulate_branch(op->flags) && i + 2 < block->nb_ops)
865                                 list[i + 2].flags |= LIGHTREC_SYNC;
866                 }
867         }
868 }
869
870 static int lightrec_transform_ops(struct lightrec_state *state, struct block *block)
871 {
872         struct opcode *op, *list = block->opcode_list;
873         struct constprop_data v[32] = LIGHTREC_CONSTPROP_INITIALIZER;
874         unsigned int i;
875         bool local;
876         u8 tmp;
877
878         for (i = 0; i < block->nb_ops; i++) {
879                 op = &list[i];
880
881                 lightrec_consts_propagate(block, i, v);
882
883                 lightrec_patch_known_zero(op, v);
884
885                 /* Transform all opcodes detected as useless to real NOPs
886                  * (0x0: SLL r0, r0, #0) */
887                 if (op->opcode != 0 && is_nop(op->c)) {
888                         pr_debug("Converting useless opcode 0x%08x to NOP\n",
889                                         op->opcode);
890                         op->opcode = 0x0;
891                 }
892
893                 if (!op->opcode)
894                         continue;
895
896                 switch (op->i.op) {
897                 case OP_BEQ:
898                         if (op->i.rs == op->i.rt ||
899                             (is_known(v, op->i.rs) && is_known(v, op->i.rt) &&
900                              v[op->i.rs].value == v[op->i.rt].value)) {
901                                 if (op->i.rs != op->i.rt)
902                                         pr_debug("Found always-taken BEQ\n");
903
904                                 op->i.rs = 0;
905                                 op->i.rt = 0;
906                         } else if (v[op->i.rs].known & v[op->i.rt].known &
907                                    (v[op->i.rs].value ^ v[op->i.rt].value)) {
908                                 pr_debug("Found never-taken BEQ\n");
909
910                                 local = op_flag_local_branch(op->flags);
911                                 op->opcode = 0;
912                                 op->flags = 0;
913
914                                 if (local)
915                                         lightrec_reset_syncs(block);
916                         } else if (op->i.rs == 0) {
917                                 op->i.rs = op->i.rt;
918                                 op->i.rt = 0;
919                         }
920                         break;
921
922                 case OP_BNE:
923                         if (v[op->i.rs].known & v[op->i.rt].known &
924                             (v[op->i.rs].value ^ v[op->i.rt].value)) {
925                                 pr_debug("Found always-taken BNE\n");
926
927                                 op->i.op = OP_BEQ;
928                                 op->i.rs = 0;
929                                 op->i.rt = 0;
930                         } else if (is_known(v, op->i.rs) && is_known(v, op->i.rt) &&
931                                    v[op->i.rs].value == v[op->i.rt].value) {
932                                 pr_debug("Found never-taken BNE\n");
933
934                                 local = op_flag_local_branch(op->flags);
935                                 op->opcode = 0;
936                                 op->flags = 0;
937
938                                 if (local)
939                                         lightrec_reset_syncs(block);
940                         } else if (op->i.rs == 0) {
941                                 op->i.rs = op->i.rt;
942                                 op->i.rt = 0;
943                         }
944                         break;
945
946                 case OP_BLEZ:
947                         if (v[op->i.rs].known & BIT(31) &&
948                             v[op->i.rs].value & BIT(31)) {
949                                 pr_debug("Found always-taken BLEZ\n");
950
951                                 op->i.op = OP_BEQ;
952                                 op->i.rs = 0;
953                                 op->i.rt = 0;
954                         }
955                         break;
956
957                 case OP_BGTZ:
958                         if (v[op->i.rs].known & BIT(31) &&
959                             v[op->i.rs].value & BIT(31)) {
960                                 pr_debug("Found never-taken BGTZ\n");
961
962                                 local = op_flag_local_branch(op->flags);
963                                 op->opcode = 0;
964                                 op->flags = 0;
965
966                                 if (local)
967                                         lightrec_reset_syncs(block);
968                         }
969                         break;
970
971                 case OP_LUI:
972                         if (i == 0 || !has_delay_slot(list[i - 1].c))
973                                 lightrec_modify_lui(block, i);
974                         lightrec_remove_useless_lui(block, i, v);
975                         if (i == 0 || !has_delay_slot(list[i - 1].c))
976                                 lightrec_lui_to_movi(block, i);
977                         break;
978
979                 /* Transform ORI/ADDI/ADDIU with imm #0 or ORR/ADD/ADDU/SUB/SUBU
980                  * with register $zero to the MOV meta-opcode */
981                 case OP_ORI:
982                 case OP_ADDI:
983                 case OP_ADDIU:
984                         if (op->i.imm == 0) {
985                                 pr_debug("Convert ORI/ADDI/ADDIU #0 to MOV\n");
986                                 op->m.rd = op->i.rt;
987                                 op->m.op = OP_META_MOV;
988                                 op->i.op = OP_META;
989                         }
990                         break;
991                 case OP_ANDI:
992                         if (bits_are_known_zero(v, op->i.rs, ~op->i.imm)) {
993                                 pr_debug("Found useless ANDI 0x%x\n", op->i.imm);
994
995                                 if (op->i.rs == op->i.rt) {
996                                         op->opcode = 0;
997                                 } else {
998                                         op->m.rd = op->i.rt;
999                                         op->m.op = OP_META_MOV;
1000                                         op->i.op = OP_META;
1001                                 }
1002                         }
1003                         break;
1004                 case OP_REGIMM:
1005                         switch (op->r.rt) {
1006                         case OP_REGIMM_BLTZ:
1007                         case OP_REGIMM_BGEZ:
1008                                 if (!(v[op->r.rs].known & BIT(31)))
1009                                         break;
1010
1011                                 if (!!(v[op->r.rs].value & BIT(31))
1012                                     ^ (op->r.rt == OP_REGIMM_BGEZ)) {
1013                                         pr_debug("Found always-taken BLTZ/BGEZ\n");
1014                                         op->i.op = OP_BEQ;
1015                                         op->i.rs = 0;
1016                                         op->i.rt = 0;
1017                                 } else {
1018                                         pr_debug("Found never-taken BLTZ/BGEZ\n");
1019
1020                                         local = op_flag_local_branch(op->flags);
1021                                         op->opcode = 0;
1022                                         op->flags = 0;
1023
1024                                         if (local)
1025                                                 lightrec_reset_syncs(block);
1026                                 }
1027                                 break;
1028                         case OP_REGIMM_BLTZAL:
1029                         case OP_REGIMM_BGEZAL:
1030                                 /* TODO: Detect always-taken and replace with JAL */
1031                                 break;
1032                         }
1033                         break;
1034                 case OP_SPECIAL:
1035                         switch (op->r.op) {
1036                         case OP_SPECIAL_SRAV:
1037                                 if ((v[op->r.rs].known & 0x1f) != 0x1f)
1038                                         break;
1039
1040                                 pr_debug("Convert SRAV to SRA\n");
1041                                 op->r.imm = v[op->r.rs].value & 0x1f;
1042                                 op->r.op = OP_SPECIAL_SRA;
1043
1044                                 fallthrough;
1045                         case OP_SPECIAL_SRA:
1046                                 if (op->r.imm == 0) {
1047                                         pr_debug("Convert SRA #0 to MOV\n");
1048                                         op->m.rs = op->r.rt;
1049                                         op->m.op = OP_META_MOV;
1050                                         op->i.op = OP_META;
1051                                         break;
1052                                 }
1053                                 break;
1054
1055                         case OP_SPECIAL_SLLV:
1056                                 if ((v[op->r.rs].known & 0x1f) != 0x1f)
1057                                         break;
1058
1059                                 pr_debug("Convert SLLV to SLL\n");
1060                                 op->r.imm = v[op->r.rs].value & 0x1f;
1061                                 op->r.op = OP_SPECIAL_SLL;
1062
1063                                 fallthrough;
1064                         case OP_SPECIAL_SLL:
1065                                 if (op->r.imm == 0) {
1066                                         pr_debug("Convert SLL #0 to MOV\n");
1067                                         op->m.rs = op->r.rt;
1068                                         op->m.op = OP_META_MOV;
1069                                         op->i.op = OP_META;
1070                                 }
1071
1072                                 lightrec_optimize_sll_sra(block->opcode_list, i, v);
1073                                 break;
1074
1075                         case OP_SPECIAL_SRLV:
1076                                 if ((v[op->r.rs].known & 0x1f) != 0x1f)
1077                                         break;
1078
1079                                 pr_debug("Convert SRLV to SRL\n");
1080                                 op->r.imm = v[op->r.rs].value & 0x1f;
1081                                 op->r.op = OP_SPECIAL_SRL;
1082
1083                                 fallthrough;
1084                         case OP_SPECIAL_SRL:
1085                                 if (op->r.imm == 0) {
1086                                         pr_debug("Convert SRL #0 to MOV\n");
1087                                         op->m.rs = op->r.rt;
1088                                         op->m.op = OP_META_MOV;
1089                                         op->i.op = OP_META;
1090                                 }
1091                                 break;
1092
1093                         case OP_SPECIAL_MULT:
1094                         case OP_SPECIAL_MULTU:
1095                                 if (is_known(v, op->r.rs) &&
1096                                     is_power_of_two(v[op->r.rs].value)) {
1097                                         tmp = op->c.i.rs;
1098                                         op->c.i.rs = op->c.i.rt;
1099                                         op->c.i.rt = tmp;
1100                                 } else if (!is_known(v, op->r.rt) ||
1101                                            !is_power_of_two(v[op->r.rt].value)) {
1102                                         break;
1103                                 }
1104
1105                                 pr_debug("Multiply by power-of-two: %u\n",
1106                                          v[op->r.rt].value);
1107
1108                                 if (op->r.op == OP_SPECIAL_MULT)
1109                                         op->i.op = OP_META_MULT2;
1110                                 else
1111                                         op->i.op = OP_META_MULTU2;
1112
1113                                 op->r.op = ctz32(v[op->r.rt].value);
1114                                 break;
1115                         case OP_SPECIAL_NOR:
1116                                 if (op->r.rs == 0 || op->r.rt == 0) {
1117                                         pr_debug("Convert NOR $zero to COM\n");
1118                                         op->i.op = OP_META;
1119                                         op->m.op = OP_META_COM;
1120                                         if (!op->m.rs)
1121                                                 op->m.rs = op->r.rt;
1122                                 }
1123                                 break;
1124                         case OP_SPECIAL_OR:
1125                         case OP_SPECIAL_ADD:
1126                         case OP_SPECIAL_ADDU:
1127                                 if (op->r.rs == 0) {
1128                                         pr_debug("Convert OR/ADD $zero to MOV\n");
1129                                         op->m.rs = op->r.rt;
1130                                         op->m.op = OP_META_MOV;
1131                                         op->i.op = OP_META;
1132                                 }
1133                                 fallthrough;
1134                         case OP_SPECIAL_SUB:
1135                         case OP_SPECIAL_SUBU:
1136                                 if (op->r.rt == 0) {
1137                                         pr_debug("Convert OR/ADD/SUB $zero to MOV\n");
1138                                         op->m.op = OP_META_MOV;
1139                                         op->i.op = OP_META;
1140                                 }
1141                                 fallthrough;
1142                         default:
1143                                 break;
1144                         }
1145                         fallthrough;
1146                 default:
1147                         break;
1148                 }
1149         }
1150
1151         return 0;
1152 }
1153
1154 static bool lightrec_can_switch_delay_slot(union code op, union code next_op)
1155 {
1156         switch (op.i.op) {
1157         case OP_SPECIAL:
1158                 switch (op.r.op) {
1159                 case OP_SPECIAL_JALR:
1160                         if (opcode_reads_register(next_op, op.r.rd) ||
1161                             opcode_writes_register(next_op, op.r.rd))
1162                                 return false;
1163                         fallthrough;
1164                 case OP_SPECIAL_JR:
1165                         if (opcode_writes_register(next_op, op.r.rs))
1166                                 return false;
1167                         fallthrough;
1168                 default:
1169                         break;
1170                 }
1171                 fallthrough;
1172         case OP_J:
1173                 break;
1174         case OP_JAL:
1175                 if (opcode_reads_register(next_op, 31) ||
1176                     opcode_writes_register(next_op, 31))
1177                         return false;;
1178
1179                 break;
1180         case OP_BEQ:
1181         case OP_BNE:
1182                 if (op.i.rt && opcode_writes_register(next_op, op.i.rt))
1183                         return false;
1184                 fallthrough;
1185         case OP_BLEZ:
1186         case OP_BGTZ:
1187                 if (op.i.rs && opcode_writes_register(next_op, op.i.rs))
1188                         return false;
1189                 break;
1190         case OP_REGIMM:
1191                 switch (op.r.rt) {
1192                 case OP_REGIMM_BLTZAL:
1193                 case OP_REGIMM_BGEZAL:
1194                         if (opcode_reads_register(next_op, 31) ||
1195                             opcode_writes_register(next_op, 31))
1196                                 return false;
1197                         fallthrough;
1198                 case OP_REGIMM_BLTZ:
1199                 case OP_REGIMM_BGEZ:
1200                         if (op.i.rs && opcode_writes_register(next_op, op.i.rs))
1201                                 return false;
1202                         break;
1203                 }
1204                 fallthrough;
1205         default:
1206                 break;
1207         }
1208
1209         return true;
1210 }
1211
1212 static int lightrec_switch_delay_slots(struct lightrec_state *state, struct block *block)
1213 {
1214         struct opcode *list, *next = &block->opcode_list[0];
1215         unsigned int i;
1216         union code op, next_op;
1217         u32 flags;
1218
1219         for (i = 0; i < block->nb_ops - 1; i++) {
1220                 list = next;
1221                 next = &block->opcode_list[i + 1];
1222                 next_op = next->c;
1223                 op = list->c;
1224
1225                 if (!has_delay_slot(op) || op_flag_no_ds(list->flags) ||
1226                     op_flag_emulate_branch(list->flags) ||
1227                     op.opcode == 0 || next_op.opcode == 0)
1228                         continue;
1229
1230                 if (is_delay_slot(block->opcode_list, i))
1231                         continue;
1232
1233                 if (op_flag_sync(next->flags))
1234                         continue;
1235
1236                 if (op_flag_load_delay(next->flags) && opcode_is_load(next_op))
1237                         continue;
1238
1239                 if (!lightrec_can_switch_delay_slot(list->c, next_op))
1240                         continue;
1241
1242                 pr_debug("Swap branch and delay slot opcodes "
1243                          "at offsets 0x%x / 0x%x\n",
1244                          i << 2, (i + 1) << 2);
1245
1246                 flags = next->flags | (list->flags & LIGHTREC_SYNC);
1247                 list->c = next_op;
1248                 next->c = op;
1249                 next->flags = (list->flags | LIGHTREC_NO_DS) & ~LIGHTREC_SYNC;
1250                 list->flags = flags | LIGHTREC_NO_DS;
1251         }
1252
1253         return 0;
1254 }
1255
1256 static int lightrec_detect_impossible_branches(struct lightrec_state *state,
1257                                                struct block *block)
1258 {
1259         struct opcode *op, *list = block->opcode_list, *next = &list[0];
1260         unsigned int i;
1261         int ret = 0;
1262
1263         for (i = 0; i < block->nb_ops - 1; i++) {
1264                 op = next;
1265                 next = &list[i + 1];
1266
1267                 if (!has_delay_slot(op->c) ||
1268                     (!has_delay_slot(next->c) &&
1269                      !opcode_is_mfc(next->c) &&
1270                      !(next->i.op == OP_CP0 && next->r.rs == OP_CP0_RFE)))
1271                         continue;
1272
1273                 if (op->c.opcode == next->c.opcode) {
1274                         /* The delay slot is the exact same opcode as the branch
1275                          * opcode: this is effectively a NOP */
1276                         next->c.opcode = 0;
1277                         continue;
1278                 }
1279
1280                 op->flags |= LIGHTREC_EMULATE_BRANCH;
1281
1282                 if (OPT_LOCAL_BRANCHES && i + 2 < block->nb_ops) {
1283                         /* The interpreter will only emulate the branch, then
1284                          * return to the compiled code. Add a SYNC after the
1285                          * branch + delay slot in the case where the branch
1286                          * was not taken. */
1287                         list[i + 2].flags |= LIGHTREC_SYNC;
1288                 }
1289         }
1290
1291         return ret;
1292 }
1293
1294 static bool is_local_branch(const struct block *block, unsigned int idx)
1295 {
1296         const struct opcode *op = &block->opcode_list[idx];
1297         s32 offset;
1298
1299         switch (op->c.i.op) {
1300         case OP_BEQ:
1301         case OP_BNE:
1302         case OP_BLEZ:
1303         case OP_BGTZ:
1304         case OP_REGIMM:
1305                 offset = idx + 1 + (s16)op->c.i.imm;
1306                 if (offset >= 0 && offset < block->nb_ops)
1307                         return true;
1308                 fallthrough;
1309         default:
1310                 return false;
1311         }
1312 }
1313
1314 static int lightrec_handle_load_delays(struct lightrec_state *state,
1315                                        struct block *block)
1316 {
1317         struct opcode *op, *list = block->opcode_list;
1318         unsigned int i;
1319         s16 imm;
1320
1321         for (i = 0; i < block->nb_ops; i++) {
1322                 op = &list[i];
1323
1324                 if (!opcode_is_load(op->c) || !op->c.i.rt || op->c.i.op == OP_LWC2)
1325                         continue;
1326
1327                 if (!is_delay_slot(list, i)) {
1328                         /* Only handle load delays in delay slots.
1329                          * PSX games never abused load delay slots otherwise. */
1330                         continue;
1331                 }
1332
1333                 if (is_local_branch(block, i - 1)) {
1334                         imm = (s16)list[i - 1].c.i.imm;
1335
1336                         if (!opcode_reads_register(list[i + imm].c, op->c.i.rt)) {
1337                                 /* The target opcode of the branch is inside
1338                                  * the block, and it does not read the register
1339                                  * written to by the load opcode; we can ignore
1340                                  * the load delay. */
1341                                 continue;
1342                         }
1343                 }
1344
1345                 op->flags |= LIGHTREC_LOAD_DELAY;
1346         }
1347
1348         return 0;
1349 }
1350
1351 static int lightrec_swap_load_delays(struct lightrec_state *state,
1352                                      struct block *block)
1353 {
1354         unsigned int i;
1355         union code c, next;
1356         bool in_ds = false, skip_next = false;
1357         struct opcode op;
1358
1359         if (block->nb_ops < 2)
1360                 return 0;
1361
1362         for (i = 0; i < block->nb_ops - 2; i++) {
1363                 c = block->opcode_list[i].c;
1364
1365                 if (skip_next) {
1366                         skip_next = false;
1367                 } else if (!in_ds && opcode_is_load(c) && c.i.op != OP_LWC2) {
1368                         next = block->opcode_list[i + 1].c;
1369
1370                         switch (next.i.op) {
1371                         case OP_LWL:
1372                         case OP_LWR:
1373                         case OP_REGIMM:
1374                         case OP_BEQ:
1375                         case OP_BNE:
1376                         case OP_BLEZ:
1377                         case OP_BGTZ:
1378                                 continue;
1379                         }
1380
1381                         if (opcode_reads_register(next, c.i.rt)
1382                             && !opcode_writes_register(next, c.i.rs)) {
1383                                 pr_debug("Swapping opcodes at offset 0x%x to "
1384                                          "respect load delay\n", i << 2);
1385
1386                                 op = block->opcode_list[i];
1387                                 block->opcode_list[i] = block->opcode_list[i + 1];
1388                                 block->opcode_list[i + 1] = op;
1389                                 skip_next = true;
1390                         }
1391                 }
1392
1393                 in_ds = has_delay_slot(c);
1394         }
1395
1396         return 0;
1397 }
1398
1399 static int lightrec_local_branches(struct lightrec_state *state, struct block *block)
1400 {
1401         const struct opcode *ds;
1402         struct opcode *list;
1403         unsigned int i;
1404         s32 offset;
1405
1406         for (i = 0; i < block->nb_ops; i++) {
1407                 list = &block->opcode_list[i];
1408
1409                 if (should_emulate(list) || !is_local_branch(block, i))
1410                         continue;
1411
1412                 offset = i + 1 + (s16)list->c.i.imm;
1413
1414                 pr_debug("Found local branch to offset 0x%x\n", offset << 2);
1415
1416                 ds = get_delay_slot(block->opcode_list, i);
1417                 if (op_flag_load_delay(ds->flags) && opcode_is_load(ds->c)) {
1418                         pr_debug("Branch delay slot has a load delay - skip\n");
1419                         continue;
1420                 }
1421
1422                 if (should_emulate(&block->opcode_list[offset])) {
1423                         pr_debug("Branch target must be emulated - skip\n");
1424                         continue;
1425                 }
1426
1427                 if (offset && has_delay_slot(block->opcode_list[offset - 1].c)) {
1428                         pr_debug("Branch target is a delay slot - skip\n");
1429                         continue;
1430                 }
1431
1432                 list->flags |= LIGHTREC_LOCAL_BRANCH;
1433         }
1434
1435         lightrec_reset_syncs(block);
1436
1437         return 0;
1438 }
1439
1440 bool has_delay_slot(union code op)
1441 {
1442         switch (op.i.op) {
1443         case OP_SPECIAL:
1444                 switch (op.r.op) {
1445                 case OP_SPECIAL_JR:
1446                 case OP_SPECIAL_JALR:
1447                         return true;
1448                 default:
1449                         return false;
1450                 }
1451         case OP_J:
1452         case OP_JAL:
1453         case OP_BEQ:
1454         case OP_BNE:
1455         case OP_BLEZ:
1456         case OP_BGTZ:
1457         case OP_REGIMM:
1458                 return true;
1459         default:
1460                 return false;
1461         }
1462 }
1463
1464 bool is_delay_slot(const struct opcode *list, unsigned int offset)
1465 {
1466         return offset > 0
1467                 && !op_flag_no_ds(list[offset - 1].flags)
1468                 && has_delay_slot(list[offset - 1].c);
1469 }
1470
1471 bool should_emulate(const struct opcode *list)
1472 {
1473         return op_flag_emulate_branch(list->flags) && has_delay_slot(list->c);
1474 }
1475
1476 static bool op_writes_rd(union code c)
1477 {
1478         switch (c.i.op) {
1479         case OP_SPECIAL:
1480         case OP_META:
1481                 return true;
1482         default:
1483                 return false;
1484         }
1485 }
1486
1487 static void lightrec_add_reg_op(struct opcode *op, u8 reg, u32 reg_op)
1488 {
1489         if (op_writes_rd(op->c) && reg == op->r.rd)
1490                 op->flags |= LIGHTREC_REG_RD(reg_op);
1491         else if (op->i.rs == reg)
1492                 op->flags |= LIGHTREC_REG_RS(reg_op);
1493         else if (op->i.rt == reg)
1494                 op->flags |= LIGHTREC_REG_RT(reg_op);
1495         else
1496                 pr_debug("Cannot add unload/clean/discard flag: "
1497                          "opcode does not touch register %s!\n",
1498                          lightrec_reg_name(reg));
1499 }
1500
1501 static void lightrec_add_unload(struct opcode *op, u8 reg)
1502 {
1503         lightrec_add_reg_op(op, reg, LIGHTREC_REG_UNLOAD);
1504 }
1505
1506 static void lightrec_add_discard(struct opcode *op, u8 reg)
1507 {
1508         lightrec_add_reg_op(op, reg, LIGHTREC_REG_DISCARD);
1509 }
1510
1511 static void lightrec_add_clean(struct opcode *op, u8 reg)
1512 {
1513         lightrec_add_reg_op(op, reg, LIGHTREC_REG_CLEAN);
1514 }
1515
1516 static void
1517 lightrec_early_unload_sync(struct opcode *list, s16 *last_r, s16 *last_w)
1518 {
1519         unsigned int reg;
1520         s16 offset;
1521
1522         for (reg = 0; reg < 34; reg++) {
1523                 offset = s16_max(last_w[reg], last_r[reg]);
1524
1525                 if (offset >= 0)
1526                         lightrec_add_unload(&list[offset], reg);
1527         }
1528
1529         memset(last_r, 0xff, sizeof(*last_r) * 34);
1530         memset(last_w, 0xff, sizeof(*last_w) * 34);
1531 }
1532
1533 static int lightrec_early_unload(struct lightrec_state *state, struct block *block)
1534 {
1535         u16 i, offset;
1536         struct opcode *op;
1537         s16 last_r[34], last_w[34], last_sync = 0, next_sync = 0;
1538         u64 mask_r, mask_w, dirty = 0, loaded = 0;
1539         u8 reg, load_delay_reg = 0;
1540
1541         memset(last_r, 0xff, sizeof(last_r));
1542         memset(last_w, 0xff, sizeof(last_w));
1543
1544         /*
1545          * Clean if:
1546          * - the register is dirty, and is read again after a branch opcode
1547          *
1548          * Unload if:
1549          * - the register is dirty or loaded, and is not read again
1550          * - the register is dirty or loaded, and is written again after a branch opcode
1551          * - the next opcode has the SYNC flag set
1552          *
1553          * Discard if:
1554          * - the register is dirty or loaded, and is written again
1555          */
1556
1557         for (i = 0; i < block->nb_ops; i++) {
1558                 op = &block->opcode_list[i];
1559
1560                 if (OPT_HANDLE_LOAD_DELAYS && load_delay_reg) {
1561                         /* Handle delayed register write from load opcodes in
1562                          * delay slots */
1563                         last_w[load_delay_reg] = i;
1564                         load_delay_reg = 0;
1565                 }
1566
1567                 if (op_flag_sync(op->flags) || should_emulate(op)) {
1568                         /* The next opcode has the SYNC flag set, or is a branch
1569                          * that should be emulated: unload all registers. */
1570                         lightrec_early_unload_sync(block->opcode_list, last_r, last_w);
1571                         dirty = 0;
1572                         loaded = 0;
1573                 }
1574
1575                 if (next_sync == i) {
1576                         last_sync = i;
1577                         pr_debug("Last sync: 0x%x\n", last_sync << 2);
1578                 }
1579
1580                 if (has_delay_slot(op->c)) {
1581                         next_sync = i + 1 + !op_flag_no_ds(op->flags);
1582                         pr_debug("Next sync: 0x%x\n", next_sync << 2);
1583                 }
1584
1585                 mask_r = opcode_read_mask(op->c);
1586                 mask_w = opcode_write_mask(op->c);
1587
1588                 if (op_flag_load_delay(op->flags) && opcode_is_load(op->c)) {
1589                         /* If we have a load opcode in a delay slot, its target
1590                          * register is actually not written there but at a
1591                          * later point, in the dispatcher. Prevent the algorithm
1592                          * from discarding its previous value. */
1593                         load_delay_reg = op->c.i.rt;
1594                         mask_w &= ~BIT(op->c.i.rt);
1595                 }
1596
1597                 for (reg = 0; reg < 34; reg++) {
1598                         if (mask_r & BIT(reg)) {
1599                                 if (dirty & BIT(reg) && last_w[reg] < last_sync) {
1600                                         /* The register is dirty, and is read
1601                                          * again after a branch: clean it */
1602
1603                                         lightrec_add_clean(&block->opcode_list[last_w[reg]], reg);
1604                                         dirty &= ~BIT(reg);
1605                                         loaded |= BIT(reg);
1606                                 }
1607
1608                                 last_r[reg] = i;
1609                         }
1610
1611                         if (mask_w & BIT(reg)) {
1612                                 if ((dirty & BIT(reg) && last_w[reg] < last_sync) ||
1613                                     (loaded & BIT(reg) && last_r[reg] < last_sync)) {
1614                                         /* The register is dirty or loaded, and
1615                                          * is written again after a branch:
1616                                          * unload it */
1617
1618                                         offset = s16_max(last_w[reg], last_r[reg]);
1619                                         lightrec_add_unload(&block->opcode_list[offset], reg);
1620                                         dirty &= ~BIT(reg);
1621                                         loaded &= ~BIT(reg);
1622                                 } else if (!(mask_r & BIT(reg)) &&
1623                                            ((dirty & BIT(reg) && last_w[reg] > last_sync) ||
1624                                            (loaded & BIT(reg) && last_r[reg] > last_sync))) {
1625                                         /* The register is dirty or loaded, and
1626                                          * is written again: discard it */
1627
1628                                         offset = s16_max(last_w[reg], last_r[reg]);
1629                                         lightrec_add_discard(&block->opcode_list[offset], reg);
1630                                         dirty &= ~BIT(reg);
1631                                         loaded &= ~BIT(reg);
1632                                 }
1633
1634                                 last_w[reg] = i;
1635                         }
1636
1637                 }
1638
1639                 dirty |= mask_w;
1640                 loaded |= mask_r;
1641         }
1642
1643         /* Unload all registers that are dirty or loaded at the end of block. */
1644         lightrec_early_unload_sync(block->opcode_list, last_r, last_w);
1645
1646         return 0;
1647 }
1648
1649 static int lightrec_flag_io(struct lightrec_state *state, struct block *block)
1650 {
1651         struct opcode *list;
1652         enum psx_map psx_map;
1653         struct constprop_data v[32] = LIGHTREC_CONSTPROP_INITIALIZER;
1654         unsigned int i;
1655         u32 val, kunseg_val;
1656         bool no_mask;
1657
1658         for (i = 0; i < block->nb_ops; i++) {
1659                 list = &block->opcode_list[i];
1660
1661                 lightrec_consts_propagate(block, i, v);
1662
1663                 switch (list->i.op) {
1664                 case OP_SB:
1665                 case OP_SH:
1666                 case OP_SW:
1667                         /* Mark all store operations that target $sp or $gp
1668                          * as not requiring code invalidation. This is based
1669                          * on the heuristic that stores using one of these
1670                          * registers as address will never hit a code page. */
1671                         if (list->i.rs >= 28 && list->i.rs <= 29 &&
1672                             !state->maps[PSX_MAP_KERNEL_USER_RAM].ops) {
1673                                 pr_debug("Flaging opcode 0x%08x as not requiring invalidation\n",
1674                                          list->opcode);
1675                                 list->flags |= LIGHTREC_NO_INVALIDATE;
1676                         }
1677
1678                         /* Detect writes whose destination address is inside the
1679                          * current block, using constant propagation. When these
1680                          * occur, we mark the blocks as not compilable. */
1681                         if (is_known(v, list->i.rs) &&
1682                             kunseg(v[list->i.rs].value) >= kunseg(block->pc) &&
1683                             kunseg(v[list->i.rs].value) < (kunseg(block->pc) + block->nb_ops * 4)) {
1684                                 pr_debug("Self-modifying block detected\n");
1685                                 block_set_flags(block, BLOCK_NEVER_COMPILE);
1686                                 list->flags |= LIGHTREC_SMC;
1687                         }
1688                         fallthrough;
1689                 case OP_SWL:
1690                 case OP_SWR:
1691                 case OP_SWC2:
1692                 case OP_LB:
1693                 case OP_LBU:
1694                 case OP_LH:
1695                 case OP_LHU:
1696                 case OP_LW:
1697                 case OP_LWL:
1698                 case OP_LWR:
1699                 case OP_LWC2:
1700                         if (v[list->i.rs].known | v[list->i.rs].sign) {
1701                                 psx_map = lightrec_get_constprop_map(state, v,
1702                                                                      list->i.rs,
1703                                                                      (s16) list->i.imm);
1704
1705                                 if (psx_map != PSX_MAP_UNKNOWN && !is_known(v, list->i.rs))
1706                                         pr_debug("Detected map thanks to bit-level const propagation!\n");
1707
1708                                 list->flags &= ~LIGHTREC_IO_MASK;
1709
1710                                 val = v[list->i.rs].value + (s16) list->i.imm;
1711                                 kunseg_val = kunseg(val);
1712
1713                                 no_mask = (v[list->i.rs].known & ~v[list->i.rs].value
1714                                            & 0xe0000000) == 0xe0000000;
1715
1716                                 switch (psx_map) {
1717                                 case PSX_MAP_KERNEL_USER_RAM:
1718                                         if (no_mask)
1719                                                 list->flags |= LIGHTREC_NO_MASK;
1720                                         fallthrough;
1721                                 case PSX_MAP_MIRROR1:
1722                                 case PSX_MAP_MIRROR2:
1723                                 case PSX_MAP_MIRROR3:
1724                                         pr_debug("Flaging opcode %u as RAM access\n", i);
1725                                         list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_RAM);
1726                                         if (no_mask && state->mirrors_mapped)
1727                                                 list->flags |= LIGHTREC_NO_MASK;
1728                                         break;
1729                                 case PSX_MAP_BIOS:
1730                                         pr_debug("Flaging opcode %u as BIOS access\n", i);
1731                                         list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_BIOS);
1732                                         if (no_mask)
1733                                                 list->flags |= LIGHTREC_NO_MASK;
1734                                         break;
1735                                 case PSX_MAP_SCRATCH_PAD:
1736                                         pr_debug("Flaging opcode %u as scratchpad access\n", i);
1737                                         list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_SCRATCH);
1738                                         if (no_mask)
1739                                                 list->flags |= LIGHTREC_NO_MASK;
1740
1741                                         /* Consider that we're never going to run code from
1742                                          * the scratchpad. */
1743                                         list->flags |= LIGHTREC_NO_INVALIDATE;
1744                                         break;
1745                                 case PSX_MAP_HW_REGISTERS:
1746                                         if (state->ops.hw_direct &&
1747                                             state->ops.hw_direct(kunseg_val,
1748                                                                  opcode_is_store(list->c),
1749                                                                  opcode_get_io_size(list->c))) {
1750                                                 pr_debug("Flagging opcode %u as direct I/O access\n",
1751                                                          i);
1752                                                 list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_DIRECT_HW);
1753
1754                                                 if (no_mask)
1755                                                         list->flags |= LIGHTREC_NO_MASK;
1756                                         } else {
1757                                                 pr_debug("Flagging opcode %u as I/O access\n",
1758                                                          i);
1759                                                 list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_HW);
1760                                         }
1761                                         break;
1762                                 default:
1763                                         break;
1764                                 }
1765                         }
1766
1767                         if (!LIGHTREC_FLAGS_GET_IO_MODE(list->flags)
1768                             && list->i.rs >= 28 && list->i.rs <= 29
1769                             && !state->maps[PSX_MAP_KERNEL_USER_RAM].ops) {
1770                                 /* Assume that all I/O operations that target
1771                                  * $sp or $gp will always only target a mapped
1772                                  * memory (RAM, BIOS, scratchpad). */
1773                                 if (state->opt_flags & LIGHTREC_OPT_SP_GP_HIT_RAM)
1774                                         list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_RAM);
1775                                 else
1776                                         list->flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_DIRECT);
1777                         }
1778
1779                         fallthrough;
1780                 default:
1781                         break;
1782                 }
1783         }
1784
1785         return 0;
1786 }
1787
1788 static u8 get_mfhi_mflo_reg(const struct block *block, u16 offset,
1789                             const struct opcode *last,
1790                             u32 mask, bool sync, bool mflo, bool another)
1791 {
1792         const struct opcode *op, *next = &block->opcode_list[offset];
1793         u32 old_mask;
1794         u8 reg2, reg = mflo ? REG_LO : REG_HI;
1795         u16 branch_offset;
1796         unsigned int i;
1797
1798         for (i = offset; i < block->nb_ops; i++) {
1799                 op = next;
1800                 next = &block->opcode_list[i + 1];
1801                 old_mask = mask;
1802
1803                 /* If any other opcode writes or reads to the register
1804                  * we'd use, then we cannot use it anymore. */
1805                 mask |= opcode_read_mask(op->c);
1806                 mask |= opcode_write_mask(op->c);
1807
1808                 if (op_flag_sync(op->flags))
1809                         sync = true;
1810
1811                 switch (op->i.op) {
1812                 case OP_BEQ:
1813                 case OP_BNE:
1814                 case OP_BLEZ:
1815                 case OP_BGTZ:
1816                 case OP_REGIMM:
1817                         /* TODO: handle backwards branches too */
1818                         if (!last && op_flag_local_branch(op->flags) &&
1819                             (s16)op->c.i.imm >= 0) {
1820                                 branch_offset = i + 1 + (s16)op->c.i.imm
1821                                         - !!op_flag_no_ds(op->flags);
1822
1823                                 reg = get_mfhi_mflo_reg(block, branch_offset, NULL,
1824                                                         mask, sync, mflo, false);
1825                                 reg2 = get_mfhi_mflo_reg(block, offset + 1, next,
1826                                                          mask, sync, mflo, false);
1827                                 if (reg > 0 && reg == reg2)
1828                                         return reg;
1829                                 if (!reg && !reg2)
1830                                         return 0;
1831                         }
1832
1833                         return mflo ? REG_LO : REG_HI;
1834                 case OP_META_MULT2:
1835                 case OP_META_MULTU2:
1836                         return 0;
1837                 case OP_SPECIAL:
1838                         switch (op->r.op) {
1839                         case OP_SPECIAL_MULT:
1840                         case OP_SPECIAL_MULTU:
1841                         case OP_SPECIAL_DIV:
1842                         case OP_SPECIAL_DIVU:
1843                                 return 0;
1844                         case OP_SPECIAL_MTHI:
1845                                 if (!mflo)
1846                                         return 0;
1847                                 continue;
1848                         case OP_SPECIAL_MTLO:
1849                                 if (mflo)
1850                                         return 0;
1851                                 continue;
1852                         case OP_SPECIAL_JR:
1853                                 if (op->r.rs != 31)
1854                                         return reg;
1855
1856                                 if (!sync && !op_flag_no_ds(op->flags) &&
1857                                     (next->i.op == OP_SPECIAL) &&
1858                                     ((!mflo && next->r.op == OP_SPECIAL_MFHI) ||
1859                                     (mflo && next->r.op == OP_SPECIAL_MFLO)))
1860                                         return next->r.rd;
1861
1862                                 return 0;
1863                         case OP_SPECIAL_JALR:
1864                                 return reg;
1865                         case OP_SPECIAL_MFHI:
1866                                 if (!mflo) {
1867                                         if (another)
1868                                                 return op->r.rd;
1869                                         /* Must use REG_HI if there is another MFHI target*/
1870                                         reg2 = get_mfhi_mflo_reg(block, i + 1, next,
1871                                                          0, sync, mflo, true);
1872                                         if (reg2 > 0 && reg2 != REG_HI)
1873                                                 return REG_HI;
1874
1875                                         if (!sync && !(old_mask & BIT(op->r.rd)))
1876                                                 return op->r.rd;
1877                                         else
1878                                                 return REG_HI;
1879                                 }
1880                                 continue;
1881                         case OP_SPECIAL_MFLO:
1882                                 if (mflo) {
1883                                         if (another)
1884                                                 return op->r.rd;
1885                                         /* Must use REG_LO if there is another MFLO target*/
1886                                         reg2 = get_mfhi_mflo_reg(block, i + 1, next,
1887                                                          0, sync, mflo, true);
1888                                         if (reg2 > 0 && reg2 != REG_LO)
1889                                                 return REG_LO;
1890
1891                                         if (!sync && !(old_mask & BIT(op->r.rd)))
1892                                                 return op->r.rd;
1893                                         else
1894                                                 return REG_LO;
1895                                 }
1896                                 continue;
1897                         default:
1898                                 break;
1899                         }
1900
1901                         fallthrough;
1902                 default:
1903                         continue;
1904                 }
1905         }
1906
1907         return reg;
1908 }
1909
1910 static void lightrec_replace_lo_hi(struct block *block, u16 offset,
1911                                    u16 last, bool lo)
1912 {
1913         unsigned int i;
1914         u32 branch_offset;
1915
1916         /* This function will remove the following MFLO/MFHI. It must be called
1917          * only if get_mfhi_mflo_reg() returned a non-zero value. */
1918
1919         for (i = offset; i < last; i++) {
1920                 struct opcode *op = &block->opcode_list[i];
1921
1922                 switch (op->i.op) {
1923                 case OP_BEQ:
1924                 case OP_BNE:
1925                 case OP_BLEZ:
1926                 case OP_BGTZ:
1927                 case OP_REGIMM:
1928                         /* TODO: handle backwards branches too */
1929                         if (op_flag_local_branch(op->flags) && (s16)op->c.i.imm >= 0) {
1930                                 branch_offset = i + 1 + (s16)op->c.i.imm
1931                                         - !!op_flag_no_ds(op->flags);
1932
1933                                 lightrec_replace_lo_hi(block, branch_offset, last, lo);
1934                                 lightrec_replace_lo_hi(block, i + 1, branch_offset, lo);
1935                         }
1936                         break;
1937
1938                 case OP_SPECIAL:
1939                         if (lo && op->r.op == OP_SPECIAL_MFLO) {
1940                                 pr_debug("Removing MFLO opcode at offset 0x%x\n",
1941                                          i << 2);
1942                                 op->opcode = 0;
1943                                 return;
1944                         } else if (!lo && op->r.op == OP_SPECIAL_MFHI) {
1945                                 pr_debug("Removing MFHI opcode at offset 0x%x\n",
1946                                          i << 2);
1947                                 op->opcode = 0;
1948                                 return;
1949                         }
1950
1951                         fallthrough;
1952                 default:
1953                         break;
1954                 }
1955         }
1956 }
1957
1958 static bool lightrec_always_skip_div_check(void)
1959 {
1960 #ifdef __mips__
1961         return true;
1962 #else
1963         return false;
1964 #endif
1965 }
1966
1967 static int lightrec_flag_mults_divs(struct lightrec_state *state, struct block *block)
1968 {
1969         struct opcode *list = NULL;
1970         struct constprop_data v[32] = LIGHTREC_CONSTPROP_INITIALIZER;
1971         u8 reg_hi, reg_lo;
1972         unsigned int i;
1973
1974         for (i = 0; i < block->nb_ops - 1; i++) {
1975                 list = &block->opcode_list[i];
1976
1977                 lightrec_consts_propagate(block, i, v);
1978
1979                 switch (list->i.op) {
1980                 case OP_SPECIAL:
1981                         switch (list->r.op) {
1982                         case OP_SPECIAL_DIV:
1983                         case OP_SPECIAL_DIVU:
1984                                 /* If we are dividing by a non-zero constant, don't
1985                                  * emit the div-by-zero check. */
1986                                 if (lightrec_always_skip_div_check() ||
1987                                     (v[list->r.rt].known & v[list->r.rt].value)) {
1988                                         list->flags |= LIGHTREC_NO_DIV_CHECK;
1989                                 }
1990                                 fallthrough;
1991                         case OP_SPECIAL_MULT:
1992                         case OP_SPECIAL_MULTU:
1993                                 break;
1994                         default:
1995                                 continue;
1996                         }
1997                         fallthrough;
1998                 case OP_META_MULT2:
1999                 case OP_META_MULTU2:
2000                         break;
2001                 default:
2002                         continue;
2003                 }
2004
2005                 /* Don't support opcodes in delay slots */
2006                 if (is_delay_slot(block->opcode_list, i) ||
2007                     op_flag_no_ds(list->flags)) {
2008                         continue;
2009                 }
2010
2011                 reg_lo = get_mfhi_mflo_reg(block, i + 1, NULL, 0, false, true, false);
2012                 if (reg_lo == 0) {
2013                         pr_debug("Mark MULT(U)/DIV(U) opcode at offset 0x%x as"
2014                                  " not writing LO\n", i << 2);
2015                         list->flags |= LIGHTREC_NO_LO;
2016                 }
2017
2018                 reg_hi = get_mfhi_mflo_reg(block, i + 1, NULL, 0, false, false, false);
2019                 if (reg_hi == 0) {
2020                         pr_debug("Mark MULT(U)/DIV(U) opcode at offset 0x%x as"
2021                                  " not writing HI\n", i << 2);
2022                         list->flags |= LIGHTREC_NO_HI;
2023                 }
2024
2025                 if (!reg_lo && !reg_hi) {
2026                         pr_debug("Both LO/HI unused in this block, they will "
2027                                  "probably be used in parent block - removing "
2028                                  "flags.\n");
2029                         list->flags &= ~(LIGHTREC_NO_LO | LIGHTREC_NO_HI);
2030                 }
2031
2032                 if (reg_lo > 0 && reg_lo != REG_LO) {
2033                         pr_debug("Found register %s to hold LO (rs = %u, rt = %u)\n",
2034                                  lightrec_reg_name(reg_lo), list->r.rs, list->r.rt);
2035
2036                         lightrec_replace_lo_hi(block, i + 1, block->nb_ops, true);
2037                         list->r.rd = reg_lo;
2038                 } else {
2039                         list->r.rd = 0;
2040                 }
2041
2042                 if (reg_hi > 0 && reg_hi != REG_HI) {
2043                         pr_debug("Found register %s to hold HI (rs = %u, rt = %u)\n",
2044                                  lightrec_reg_name(reg_hi), list->r.rs, list->r.rt);
2045
2046                         lightrec_replace_lo_hi(block, i + 1, block->nb_ops, false);
2047                         list->r.imm = reg_hi;
2048                 } else {
2049                         list->r.imm = 0;
2050                 }
2051         }
2052
2053         return 0;
2054 }
2055
2056 static bool remove_div_sequence(struct block *block, unsigned int offset)
2057 {
2058         struct opcode *op;
2059         unsigned int i, found = 0;
2060
2061         /*
2062          * Scan for the zero-checking sequence that GCC automatically introduced
2063          * after most DIV/DIVU opcodes. This sequence checks the value of the
2064          * divisor, and if zero, executes a BREAK opcode, causing the BIOS
2065          * handler to crash the PS1.
2066          *
2067          * For DIV opcodes, this sequence additionally checks that the signed
2068          * operation does not overflow.
2069          *
2070          * With the assumption that the games never crashed the PS1, we can
2071          * therefore assume that the games never divided by zero or overflowed,
2072          * and these sequences can be removed.
2073          */
2074
2075         for (i = offset; i < block->nb_ops; i++) {
2076                 op = &block->opcode_list[i];
2077
2078                 if (!found) {
2079                         if (op->i.op == OP_SPECIAL &&
2080                             (op->r.op == OP_SPECIAL_DIV || op->r.op == OP_SPECIAL_DIVU))
2081                                 break;
2082
2083                         if ((op->opcode & 0xfc1fffff) == 0x14000002) {
2084                                 /* BNE ???, zero, +8 */
2085                                 found++;
2086                         } else {
2087                                 offset++;
2088                         }
2089                 } else if (found == 1 && !op->opcode) {
2090                         /* NOP */
2091                         found++;
2092                 } else if (found == 2 && op->opcode == 0x0007000d) {
2093                         /* BREAK 0x1c00 */
2094                         found++;
2095                 } else if (found == 3 && op->opcode == 0x2401ffff) {
2096                         /* LI at, -1 */
2097                         found++;
2098                 } else if (found == 4 && (op->opcode & 0xfc1fffff) == 0x14010004) {
2099                         /* BNE ???, at, +16 */
2100                         found++;
2101                 } else if (found == 5 && op->opcode == 0x3c018000) {
2102                         /* LUI at, 0x8000 */
2103                         found++;
2104                 } else if (found == 6 && (op->opcode & 0x141fffff) == 0x14010002) {
2105                         /* BNE ???, at, +16 */
2106                         found++;
2107                 } else if (found == 7 && !op->opcode) {
2108                         /* NOP */
2109                         found++;
2110                 } else if (found == 8 && op->opcode == 0x0006000d) {
2111                         /* BREAK 0x1800 */
2112                         found++;
2113                         break;
2114                 } else {
2115                         break;
2116                 }
2117         }
2118
2119         if (found >= 3) {
2120                 if (found != 9)
2121                         found = 3;
2122
2123                 pr_debug("Removing DIV%s sequence at offset 0x%x\n",
2124                          found == 9 ? "" : "U", offset << 2);
2125
2126                 for (i = 0; i < found; i++)
2127                         block->opcode_list[offset + i].opcode = 0;
2128
2129                 return true;
2130         }
2131
2132         return false;
2133 }
2134
2135 static int lightrec_remove_div_by_zero_check_sequence(struct lightrec_state *state,
2136                                                       struct block *block)
2137 {
2138         struct opcode *op;
2139         unsigned int i;
2140
2141         for (i = 0; i < block->nb_ops; i++) {
2142                 op = &block->opcode_list[i];
2143
2144                 if (op->i.op == OP_SPECIAL &&
2145                     (op->r.op == OP_SPECIAL_DIVU || op->r.op == OP_SPECIAL_DIV) &&
2146                     remove_div_sequence(block, i + 1))
2147                         op->flags |= LIGHTREC_NO_DIV_CHECK;
2148         }
2149
2150         return 0;
2151 }
2152
2153 static const u32 memset_code[] = {
2154         0x10a00006,     // beqz         a1, 2f
2155         0x24a2ffff,     // addiu        v0,a1,-1
2156         0x2403ffff,     // li           v1,-1
2157         0xac800000,     // 1: sw        zero,0(a0)
2158         0x2442ffff,     // addiu        v0,v0,-1
2159         0x1443fffd,     // bne          v0,v1, 1b
2160         0x24840004,     // addiu        a0,a0,4
2161         0x03e00008,     // 2: jr        ra
2162         0x00000000,     // nop
2163 };
2164
2165 static int lightrec_replace_memset(struct lightrec_state *state, struct block *block)
2166 {
2167         unsigned int i;
2168         union code c;
2169
2170         for (i = 0; i < block->nb_ops; i++) {
2171                 c = block->opcode_list[i].c;
2172
2173                 if (c.opcode != memset_code[i])
2174                         return 0;
2175
2176                 if (i == ARRAY_SIZE(memset_code) - 1) {
2177                         /* success! */
2178                         pr_debug("Block at PC 0x%x is a memset\n", block->pc);
2179                         block_set_flags(block,
2180                                         BLOCK_IS_MEMSET | BLOCK_NEVER_COMPILE);
2181
2182                         /* Return non-zero to skip other optimizers. */
2183                         return 1;
2184                 }
2185         }
2186
2187         return 0;
2188 }
2189
2190 static int lightrec_test_preload_pc(struct lightrec_state *state, struct block *block)
2191 {
2192         unsigned int i;
2193         union code c;
2194         u32 flags;
2195
2196         for (i = 0; i < block->nb_ops; i++) {
2197                 c = block->opcode_list[i].c;
2198                 flags = block->opcode_list[i].flags;
2199
2200                 if (op_flag_sync(flags))
2201                         break;
2202
2203                 switch (c.i.op) {
2204                 case OP_J:
2205                 case OP_JAL:
2206                         block->flags |= BLOCK_PRELOAD_PC;
2207                         return 0;
2208
2209                 case OP_REGIMM:
2210                         switch (c.r.rt) {
2211                         case OP_REGIMM_BLTZAL:
2212                         case OP_REGIMM_BGEZAL:
2213                                 block->flags |= BLOCK_PRELOAD_PC;
2214                                 return 0;
2215                         default:
2216                                 break;
2217                         }
2218                         fallthrough;
2219                 case OP_BEQ:
2220                 case OP_BNE:
2221                 case OP_BLEZ:
2222                 case OP_BGTZ:
2223                         if (!op_flag_local_branch(flags)) {
2224                                 block->flags |= BLOCK_PRELOAD_PC;
2225                                 return 0;
2226                         }
2227
2228                 case OP_SPECIAL:
2229                         switch (c.r.op) {
2230                         case OP_SPECIAL_JALR:
2231                                 if (c.r.rd) {
2232                                         block->flags |= BLOCK_PRELOAD_PC;
2233                                         return 0;
2234                                 }
2235                                 break;
2236                         case OP_SPECIAL_SYSCALL:
2237                         case OP_SPECIAL_BREAK:
2238                                 block->flags |= BLOCK_PRELOAD_PC;
2239                                 return 0;
2240                         default:
2241                                 break;
2242                         }
2243                         break;
2244                 }
2245         }
2246
2247         return 0;
2248 }
2249
2250 static int (*lightrec_optimizers[])(struct lightrec_state *state, struct block *) = {
2251         IF_OPT(OPT_REMOVE_DIV_BY_ZERO_SEQ, &lightrec_remove_div_by_zero_check_sequence),
2252         IF_OPT(OPT_REPLACE_MEMSET, &lightrec_replace_memset),
2253         IF_OPT(OPT_DETECT_IMPOSSIBLE_BRANCHES, &lightrec_detect_impossible_branches),
2254         IF_OPT(OPT_HANDLE_LOAD_DELAYS, &lightrec_handle_load_delays),
2255         IF_OPT(OPT_HANDLE_LOAD_DELAYS, &lightrec_swap_load_delays),
2256         IF_OPT(OPT_TRANSFORM_OPS, &lightrec_transform_branches),
2257         IF_OPT(OPT_LOCAL_BRANCHES, &lightrec_local_branches),
2258         IF_OPT(OPT_TRANSFORM_OPS, &lightrec_transform_ops),
2259         IF_OPT(OPT_SWITCH_DELAY_SLOTS, &lightrec_switch_delay_slots),
2260         IF_OPT(OPT_FLAG_IO, &lightrec_flag_io),
2261         IF_OPT(OPT_FLAG_MULT_DIV, &lightrec_flag_mults_divs),
2262         IF_OPT(OPT_EARLY_UNLOAD, &lightrec_early_unload),
2263         IF_OPT(OPT_PRELOAD_PC, &lightrec_test_preload_pc),
2264 };
2265
2266 int lightrec_optimize(struct lightrec_state *state, struct block *block)
2267 {
2268         unsigned int i;
2269         int ret;
2270
2271         for (i = 0; i < ARRAY_SIZE(lightrec_optimizers); i++) {
2272                 if (lightrec_optimizers[i]) {
2273                         ret = (*lightrec_optimizers[i])(state, block);
2274                         if (ret)
2275                                 return ret;
2276                 }
2277         }
2278
2279         return 0;
2280 }