drc: fix a silly mistake of overwriting a reg
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef HAVE_LIBNX
33 #include <switch.h>
34 static Jit g_jit;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42 #include "arm_features.h"
43
44 #define unused __attribute__((unused))
45 #ifdef __clang__
46 #define noinline __attribute__((noinline))
47 #else
48 #define noinline __attribute__((noinline,noclone))
49 #endif
50 #ifndef ARRAY_SIZE
51 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
52 #endif
53 #ifndef min
54 #define min(a, b) ((b) < (a) ? (b) : (a))
55 #endif
56 #ifndef max
57 #define max(a, b) ((b) > (a) ? (b) : (a))
58 #endif
59
60 //#define DISASM
61 //#define ASSEM_PRINT
62 //#define INV_DEBUG_W
63 //#define STAT_PRINT
64
65 #ifdef ASSEM_PRINT
66 #define assem_debug printf
67 #else
68 #define assem_debug(...)
69 #endif
70 //#define inv_debug printf
71 #define inv_debug(...)
72
73 #ifdef __i386__
74 #include "assem_x86.h"
75 #endif
76 #ifdef __x86_64__
77 #include "assem_x64.h"
78 #endif
79 #ifdef __arm__
80 #include "assem_arm.h"
81 #endif
82 #ifdef __aarch64__
83 #include "assem_arm64.h"
84 #endif
85
86 #define RAM_SIZE 0x200000
87 #define MAXBLOCK 4096
88 #define MAX_OUTPUT_BLOCK_SIZE 262144
89 #define EXPIRITY_OFFSET (MAX_OUTPUT_BLOCK_SIZE * 2)
90 #define PAGE_COUNT 1024
91
92 #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
93 #define INVALIDATE_USE_COND_CALL
94 #endif
95
96 #ifdef VITA
97 // apparently Vita has a 16MB limit, so either we cut tc in half,
98 // or use this hack (it's a hack because tc size was designed to be power-of-2)
99 #define TC_REDUCE_BYTES 4096
100 #else
101 #define TC_REDUCE_BYTES 0
102 #endif
103
104 struct ndrc_tramp
105 {
106   struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
107   const void *f[2048 / sizeof(void *)];
108 };
109
110 struct ndrc_mem
111 {
112   u_char translation_cache[(1 << TARGET_SIZE_2) - TC_REDUCE_BYTES];
113   struct ndrc_tramp tramp;
114 };
115
116 #ifdef BASE_ADDR_DYNAMIC
117 static struct ndrc_mem *ndrc;
118 #else
119 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
120 static struct ndrc_mem *ndrc = &ndrc_;
121 #endif
122 #ifdef TC_WRITE_OFFSET
123 # ifdef __GLIBC__
124 # include <sys/types.h>
125 # include <sys/stat.h>
126 # include <fcntl.h>
127 # include <unistd.h>
128 # endif
129 static long ndrc_write_ofs;
130 #define NDRC_WRITE_OFFSET(x) (void *)((char *)(x) + ndrc_write_ofs)
131 #else
132 #define NDRC_WRITE_OFFSET(x) (x)
133 #endif
134
135 // stubs
136 enum stub_type {
137   CC_STUB = 1,
138   FP_STUB = 2,
139   LOADB_STUB = 3,
140   LOADH_STUB = 4,
141   LOADW_STUB = 5,
142   LOADD_STUB = 6,
143   LOADBU_STUB = 7,
144   LOADHU_STUB = 8,
145   STOREB_STUB = 9,
146   STOREH_STUB = 10,
147   STOREW_STUB = 11,
148   STORED_STUB = 12,
149   STORELR_STUB = 13,
150   INVCODE_STUB = 14,
151 };
152
153 // regmap_pre[i]    - regs before [i] insn starts; dirty things here that
154 //                    don't match .regmap will be written back
155 // [i].regmap_entry - regs that must be set up if someone jumps here
156 // [i].regmap       - regs [i] insn will read/(over)write
157 // branch_regs[i].* - same as above but for branches, takes delay slot into account
158 struct regstat
159 {
160   signed char regmap_entry[HOST_REGS];
161   signed char regmap[HOST_REGS];
162   uint64_t wasdirty;
163   uint64_t dirty;
164   uint64_t u;
165   u_int wasconst;                // before; for example 'lw r2, (r2)' wasconst is true
166   u_int isconst;                 //  ... but isconst is false when r2 is known
167   u_int loadedconst;             // host regs that have constants loaded
168   //u_int waswritten;              // MIPS regs that were used as store base before
169 };
170
171 struct ht_entry
172 {
173   u_int vaddr[2];
174   void *tcaddr[2];
175 };
176
177 struct code_stub
178 {
179   enum stub_type type;
180   void *addr;
181   void *retaddr;
182   u_int a;
183   uintptr_t b;
184   uintptr_t c;
185   u_int d;
186   u_int e;
187 };
188
189 struct link_entry
190 {
191   void *addr;
192   u_int target;
193   u_int internal;
194 };
195
196 struct block_info
197 {
198   struct block_info *next;
199   const void *source;
200   const void *copy;
201   u_int start; // vaddr of the block start
202   u_int len;   // of the whole block source
203   u_int tc_offs;
204   //u_int tc_len;
205   u_int reg_sv_flags;
206   u_char is_dirty;
207   u_char inv_near_misses;
208   u_short jump_in_cnt;
209   struct {
210     u_int vaddr;
211     void *addr;
212   } jump_in[0];
213 };
214
215 struct jump_info
216 {
217   int alloc;
218   int count;
219   struct {
220     u_int target_vaddr;
221     void *stub;
222   } e[0];
223 };
224
225 static struct decoded_insn
226 {
227   u_char itype;
228   u_char opcode;
229   u_char opcode2;
230   u_char rs1;
231   u_char rs2;
232   u_char rt1;
233   u_char rt2;
234   u_char use_lt1:1;
235   u_char bt:1;
236   u_char ooo:1;
237   u_char is_ds:1;
238   u_char is_jump:1;
239   u_char is_ujump:1;
240   u_char is_load:1;
241   u_char is_store:1;
242 } dops[MAXBLOCK];
243
244   static u_char *out;
245   static struct ht_entry hash_table[65536];
246   static struct block_info *blocks[PAGE_COUNT];
247   static struct jump_info *jumps[PAGE_COUNT];
248   static u_int start;
249   static u_int *source;
250   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
251   static uint64_t gte_rt[MAXBLOCK];
252   static uint64_t gte_unneeded[MAXBLOCK];
253   static u_int smrv[32]; // speculated MIPS register values
254   static u_int smrv_strong; // mask or regs that are likely to have correct values
255   static u_int smrv_weak; // same, but somewhat less likely
256   static u_int smrv_strong_next; // same, but after current insn executes
257   static u_int smrv_weak_next;
258   static int imm[MAXBLOCK];
259   static u_int ba[MAXBLOCK];
260   static uint64_t unneeded_reg[MAXBLOCK];
261   static uint64_t branch_unneeded_reg[MAXBLOCK];
262   // see 'struct regstat' for a description
263   static signed char regmap_pre[MAXBLOCK][HOST_REGS];
264   // contains 'real' consts at [i] insn, but may differ from what's actually
265   // loaded in host reg as 'final' value is always loaded, see get_final_value()
266   static uint32_t current_constmap[HOST_REGS];
267   static uint32_t constmap[MAXBLOCK][HOST_REGS];
268   static struct regstat regs[MAXBLOCK];
269   static struct regstat branch_regs[MAXBLOCK];
270   static signed char minimum_free_regs[MAXBLOCK];
271   static int ccadj[MAXBLOCK];
272   static int slen;
273   static void *instr_addr[MAXBLOCK];
274   static struct link_entry link_addr[MAXBLOCK];
275   static int linkcount;
276   static struct code_stub stubs[MAXBLOCK*3];
277   static int stubcount;
278   static u_int literals[1024][2];
279   static int literalcount;
280   static int is_delayslot;
281   static char shadow[1048576]  __attribute__((aligned(16)));
282   static void *copy;
283   static u_int expirep;
284   static u_int stop_after_jal;
285   static u_int f1_hack;
286 #ifdef STAT_PRINT
287   static int stat_bc_direct;
288   static int stat_bc_pre;
289   static int stat_bc_restore;
290   static int stat_ht_lookups;
291   static int stat_jump_in_lookups;
292   static int stat_restore_tries;
293   static int stat_restore_compares;
294   static int stat_inv_addr_calls;
295   static int stat_inv_hits;
296   static int stat_blocks;
297   static int stat_links;
298   #define stat_inc(s) s++
299   #define stat_dec(s) s--
300   #define stat_clear(s) s = 0
301 #else
302   #define stat_inc(s)
303   #define stat_dec(s)
304   #define stat_clear(s)
305 #endif
306
307   int new_dynarec_hacks;
308   int new_dynarec_hacks_pergame;
309   int new_dynarec_hacks_old;
310   int new_dynarec_did_compile;
311
312   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
313
314   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
315   extern int last_count;  // last absolute target, often = next_interupt
316   extern int pcaddr;
317   extern int pending_exception;
318   extern int branch_target;
319   extern uintptr_t ram_offset;
320   extern uintptr_t mini_ht[32][2];
321
322   /* registers that may be allocated */
323   /* 1-31 gpr */
324 #define LOREG 32 // lo
325 #define HIREG 33 // hi
326 //#define FSREG 34 // FPU status (FCSR)
327 #define CSREG 35 // Coprocessor status
328 #define CCREG 36 // Cycle count
329 #define INVCP 37 // Pointer to invalid_code
330 //#define MMREG 38 // Pointer to memory_map
331 #define ROREG 39 // ram offset (if rdram!=0x80000000)
332 #define TEMPREG 40
333 #define FTEMP 40 // FPU temporary register
334 #define PTEMP 41 // Prefetch temporary register
335 //#define TLREG 42 // TLB mapping offset
336 #define RHASH 43 // Return address hash
337 #define RHTBL 44 // Return address hash table address
338 #define RTEMP 45 // JR/JALR address register
339 #define MAXREG 45
340 #define AGEN1 46 // Address generation temporary register
341 //#define AGEN2 47 // Address generation temporary register
342 //#define MGEN1 48 // Maptable address generation temporary register
343 //#define MGEN2 49 // Maptable address generation temporary register
344 #define BTREG 50 // Branch target temporary register
345
346   /* instruction types */
347 #define NOP 0     // No operation
348 #define LOAD 1    // Load
349 #define STORE 2   // Store
350 #define LOADLR 3  // Unaligned load
351 #define STORELR 4 // Unaligned store
352 #define MOV 5     // Move
353 #define ALU 6     // Arithmetic/logic
354 #define MULTDIV 7 // Multiply/divide
355 #define SHIFT 8   // Shift by register
356 #define SHIFTIMM 9// Shift by immediate
357 #define IMM16 10  // 16-bit immediate
358 #define RJUMP 11  // Unconditional jump to register
359 #define UJUMP 12  // Unconditional jump
360 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
361 #define SJUMP 14  // Conditional branch (regimm format)
362 #define COP0 15   // Coprocessor 0
363 #define COP1 16   // Coprocessor 1
364 #define C1LS 17   // Coprocessor 1 load/store
365 //#define FJUMP 18  // Conditional branch (floating point)
366 //#define FLOAT 19  // Floating point unit
367 //#define FCONV 20  // Convert integer to float
368 //#define FCOMP 21  // Floating point compare (sets FSREG)
369 #define SYSCALL 22// SYSCALL,BREAK
370 #define OTHER 23  // Other
371 //#define SPAN 24   // Branch/delay slot spans 2 pages
372 #define NI 25     // Not implemented
373 #define HLECALL 26// PCSX fake opcodes for HLE
374 #define COP2 27   // Coprocessor 2 move
375 #define C2LS 28   // Coprocessor 2 load/store
376 #define C2OP 29   // Coprocessor 2 operation
377 #define INTCALL 30// Call interpreter to handle rare corner cases
378
379   /* branch codes */
380 #define TAKEN 1
381 #define NOTTAKEN 2
382 #define NULLDS 3
383
384 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
385 #define DJT_2 (void *)2l
386
387 // asm linkage
388 void dyna_linker();
389 void cc_interrupt();
390 void fp_exception();
391 void fp_exception_ds();
392 void jump_syscall   (u_int u0, u_int u1, u_int pc);
393 void jump_syscall_ds(u_int u0, u_int u1, u_int pc);
394 void jump_break   (u_int u0, u_int u1, u_int pc);
395 void jump_break_ds(u_int u0, u_int u1, u_int pc);
396 void jump_to_new_pc();
397 void call_gteStall();
398 void new_dyna_leave();
399
400 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile);
401 void *ndrc_get_addr_ht(u_int vaddr);
402 void ndrc_add_jump_out(u_int vaddr, void *src);
403 void ndrc_write_invalidate_one(u_int addr);
404 static void ndrc_write_invalidate_many(u_int addr, u_int end);
405
406 static int new_recompile_block(u_int addr);
407 static void invalidate_block(struct block_info *block);
408
409 // Needed by assembler
410 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty);
411 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty);
412 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr);
413 static void load_all_regs(const signed char i_regmap[]);
414 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[]);
415 static void load_regs_entry(int t);
416 static void load_all_consts(const signed char regmap[], u_int dirty, int i);
417 static u_int get_host_reglist(const signed char *regmap);
418
419 static int get_final_value(int hr, int i, int *value);
420 static void add_stub(enum stub_type type, void *addr, void *retaddr,
421   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
422 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
423   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
424 static void add_to_linker(void *addr, u_int target, int ext);
425 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
426   int addr, int *offset_reg, int *addr_reg_override);
427 static void *get_direct_memhandler(void *table, u_int addr,
428   enum stub_type type, uintptr_t *addr_host);
429 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
430 static void pass_args(int a0, int a1);
431 static void emit_far_jump(const void *f);
432 static void emit_far_call(const void *f);
433
434 #ifdef VITA
435 #include <psp2/kernel/sysmem.h>
436 static int sceBlock;
437 // note: this interacts with RetroArch's Vita bootstrap code: bootstrap/vita/sbrk.c
438 extern int getVMBlock();
439 int _newlib_vm_size_user = sizeof(*ndrc);
440 #endif
441
442 static void mprotect_w_x(void *start, void *end, int is_x)
443 {
444 #ifdef NO_WRITE_EXEC
445   #if defined(VITA)
446   // *Open* enables write on all memory that was
447   // allocated by sceKernelAllocMemBlockForVM()?
448   if (is_x)
449     sceKernelCloseVMDomain();
450   else
451     sceKernelOpenVMDomain();
452   #elif defined(HAVE_LIBNX)
453   Result rc;
454   // check to avoid the full flush in jitTransitionToExecutable()
455   if (g_jit.type != JitType_CodeMemory) {
456     if (is_x)
457       rc = jitTransitionToExecutable(&g_jit);
458     else
459       rc = jitTransitionToWritable(&g_jit);
460     if (R_FAILED(rc))
461       ;//SysPrintf("jitTransition %d %08x\n", is_x, rc);
462   }
463   #elif defined(TC_WRITE_OFFSET)
464   // separated rx and rw areas are always available
465   #else
466   u_long mstart = (u_long)start & ~4095ul;
467   u_long mend = (u_long)end;
468   if (mprotect((void *)mstart, mend - mstart,
469                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
470     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
471   #endif
472 #endif
473 }
474
475 static void start_tcache_write(void *start, void *end)
476 {
477   mprotect_w_x(start, end, 0);
478 }
479
480 static void end_tcache_write(void *start, void *end)
481 {
482 #if defined(__arm__) || defined(__aarch64__)
483   size_t len = (char *)end - (char *)start;
484   #if   defined(__BLACKBERRY_QNX__)
485   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
486   #elif defined(__MACH__)
487   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
488   #elif defined(VITA)
489   sceKernelSyncVMDomain(sceBlock, start, len);
490   #elif defined(_3DS)
491   ctr_flush_invalidate_cache();
492   #elif defined(HAVE_LIBNX)
493   if (g_jit.type == JitType_CodeMemory) {
494     armDCacheClean(start, len);
495     armICacheInvalidate((char *)start - ndrc_write_ofs, len);
496     // as of v4.2.1 libnx lacks isb
497     __asm__ volatile("isb" ::: "memory");
498   }
499   #elif defined(__aarch64__)
500   // as of 2021, __clear_cache() is still broken on arm64
501   // so here is a custom one :(
502   clear_cache_arm64(start, end);
503   #else
504   __clear_cache(start, end);
505   #endif
506   (void)len;
507 #endif
508
509   mprotect_w_x(start, end, 1);
510 }
511
512 static void *start_block(void)
513 {
514   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
515   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
516     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
517   start_tcache_write(NDRC_WRITE_OFFSET(out), NDRC_WRITE_OFFSET(end));
518   return out;
519 }
520
521 static void end_block(void *start)
522 {
523   end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(out));
524 }
525
526 #ifdef NDRC_CACHE_FLUSH_ALL
527
528 static int needs_clear_cache;
529
530 static void mark_clear_cache(void *target)
531 {
532   if (!needs_clear_cache) {
533     start_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
534     needs_clear_cache = 1;
535   }
536 }
537
538 static void do_clear_cache(void)
539 {
540   if (needs_clear_cache) {
541     end_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
542     needs_clear_cache = 0;
543   }
544 }
545
546 #else
547
548 // also takes care of w^x mappings when patching code
549 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
550
551 static void mark_clear_cache(void *target)
552 {
553   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
554   u_int mask = 1u << ((offset >> 12) & 31);
555   if (!(needs_clear_cache[offset >> 17] & mask)) {
556     char *start = (char *)NDRC_WRITE_OFFSET((uintptr_t)target & ~4095l);
557     start_tcache_write(start, start + 4095);
558     needs_clear_cache[offset >> 17] |= mask;
559   }
560 }
561
562 // Clearing the cache is rather slow on ARM Linux, so mark the areas
563 // that need to be cleared, and then only clear these areas once.
564 static void do_clear_cache(void)
565 {
566   int i, j;
567   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
568   {
569     u_int bitmap = needs_clear_cache[i];
570     if (!bitmap)
571       continue;
572     for (j = 0; j < 32; j++)
573     {
574       u_char *start, *end;
575       if (!(bitmap & (1u << j)))
576         continue;
577
578       start = ndrc->translation_cache + i*131072 + j*4096;
579       end = start + 4095;
580       for (j++; j < 32; j++) {
581         if (!(bitmap & (1u << j)))
582           break;
583         end += 4096;
584       }
585       end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(end));
586     }
587     needs_clear_cache[i] = 0;
588   }
589 }
590
591 #endif // NDRC_CACHE_FLUSH_ALL
592
593 #define NO_CYCLE_PENALTY_THR 12
594
595 int cycle_multiplier = CYCLE_MULT_DEFAULT; // 100 for 1.0
596 int cycle_multiplier_override;
597 int cycle_multiplier_old;
598 static int cycle_multiplier_active;
599
600 static int CLOCK_ADJUST(int x)
601 {
602   int m = cycle_multiplier_active;
603   int s = (x >> 31) | 1;
604   return (x * m + s * 50) / 100;
605 }
606
607 static int ds_writes_rjump_rs(int i)
608 {
609   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
610 }
611
612 // psx addr mirror masking (for invalidation)
613 static u_int pmmask(u_int vaddr)
614 {
615   vaddr &= ~0xe0000000;
616   if (vaddr < 0x01000000)
617     vaddr &= ~0x00e00000; // RAM mirrors
618   return vaddr;
619 }
620
621 static u_int get_page(u_int vaddr)
622 {
623   u_int page = pmmask(vaddr) >> 12;
624   if (page >= PAGE_COUNT / 2)
625     page = PAGE_COUNT / 2 + (page & (PAGE_COUNT / 2 - 1));
626   return page;
627 }
628
629 // get a page for looking for a block that has vaddr
630 // (needed because the block may start in previous page)
631 static u_int get_page_prev(u_int vaddr)
632 {
633   assert(MAXBLOCK <= (1 << 12));
634   u_int page = get_page(vaddr);
635   if (page & 511)
636     page--;
637   return page;
638 }
639
640 static struct ht_entry *hash_table_get(u_int vaddr)
641 {
642   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
643 }
644
645 static void hash_table_add(u_int vaddr, void *tcaddr)
646 {
647   struct ht_entry *ht_bin = hash_table_get(vaddr);
648   assert(tcaddr);
649   ht_bin->vaddr[1] = ht_bin->vaddr[0];
650   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
651   ht_bin->vaddr[0] = vaddr;
652   ht_bin->tcaddr[0] = tcaddr;
653 }
654
655 static void hash_table_remove(int vaddr)
656 {
657   //printf("remove hash: %x\n",vaddr);
658   struct ht_entry *ht_bin = hash_table_get(vaddr);
659   if (ht_bin->vaddr[1] == vaddr) {
660     ht_bin->vaddr[1] = -1;
661     ht_bin->tcaddr[1] = NULL;
662   }
663   if (ht_bin->vaddr[0] == vaddr) {
664     ht_bin->vaddr[0] = ht_bin->vaddr[1];
665     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
666     ht_bin->vaddr[1] = -1;
667     ht_bin->tcaddr[1] = NULL;
668   }
669 }
670
671 static void mark_invalid_code(u_int vaddr, u_int len, char invalid)
672 {
673   u_int vaddr_m = vaddr & 0x1fffffff;
674   u_int i, j;
675   for (i = vaddr_m & ~0xfff; i < vaddr_m + len; i += 0x1000) {
676     // ram mirrors, but should not hurt bios
677     for (j = 0; j < 0x800000; j += 0x200000) {
678       invalid_code[(i|j) >> 12] =
679       invalid_code[(i|j|0x80000000u) >> 12] =
680       invalid_code[(i|j|0xa0000000u) >> 12] = invalid;
681     }
682   }
683   if (!invalid && vaddr + len > inv_code_start && vaddr <= inv_code_end)
684     inv_code_start = inv_code_end = ~0;
685 }
686
687 static int doesnt_expire_soon(u_char *tcaddr)
688 {
689   u_int diff = (u_int)(tcaddr - out) & ((1u << TARGET_SIZE_2) - 1u);
690   return diff > EXPIRITY_OFFSET + MAX_OUTPUT_BLOCK_SIZE;
691 }
692
693 static unused void check_for_block_changes(u_int start, u_int end)
694 {
695   u_int start_page = get_page_prev(start);
696   u_int end_page = get_page(end - 1);
697   u_int page;
698
699   for (page = start_page; page <= end_page; page++) {
700     struct block_info *block;
701     for (block = blocks[page]; block != NULL; block = block->next) {
702       if (block->is_dirty)
703         continue;
704       if (memcmp(block->source, block->copy, block->len)) {
705         printf("bad block %08x-%08x %016llx %016llx @%08x\n",
706           block->start, block->start + block->len,
707           *(long long *)block->source, *(long long *)block->copy, psxRegs.pc);
708         fflush(stdout);
709         abort();
710       }
711     }
712   }
713 }
714
715 static void *try_restore_block(u_int vaddr, u_int start_page, u_int end_page)
716 {
717   void *found_clean = NULL;
718   u_int i, page;
719
720   stat_inc(stat_restore_tries);
721   for (page = start_page; page <= end_page; page++) {
722     struct block_info *block;
723     for (block = blocks[page]; block != NULL; block = block->next) {
724       if (vaddr < block->start)
725         break;
726       if (!block->is_dirty || vaddr >= block->start + block->len)
727         continue;
728       for (i = 0; i < block->jump_in_cnt; i++)
729         if (block->jump_in[i].vaddr == vaddr)
730           break;
731       if (i == block->jump_in_cnt)
732         continue;
733       assert(block->source && block->copy);
734       stat_inc(stat_restore_compares);
735       if (memcmp(block->source, block->copy, block->len))
736         continue;
737
738       block->is_dirty = block->inv_near_misses = 0;
739       found_clean = block->jump_in[i].addr;
740       hash_table_add(vaddr, found_clean);
741       mark_invalid_code(block->start, block->len, 0);
742       stat_inc(stat_bc_restore);
743       inv_debug("INV: restored %08x %p (%d)\n", vaddr, found_clean, block->jump_in_cnt);
744       return found_clean;
745     }
746   }
747   return NULL;
748 }
749
750 // Get address from virtual address
751 // This is called from the recompiled JR/JALR instructions
752 static void noinline *get_addr(u_int vaddr, int can_compile)
753 {
754   u_int start_page = get_page_prev(vaddr);
755   u_int i, page, end_page = get_page(vaddr);
756   void *found_clean = NULL;
757
758   stat_inc(stat_jump_in_lookups);
759   for (page = start_page; page <= end_page; page++) {
760     const struct block_info *block;
761     for (block = blocks[page]; block != NULL; block = block->next) {
762       if (vaddr < block->start)
763         break;
764       if (block->is_dirty || vaddr >= block->start + block->len)
765         continue;
766       for (i = 0; i < block->jump_in_cnt; i++)
767         if (block->jump_in[i].vaddr == vaddr)
768           break;
769       if (i == block->jump_in_cnt)
770         continue;
771       found_clean = block->jump_in[i].addr;
772       hash_table_add(vaddr, found_clean);
773       return found_clean;
774     }
775   }
776   found_clean = try_restore_block(vaddr, start_page, end_page);
777   if (found_clean)
778     return found_clean;
779
780   if (!can_compile)
781     return NULL;
782
783   int r = new_recompile_block(vaddr);
784   if (r == 0)
785     return ndrc_get_addr_ht(vaddr);
786
787   // generate an address error
788   Status|=2;
789   Cause=(vaddr<<31)|(4<<2);
790   EPC=(vaddr&1)?vaddr-5:vaddr;
791   BadVAddr=(vaddr&~1);
792   return ndrc_get_addr_ht(0x80000080);
793 }
794
795 // Look up address in hash table first
796 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile)
797 {
798   //check_for_block_changes(vaddr, vaddr + MAXBLOCK);
799   const struct ht_entry *ht_bin = hash_table_get(vaddr);
800   stat_inc(stat_ht_lookups);
801   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
802   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
803   return get_addr(vaddr, can_compile);
804 }
805
806 void *ndrc_get_addr_ht(u_int vaddr)
807 {
808   return ndrc_get_addr_ht_param(vaddr, 1);
809 }
810
811 static void clear_all_regs(signed char regmap[])
812 {
813   memset(regmap, -1, sizeof(regmap[0]) * HOST_REGS);
814 }
815
816 // get_reg: get allocated host reg from mips reg
817 // returns -1 if no such mips reg was allocated
818 #if defined(__arm__) && defined(HAVE_ARMV6) && HOST_REGS == 13 && EXCLUDE_REG == 11
819
820 extern signed char get_reg(const signed char regmap[], signed char r);
821
822 #else
823
824 static signed char get_reg(const signed char regmap[], signed char r)
825 {
826   int hr;
827   for (hr = 0; hr < HOST_REGS; hr++) {
828     if (hr == EXCLUDE_REG)
829       continue;
830     if (regmap[hr] == r)
831       return hr;
832   }
833   return -1;
834 }
835
836 #endif
837
838 // get reg as mask bit (1 << hr)
839 static u_int get_regm(const signed char regmap[], signed char r)
840 {
841   return (1u << (get_reg(regmap, r) & 31)) & ~(1u << 31);
842 }
843
844 static signed char get_reg_temp(const signed char regmap[])
845 {
846   int hr;
847   for (hr = 0; hr < HOST_REGS; hr++) {
848     if (hr == EXCLUDE_REG)
849       continue;
850     if (regmap[hr] == (signed char)-1)
851       return hr;
852   }
853   return -1;
854 }
855
856 // Find a register that is available for two consecutive cycles
857 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
858 {
859   int hr;
860   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
861   return -1;
862 }
863
864 // reverse reg map: mips -> host
865 #define RRMAP_SIZE 64
866 static void make_rregs(const signed char regmap[], signed char rrmap[RRMAP_SIZE],
867   u_int *regs_can_change)
868 {
869   u_int r, hr, hr_can_change = 0;
870   memset(rrmap, -1, RRMAP_SIZE);
871   for (hr = 0; hr < HOST_REGS; )
872   {
873     r = regmap[hr];
874     rrmap[r & (RRMAP_SIZE - 1)] = hr;
875     // only add mips $1-$31+$lo, others shifted out
876     hr_can_change |= (uint64_t)1 << (hr + ((r - 1) & 32));
877     hr++;
878     if (hr == EXCLUDE_REG)
879       hr++;
880   }
881   hr_can_change |= 1u << (rrmap[33] & 31);
882   hr_can_change |= 1u << (rrmap[CCREG] & 31);
883   hr_can_change &= ~(1u << 31);
884   *regs_can_change = hr_can_change;
885 }
886
887 // same as get_reg, but takes rrmap
888 static signed char get_rreg(signed char rrmap[RRMAP_SIZE], signed char r)
889 {
890   assert(0 <= r && r < RRMAP_SIZE);
891   return rrmap[r];
892 }
893
894 static int count_free_regs(const signed char regmap[])
895 {
896   int count=0;
897   int hr;
898   for(hr=0;hr<HOST_REGS;hr++)
899   {
900     if(hr!=EXCLUDE_REG) {
901       if(regmap[hr]<0) count++;
902     }
903   }
904   return count;
905 }
906
907 static void dirty_reg(struct regstat *cur, signed char reg)
908 {
909   int hr;
910   if (!reg) return;
911   hr = get_reg(cur->regmap, reg);
912   if (hr >= 0)
913     cur->dirty |= 1<<hr;
914 }
915
916 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
917 {
918   int hr;
919   if (!reg) return;
920   hr = get_reg(cur->regmap, reg);
921   if (hr >= 0) {
922     cur->isconst |= 1<<hr;
923     current_constmap[hr] = value;
924   }
925 }
926
927 static void clear_const(struct regstat *cur, signed char reg)
928 {
929   int hr;
930   if (!reg) return;
931   hr = get_reg(cur->regmap, reg);
932   if (hr >= 0)
933     cur->isconst &= ~(1<<hr);
934 }
935
936 static int is_const(const struct regstat *cur, signed char reg)
937 {
938   int hr;
939   if (reg < 0) return 0;
940   if (!reg) return 1;
941   hr = get_reg(cur->regmap, reg);
942   if (hr >= 0)
943     return (cur->isconst>>hr)&1;
944   return 0;
945 }
946
947 static uint32_t get_const(const struct regstat *cur, signed char reg)
948 {
949   int hr;
950   if (!reg) return 0;
951   hr = get_reg(cur->regmap, reg);
952   if (hr >= 0)
953     return current_constmap[hr];
954
955   SysPrintf("Unknown constant in r%d\n", reg);
956   abort();
957 }
958
959 // Least soon needed registers
960 // Look at the next ten instructions and see which registers
961 // will be used.  Try not to reallocate these.
962 static void lsn(u_char hsn[], int i, int *preferred_reg)
963 {
964   int j;
965   int b=-1;
966   for(j=0;j<9;j++)
967   {
968     if(i+j>=slen) {
969       j=slen-i-1;
970       break;
971     }
972     if (dops[i+j].is_ujump)
973     {
974       // Don't go past an unconditonal jump
975       j++;
976       break;
977     }
978   }
979   for(;j>=0;j--)
980   {
981     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
982     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
983     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
984     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
985     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
986       // Stores can allocate zero
987       hsn[dops[i+j].rs1]=j;
988       hsn[dops[i+j].rs2]=j;
989     }
990     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
991       hsn[ROREG] = j;
992     // On some architectures stores need invc_ptr
993     #if defined(HOST_IMM8)
994     if (dops[i+j].is_store)
995       hsn[INVCP] = j;
996     #endif
997     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
998     {
999       hsn[CCREG]=j;
1000       b=j;
1001     }
1002   }
1003   if(b>=0)
1004   {
1005     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
1006     {
1007       // Follow first branch
1008       int t=(ba[i+b]-start)>>2;
1009       j=7-b;if(t+j>=slen) j=slen-t-1;
1010       for(;j>=0;j--)
1011       {
1012         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
1013         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
1014         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
1015         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
1016       }
1017     }
1018     // TODO: preferred register based on backward branch
1019   }
1020   // Delay slot should preferably not overwrite branch conditions or cycle count
1021   if (i > 0 && dops[i-1].is_jump) {
1022     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
1023     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
1024     hsn[CCREG]=1;
1025     // ...or hash tables
1026     hsn[RHASH]=1;
1027     hsn[RHTBL]=1;
1028   }
1029   // Coprocessor load/store needs FTEMP, even if not declared
1030   if(dops[i].itype==C2LS) {
1031     hsn[FTEMP]=0;
1032   }
1033   // Load L/R also uses FTEMP as a temporary register
1034   if(dops[i].itype==LOADLR) {
1035     hsn[FTEMP]=0;
1036   }
1037   // Also SWL/SWR/SDL/SDR
1038   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
1039     hsn[FTEMP]=0;
1040   }
1041   // Don't remove the miniht registers
1042   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
1043   {
1044     hsn[RHASH]=0;
1045     hsn[RHTBL]=0;
1046   }
1047 }
1048
1049 // We only want to allocate registers if we're going to use them again soon
1050 static int needed_again(int r, int i)
1051 {
1052   int j;
1053   int b=-1;
1054   int rn=10;
1055
1056   if (i > 0 && dops[i-1].is_ujump)
1057   {
1058     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
1059       return 0; // Don't need any registers if exiting the block
1060   }
1061   for(j=0;j<9;j++)
1062   {
1063     if(i+j>=slen) {
1064       j=slen-i-1;
1065       break;
1066     }
1067     if (dops[i+j].is_ujump)
1068     {
1069       // Don't go past an unconditonal jump
1070       j++;
1071       break;
1072     }
1073     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
1074     {
1075       break;
1076     }
1077   }
1078   for(;j>=1;j--)
1079   {
1080     if(dops[i+j].rs1==r) rn=j;
1081     if(dops[i+j].rs2==r) rn=j;
1082     if((unneeded_reg[i+j]>>r)&1) rn=10;
1083     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
1084     {
1085       b=j;
1086     }
1087   }
1088   if(rn<10) return 1;
1089   (void)b;
1090   return 0;
1091 }
1092
1093 // Try to match register allocations at the end of a loop with those
1094 // at the beginning
1095 static int loop_reg(int i, int r, int hr)
1096 {
1097   int j,k;
1098   for(j=0;j<9;j++)
1099   {
1100     if(i+j>=slen) {
1101       j=slen-i-1;
1102       break;
1103     }
1104     if (dops[i+j].is_ujump)
1105     {
1106       // Don't go past an unconditonal jump
1107       j++;
1108       break;
1109     }
1110   }
1111   k=0;
1112   if(i>0){
1113     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
1114       k--;
1115   }
1116   for(;k<j;k++)
1117   {
1118     assert(r < 64);
1119     if((unneeded_reg[i+k]>>r)&1) return hr;
1120     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
1121     {
1122       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
1123       {
1124         int t=(ba[i+k]-start)>>2;
1125         int reg=get_reg(regs[t].regmap_entry,r);
1126         if(reg>=0) return reg;
1127         //reg=get_reg(regs[t+1].regmap_entry,r);
1128         //if(reg>=0) return reg;
1129       }
1130     }
1131   }
1132   return hr;
1133 }
1134
1135
1136 // Allocate every register, preserving source/target regs
1137 static void alloc_all(struct regstat *cur,int i)
1138 {
1139   int hr;
1140
1141   for(hr=0;hr<HOST_REGS;hr++) {
1142     if(hr!=EXCLUDE_REG) {
1143       if((cur->regmap[hr]!=dops[i].rs1)&&(cur->regmap[hr]!=dops[i].rs2)&&
1144          (cur->regmap[hr]!=dops[i].rt1)&&(cur->regmap[hr]!=dops[i].rt2))
1145       {
1146         cur->regmap[hr]=-1;
1147         cur->dirty&=~(1<<hr);
1148       }
1149       // Don't need zeros
1150       if(cur->regmap[hr]==0)
1151       {
1152         cur->regmap[hr]=-1;
1153         cur->dirty&=~(1<<hr);
1154       }
1155     }
1156   }
1157 }
1158
1159 #ifndef NDEBUG
1160 static int host_tempreg_in_use;
1161
1162 static void host_tempreg_acquire(void)
1163 {
1164   assert(!host_tempreg_in_use);
1165   host_tempreg_in_use = 1;
1166 }
1167
1168 static void host_tempreg_release(void)
1169 {
1170   host_tempreg_in_use = 0;
1171 }
1172 #else
1173 static void host_tempreg_acquire(void) {}
1174 static void host_tempreg_release(void) {}
1175 #endif
1176
1177 #ifdef ASSEM_PRINT
1178 extern void gen_interupt();
1179 extern void do_insn_cmp();
1180 #define FUNCNAME(f) { f, " " #f }
1181 static const struct {
1182   void *addr;
1183   const char *name;
1184 } function_names[] = {
1185   FUNCNAME(cc_interrupt),
1186   FUNCNAME(gen_interupt),
1187   FUNCNAME(ndrc_get_addr_ht),
1188   FUNCNAME(jump_handler_read8),
1189   FUNCNAME(jump_handler_read16),
1190   FUNCNAME(jump_handler_read32),
1191   FUNCNAME(jump_handler_write8),
1192   FUNCNAME(jump_handler_write16),
1193   FUNCNAME(jump_handler_write32),
1194   FUNCNAME(ndrc_write_invalidate_one),
1195   FUNCNAME(ndrc_write_invalidate_many),
1196   FUNCNAME(jump_to_new_pc),
1197   FUNCNAME(jump_break),
1198   FUNCNAME(jump_break_ds),
1199   FUNCNAME(jump_syscall),
1200   FUNCNAME(jump_syscall_ds),
1201   FUNCNAME(call_gteStall),
1202   FUNCNAME(new_dyna_leave),
1203   FUNCNAME(pcsx_mtc0),
1204   FUNCNAME(pcsx_mtc0_ds),
1205 #ifdef DRC_DBG
1206   FUNCNAME(do_insn_cmp),
1207 #endif
1208 };
1209
1210 static const char *func_name(const void *a)
1211 {
1212   int i;
1213   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
1214     if (function_names[i].addr == a)
1215       return function_names[i].name;
1216   return "";
1217 }
1218 #else
1219 #define func_name(x) ""
1220 #endif
1221
1222 #ifdef __i386__
1223 #include "assem_x86.c"
1224 #endif
1225 #ifdef __x86_64__
1226 #include "assem_x64.c"
1227 #endif
1228 #ifdef __arm__
1229 #include "assem_arm.c"
1230 #endif
1231 #ifdef __aarch64__
1232 #include "assem_arm64.c"
1233 #endif
1234
1235 static void *get_trampoline(const void *f)
1236 {
1237   struct ndrc_tramp *tramp = NDRC_WRITE_OFFSET(&ndrc->tramp);
1238   size_t i;
1239
1240   for (i = 0; i < ARRAY_SIZE(tramp->f); i++) {
1241     if (tramp->f[i] == f || tramp->f[i] == NULL)
1242       break;
1243   }
1244   if (i == ARRAY_SIZE(tramp->f)) {
1245     SysPrintf("trampoline table is full, last func %p\n", f);
1246     abort();
1247   }
1248   if (tramp->f[i] == NULL) {
1249     start_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1250     tramp->f[i] = f;
1251     end_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1252 #ifdef HAVE_LIBNX
1253     // invalidate the RX mirror (unsure if necessary, but just in case...)
1254     armDCacheFlush(&ndrc->tramp.f[i], sizeof(ndrc->tramp.f[i]));
1255 #endif
1256   }
1257   return &ndrc->tramp.ops[i];
1258 }
1259
1260 static void emit_far_jump(const void *f)
1261 {
1262   if (can_jump_or_call(f)) {
1263     emit_jmp(f);
1264     return;
1265   }
1266
1267   f = get_trampoline(f);
1268   emit_jmp(f);
1269 }
1270
1271 static void emit_far_call(const void *f)
1272 {
1273   if (can_jump_or_call(f)) {
1274     emit_call(f);
1275     return;
1276   }
1277
1278   f = get_trampoline(f);
1279   emit_call(f);
1280 }
1281
1282 // Check if an address is already compiled
1283 // but don't return addresses which are about to expire from the cache
1284 static void *check_addr(u_int vaddr)
1285 {
1286   struct ht_entry *ht_bin = hash_table_get(vaddr);
1287   size_t i;
1288   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1289     if (ht_bin->vaddr[i] == vaddr)
1290       if (doesnt_expire_soon(ht_bin->tcaddr[i]))
1291         return ht_bin->tcaddr[i];
1292   }
1293
1294   // refactor to get_addr_nocompile?
1295   u_int start_page = get_page_prev(vaddr);
1296   u_int page, end_page = get_page(vaddr);
1297
1298   stat_inc(stat_jump_in_lookups);
1299   for (page = start_page; page <= end_page; page++) {
1300     const struct block_info *block;
1301     for (block = blocks[page]; block != NULL; block = block->next) {
1302       if (vaddr < block->start)
1303         break;
1304       if (block->is_dirty || vaddr >= block->start + block->len)
1305         continue;
1306       if (!doesnt_expire_soon(ndrc->translation_cache + block->tc_offs))
1307         continue;
1308       for (i = 0; i < block->jump_in_cnt; i++)
1309         if (block->jump_in[i].vaddr == vaddr)
1310           break;
1311       if (i == block->jump_in_cnt)
1312         continue;
1313
1314       // Update existing entry with current address
1315       void *addr = block->jump_in[i].addr;
1316       if (ht_bin->vaddr[0] == vaddr) {
1317         ht_bin->tcaddr[0] = addr;
1318         return addr;
1319       }
1320       if (ht_bin->vaddr[1] == vaddr) {
1321         ht_bin->tcaddr[1] = addr;
1322         return addr;
1323       }
1324       // Insert into hash table with low priority.
1325       // Don't evict existing entries, as they are probably
1326       // addresses that are being accessed frequently.
1327       if (ht_bin->vaddr[0] == -1) {
1328         ht_bin->vaddr[0] = vaddr;
1329         ht_bin->tcaddr[0] = addr;
1330       }
1331       else if (ht_bin->vaddr[1] == -1) {
1332         ht_bin->vaddr[1] = vaddr;
1333         ht_bin->tcaddr[1] = addr;
1334       }
1335       return addr;
1336     }
1337   }
1338   return NULL;
1339 }
1340
1341 static void blocks_clear(struct block_info **head)
1342 {
1343   struct block_info *cur, *next;
1344
1345   if ((cur = *head)) {
1346     *head = NULL;
1347     while (cur) {
1348       next = cur->next;
1349       free(cur);
1350       cur = next;
1351     }
1352   }
1353 }
1354
1355 static int blocks_remove_matching_addrs(struct block_info **head,
1356   u_int base_offs, int shift)
1357 {
1358   struct block_info *next;
1359   int hit = 0;
1360   while (*head) {
1361     if ((((*head)->tc_offs ^ base_offs) >> shift) == 0) {
1362       inv_debug("EXP: rm block %08x (tc_offs %x)\n", (*head)->start, (*head)->tc_offs);
1363       invalidate_block(*head);
1364       next = (*head)->next;
1365       free(*head);
1366       *head = next;
1367       stat_dec(stat_blocks);
1368       hit = 1;
1369     }
1370     else
1371     {
1372       head = &((*head)->next);
1373     }
1374   }
1375   return hit;
1376 }
1377
1378 // This is called when we write to a compiled block (see do_invstub)
1379 static void unlink_jumps_vaddr_range(u_int start, u_int end)
1380 {
1381   u_int page, start_page = get_page(start), end_page = get_page(end - 1);
1382   int i;
1383
1384   for (page = start_page; page <= end_page; page++) {
1385     struct jump_info *ji = jumps[page];
1386     if (ji == NULL)
1387       continue;
1388     for (i = 0; i < ji->count; ) {
1389       if (ji->e[i].target_vaddr < start || ji->e[i].target_vaddr >= end) {
1390         i++;
1391         continue;
1392       }
1393
1394       inv_debug("INV: rm link to %08x (tc_offs %zx)\n", ji->e[i].target_vaddr,
1395         (u_char *)ji->e[i].stub - ndrc->translation_cache);
1396       void *host_addr = find_extjump_insn(ji->e[i].stub);
1397       mark_clear_cache(host_addr);
1398       set_jump_target(host_addr, ji->e[i].stub); // point back to dyna_linker stub
1399
1400       stat_dec(stat_links);
1401       ji->count--;
1402       if (i < ji->count) {
1403         ji->e[i] = ji->e[ji->count];
1404         continue;
1405       }
1406       i++;
1407     }
1408   }
1409 }
1410
1411 static void unlink_jumps_tc_range(struct jump_info *ji, u_int base_offs, int shift)
1412 {
1413   int i;
1414   if (ji == NULL)
1415     return;
1416   for (i = 0; i < ji->count; ) {
1417     u_int tc_offs = (u_char *)ji->e[i].stub - ndrc->translation_cache;
1418     if (((tc_offs ^ base_offs) >> shift) != 0) {
1419       i++;
1420       continue;
1421     }
1422
1423     inv_debug("EXP: rm link to %08x (tc_offs %x)\n", ji->e[i].target_vaddr, tc_offs);
1424     stat_dec(stat_links);
1425     ji->count--;
1426     if (i < ji->count) {
1427       ji->e[i] = ji->e[ji->count];
1428       continue;
1429     }
1430     i++;
1431   }
1432 }
1433
1434 static void invalidate_block(struct block_info *block)
1435 {
1436   u_int i;
1437
1438   block->is_dirty = 1;
1439   unlink_jumps_vaddr_range(block->start, block->start + block->len);
1440   for (i = 0; i < block->jump_in_cnt; i++)
1441     hash_table_remove(block->jump_in[i].vaddr);
1442 }
1443
1444 static int invalidate_range(u_int start, u_int end,
1445   u32 *inv_start_ret, u32 *inv_end_ret)
1446 {
1447   struct block_info *last_block = NULL;
1448   u_int start_page = get_page_prev(start);
1449   u_int end_page = get_page(end - 1);
1450   u_int start_m = pmmask(start);
1451   u_int end_m = pmmask(end - 1);
1452   u_int inv_start, inv_end;
1453   u_int blk_start_m, blk_end_m;
1454   u_int page;
1455   int hit = 0;
1456
1457   // additional area without code (to supplement invalid_code[]), [start, end)
1458   // avoids excessive ndrc_write_invalidate*() calls
1459   inv_start = start_m & ~0xfff;
1460   inv_end = end_m | 0xfff;
1461
1462   for (page = start_page; page <= end_page; page++) {
1463     struct block_info *block;
1464     for (block = blocks[page]; block != NULL; block = block->next) {
1465       if (block->is_dirty)
1466         continue;
1467       last_block = block;
1468       blk_end_m = pmmask(block->start + block->len);
1469       if (blk_end_m <= start_m) {
1470         inv_start = max(inv_start, blk_end_m);
1471         continue;
1472       }
1473       blk_start_m = pmmask(block->start);
1474       if (end_m <= blk_start_m) {
1475         inv_end = min(inv_end, blk_start_m - 1);
1476         continue;
1477       }
1478       if (!block->source) // "hack" block - leave it alone
1479         continue;
1480
1481       hit++;
1482       invalidate_block(block);
1483       stat_inc(stat_inv_hits);
1484     }
1485   }
1486
1487   if (!hit && last_block && last_block->source) {
1488     // could be some leftover unused block, uselessly trapping writes
1489     last_block->inv_near_misses++;
1490     if (last_block->inv_near_misses > 128) {
1491       invalidate_block(last_block);
1492       stat_inc(stat_inv_hits);
1493       hit++;
1494     }
1495   }
1496   if (hit) {
1497     do_clear_cache();
1498 #ifdef USE_MINI_HT
1499     memset(mini_ht, -1, sizeof(mini_ht));
1500 #endif
1501   }
1502
1503   if (inv_start <= (start_m & ~0xfff) && inv_end >= (start_m | 0xfff))
1504     // the whole page is empty now
1505     mark_invalid_code(start, 1, 1);
1506
1507   if (inv_start_ret) *inv_start_ret = inv_start | (start & 0xe0000000);
1508   if (inv_end_ret) *inv_end_ret = inv_end | (end & 0xe0000000);
1509   return hit;
1510 }
1511
1512 void new_dynarec_invalidate_range(unsigned int start, unsigned int end)
1513 {
1514   invalidate_range(start, end, NULL, NULL);
1515 }
1516
1517 static void ndrc_write_invalidate_many(u_int start, u_int end)
1518 {
1519   // this check is done by the caller
1520   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1521   int ret = invalidate_range(start, end, &inv_code_start, &inv_code_end);
1522 #ifdef INV_DEBUG_W
1523   int invc = invalid_code[start >> 12];
1524   u_int len = end - start;
1525   if (ret)
1526     printf("INV ADDR: %08x/%02x hit %d blocks\n", start, len, ret);
1527   else
1528     printf("INV ADDR: %08x/%02x miss, inv %08x-%08x invc %d->%d\n", start, len,
1529       inv_code_start, inv_code_end, invc, invalid_code[start >> 12]);
1530   check_for_block_changes(start, end);
1531 #endif
1532   stat_inc(stat_inv_addr_calls);
1533   (void)ret;
1534 }
1535
1536 void ndrc_write_invalidate_one(u_int addr)
1537 {
1538   ndrc_write_invalidate_many(addr, addr + 4);
1539 }
1540
1541 // This is called when loading a save state.
1542 // Anything could have changed, so invalidate everything.
1543 void new_dynarec_invalidate_all_pages(void)
1544 {
1545   struct block_info *block;
1546   u_int page;
1547   for (page = 0; page < ARRAY_SIZE(blocks); page++) {
1548     for (block = blocks[page]; block != NULL; block = block->next) {
1549       if (block->is_dirty)
1550         continue;
1551       if (!block->source) // hack block?
1552         continue;
1553       invalidate_block(block);
1554     }
1555   }
1556
1557   #ifdef USE_MINI_HT
1558   memset(mini_ht, -1, sizeof(mini_ht));
1559   #endif
1560   do_clear_cache();
1561 }
1562
1563 // Add an entry to jump_out after making a link
1564 // src should point to code by emit_extjump()
1565 void ndrc_add_jump_out(u_int vaddr, void *src)
1566 {
1567   inv_debug("ndrc_add_jump_out: %p -> %x\n", src, vaddr);
1568   u_int page = get_page(vaddr);
1569   struct jump_info *ji;
1570
1571   stat_inc(stat_links);
1572   check_extjump2(src);
1573   ji = jumps[page];
1574   if (ji == NULL) {
1575     ji = malloc(sizeof(*ji) + sizeof(ji->e[0]) * 16);
1576     ji->alloc = 16;
1577     ji->count = 0;
1578   }
1579   else if (ji->count >= ji->alloc) {
1580     ji->alloc += 16;
1581     ji = realloc(ji, sizeof(*ji) + sizeof(ji->e[0]) * ji->alloc);
1582   }
1583   jumps[page] = ji;
1584   ji->e[ji->count].target_vaddr = vaddr;
1585   ji->e[ji->count].stub = src;
1586   ji->count++;
1587 }
1588
1589 /* Register allocation */
1590
1591 // Note: registers are allocated clean (unmodified state)
1592 // if you intend to modify the register, you must call dirty_reg().
1593 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1594 {
1595   int r,hr;
1596   int preferred_reg = PREFERRED_REG_FIRST
1597     + reg % (PREFERRED_REG_LAST - PREFERRED_REG_FIRST + 1);
1598   if (reg == CCREG) preferred_reg = HOST_CCREG;
1599   if (reg == PTEMP || reg == FTEMP) preferred_reg = 12;
1600   assert(PREFERRED_REG_FIRST != EXCLUDE_REG && EXCLUDE_REG != HOST_REGS);
1601   assert(reg >= 0);
1602
1603   // Don't allocate unused registers
1604   if((cur->u>>reg)&1) return;
1605
1606   // see if it's already allocated
1607   if (get_reg(cur->regmap, reg) >= 0)
1608     return;
1609
1610   // Keep the same mapping if the register was already allocated in a loop
1611   preferred_reg = loop_reg(i,reg,preferred_reg);
1612
1613   // Try to allocate the preferred register
1614   if(cur->regmap[preferred_reg]==-1) {
1615     cur->regmap[preferred_reg]=reg;
1616     cur->dirty&=~(1<<preferred_reg);
1617     cur->isconst&=~(1<<preferred_reg);
1618     return;
1619   }
1620   r=cur->regmap[preferred_reg];
1621   assert(r < 64);
1622   if((cur->u>>r)&1) {
1623     cur->regmap[preferred_reg]=reg;
1624     cur->dirty&=~(1<<preferred_reg);
1625     cur->isconst&=~(1<<preferred_reg);
1626     return;
1627   }
1628
1629   // Clear any unneeded registers
1630   // We try to keep the mapping consistent, if possible, because it
1631   // makes branches easier (especially loops).  So we try to allocate
1632   // first (see above) before removing old mappings.  If this is not
1633   // possible then go ahead and clear out the registers that are no
1634   // longer needed.
1635   for(hr=0;hr<HOST_REGS;hr++)
1636   {
1637     r=cur->regmap[hr];
1638     if(r>=0) {
1639       assert(r < 64);
1640       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1641     }
1642   }
1643
1644   // Try to allocate any available register, but prefer
1645   // registers that have not been used recently.
1646   if (i > 0) {
1647     for (hr = PREFERRED_REG_FIRST; ; ) {
1648       if (cur->regmap[hr] < 0) {
1649         int oldreg = regs[i-1].regmap[hr];
1650         if (oldreg < 0 || (oldreg != dops[i-1].rs1 && oldreg != dops[i-1].rs2
1651              && oldreg != dops[i-1].rt1 && oldreg != dops[i-1].rt2))
1652         {
1653           cur->regmap[hr]=reg;
1654           cur->dirty&=~(1<<hr);
1655           cur->isconst&=~(1<<hr);
1656           return;
1657         }
1658       }
1659       hr++;
1660       if (hr == EXCLUDE_REG)
1661         hr++;
1662       if (hr == HOST_REGS)
1663         hr = 0;
1664       if (hr == PREFERRED_REG_FIRST)
1665         break;
1666     }
1667   }
1668
1669   // Try to allocate any available register
1670   for (hr = PREFERRED_REG_FIRST; ; ) {
1671     if (cur->regmap[hr] < 0) {
1672       cur->regmap[hr]=reg;
1673       cur->dirty&=~(1<<hr);
1674       cur->isconst&=~(1<<hr);
1675       return;
1676     }
1677     hr++;
1678     if (hr == EXCLUDE_REG)
1679       hr++;
1680     if (hr == HOST_REGS)
1681       hr = 0;
1682     if (hr == PREFERRED_REG_FIRST)
1683       break;
1684   }
1685
1686   // Ok, now we have to evict someone
1687   // Pick a register we hopefully won't need soon
1688   u_char hsn[MAXREG+1];
1689   memset(hsn,10,sizeof(hsn));
1690   int j;
1691   lsn(hsn,i,&preferred_reg);
1692   //printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",cur->regmap[0],cur->regmap[1],cur->regmap[2],cur->regmap[3],cur->regmap[5],cur->regmap[6],cur->regmap[7]);
1693   //printf("hsn(%x): %d %d %d %d %d %d %d\n",start+i*4,hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1694   if(i>0) {
1695     // Don't evict the cycle count at entry points, otherwise the entry
1696     // stub will have to write it.
1697     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1698     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1699     for(j=10;j>=3;j--)
1700     {
1701       // Alloc preferred register if available
1702       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1703         for(hr=0;hr<HOST_REGS;hr++) {
1704           // Evict both parts of a 64-bit register
1705           if(cur->regmap[hr]==r) {
1706             cur->regmap[hr]=-1;
1707             cur->dirty&=~(1<<hr);
1708             cur->isconst&=~(1<<hr);
1709           }
1710         }
1711         cur->regmap[preferred_reg]=reg;
1712         return;
1713       }
1714       for(r=1;r<=MAXREG;r++)
1715       {
1716         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1717           for(hr=0;hr<HOST_REGS;hr++) {
1718             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1719               if(cur->regmap[hr]==r) {
1720                 cur->regmap[hr]=reg;
1721                 cur->dirty&=~(1<<hr);
1722                 cur->isconst&=~(1<<hr);
1723                 return;
1724               }
1725             }
1726           }
1727         }
1728       }
1729     }
1730   }
1731   for(j=10;j>=0;j--)
1732   {
1733     for(r=1;r<=MAXREG;r++)
1734     {
1735       if(hsn[r]==j) {
1736         for(hr=0;hr<HOST_REGS;hr++) {
1737           if(cur->regmap[hr]==r) {
1738             cur->regmap[hr]=reg;
1739             cur->dirty&=~(1<<hr);
1740             cur->isconst&=~(1<<hr);
1741             return;
1742           }
1743         }
1744       }
1745     }
1746   }
1747   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1748 }
1749
1750 // Allocate a temporary register.  This is done without regard to
1751 // dirty status or whether the register we request is on the unneeded list
1752 // Note: This will only allocate one register, even if called multiple times
1753 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1754 {
1755   int r,hr;
1756   int preferred_reg = -1;
1757
1758   // see if it's already allocated
1759   for(hr=0;hr<HOST_REGS;hr++)
1760   {
1761     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1762   }
1763
1764   // Try to allocate any available register
1765   for(hr=HOST_REGS-1;hr>=0;hr--) {
1766     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1767       cur->regmap[hr]=reg;
1768       cur->dirty&=~(1<<hr);
1769       cur->isconst&=~(1<<hr);
1770       return;
1771     }
1772   }
1773
1774   // Find an unneeded register
1775   for(hr=HOST_REGS-1;hr>=0;hr--)
1776   {
1777     r=cur->regmap[hr];
1778     if(r>=0) {
1779       assert(r < 64);
1780       if((cur->u>>r)&1) {
1781         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1782           cur->regmap[hr]=reg;
1783           cur->dirty&=~(1<<hr);
1784           cur->isconst&=~(1<<hr);
1785           return;
1786         }
1787       }
1788     }
1789   }
1790
1791   // Ok, now we have to evict someone
1792   // Pick a register we hopefully won't need soon
1793   // TODO: we might want to follow unconditional jumps here
1794   // TODO: get rid of dupe code and make this into a function
1795   u_char hsn[MAXREG+1];
1796   memset(hsn,10,sizeof(hsn));
1797   int j;
1798   lsn(hsn,i,&preferred_reg);
1799   //printf("hsn: %d %d %d %d %d %d %d\n",hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1800   if(i>0) {
1801     // Don't evict the cycle count at entry points, otherwise the entry
1802     // stub will have to write it.
1803     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1804     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1805     for(j=10;j>=3;j--)
1806     {
1807       for(r=1;r<=MAXREG;r++)
1808       {
1809         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1810           for(hr=0;hr<HOST_REGS;hr++) {
1811             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1812               if(cur->regmap[hr]==r) {
1813                 cur->regmap[hr]=reg;
1814                 cur->dirty&=~(1<<hr);
1815                 cur->isconst&=~(1<<hr);
1816                 return;
1817               }
1818             }
1819           }
1820         }
1821       }
1822     }
1823   }
1824   for(j=10;j>=0;j--)
1825   {
1826     for(r=1;r<=MAXREG;r++)
1827     {
1828       if(hsn[r]==j) {
1829         for(hr=0;hr<HOST_REGS;hr++) {
1830           if(cur->regmap[hr]==r) {
1831             cur->regmap[hr]=reg;
1832             cur->dirty&=~(1<<hr);
1833             cur->isconst&=~(1<<hr);
1834             return;
1835           }
1836         }
1837       }
1838     }
1839   }
1840   SysPrintf("This shouldn't happen");abort();
1841 }
1842
1843 static void mov_alloc(struct regstat *current,int i)
1844 {
1845   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1846     alloc_cc(current,i); // for stalls
1847     dirty_reg(current,CCREG);
1848   }
1849
1850   // Note: Don't need to actually alloc the source registers
1851   //alloc_reg(current,i,dops[i].rs1);
1852   alloc_reg(current,i,dops[i].rt1);
1853
1854   clear_const(current,dops[i].rs1);
1855   clear_const(current,dops[i].rt1);
1856   dirty_reg(current,dops[i].rt1);
1857 }
1858
1859 static void shiftimm_alloc(struct regstat *current,int i)
1860 {
1861   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1862   {
1863     if(dops[i].rt1) {
1864       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1865       else dops[i].use_lt1=!!dops[i].rs1;
1866       alloc_reg(current,i,dops[i].rt1);
1867       dirty_reg(current,dops[i].rt1);
1868       if(is_const(current,dops[i].rs1)) {
1869         int v=get_const(current,dops[i].rs1);
1870         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1871         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1872         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1873       }
1874       else clear_const(current,dops[i].rt1);
1875     }
1876   }
1877   else
1878   {
1879     clear_const(current,dops[i].rs1);
1880     clear_const(current,dops[i].rt1);
1881   }
1882
1883   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1884   {
1885     assert(0);
1886   }
1887   if(dops[i].opcode2==0x3c) // DSLL32
1888   {
1889     assert(0);
1890   }
1891   if(dops[i].opcode2==0x3e) // DSRL32
1892   {
1893     assert(0);
1894   }
1895   if(dops[i].opcode2==0x3f) // DSRA32
1896   {
1897     assert(0);
1898   }
1899 }
1900
1901 static void shift_alloc(struct regstat *current,int i)
1902 {
1903   if(dops[i].rt1) {
1904     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1905     {
1906       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1907       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1908       alloc_reg(current,i,dops[i].rt1);
1909       if(dops[i].rt1==dops[i].rs2) {
1910         alloc_reg_temp(current,i,-1);
1911         minimum_free_regs[i]=1;
1912       }
1913     } else { // DSLLV/DSRLV/DSRAV
1914       assert(0);
1915     }
1916     clear_const(current,dops[i].rs1);
1917     clear_const(current,dops[i].rs2);
1918     clear_const(current,dops[i].rt1);
1919     dirty_reg(current,dops[i].rt1);
1920   }
1921 }
1922
1923 static void alu_alloc(struct regstat *current,int i)
1924 {
1925   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1926     if(dops[i].rt1) {
1927       if(dops[i].rs1&&dops[i].rs2) {
1928         alloc_reg(current,i,dops[i].rs1);
1929         alloc_reg(current,i,dops[i].rs2);
1930       }
1931       else {
1932         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1933         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1934       }
1935       alloc_reg(current,i,dops[i].rt1);
1936     }
1937   }
1938   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1939     if(dops[i].rt1) {
1940       alloc_reg(current,i,dops[i].rs1);
1941       alloc_reg(current,i,dops[i].rs2);
1942       alloc_reg(current,i,dops[i].rt1);
1943     }
1944   }
1945   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1946     if(dops[i].rt1) {
1947       if(dops[i].rs1&&dops[i].rs2) {
1948         alloc_reg(current,i,dops[i].rs1);
1949         alloc_reg(current,i,dops[i].rs2);
1950       }
1951       else
1952       {
1953         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1954         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1955       }
1956       alloc_reg(current,i,dops[i].rt1);
1957     }
1958   }
1959   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1960     assert(0);
1961   }
1962   clear_const(current,dops[i].rs1);
1963   clear_const(current,dops[i].rs2);
1964   clear_const(current,dops[i].rt1);
1965   dirty_reg(current,dops[i].rt1);
1966 }
1967
1968 static void imm16_alloc(struct regstat *current,int i)
1969 {
1970   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1971   else dops[i].use_lt1=!!dops[i].rs1;
1972   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1973   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1974     assert(0);
1975   }
1976   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1977     clear_const(current,dops[i].rs1);
1978     clear_const(current,dops[i].rt1);
1979   }
1980   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1981     if(is_const(current,dops[i].rs1)) {
1982       int v=get_const(current,dops[i].rs1);
1983       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1984       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1985       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1986     }
1987     else clear_const(current,dops[i].rt1);
1988   }
1989   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1990     if(is_const(current,dops[i].rs1)) {
1991       int v=get_const(current,dops[i].rs1);
1992       set_const(current,dops[i].rt1,v+imm[i]);
1993     }
1994     else clear_const(current,dops[i].rt1);
1995   }
1996   else {
1997     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1998   }
1999   dirty_reg(current,dops[i].rt1);
2000 }
2001
2002 static void load_alloc(struct regstat *current,int i)
2003 {
2004   clear_const(current,dops[i].rt1);
2005   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
2006   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
2007   if (needed_again(dops[i].rs1, i))
2008     alloc_reg(current, i, dops[i].rs1);
2009   if (ram_offset)
2010     alloc_reg(current, i, ROREG);
2011   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
2012     alloc_reg(current,i,dops[i].rt1);
2013     assert(get_reg(current->regmap,dops[i].rt1)>=0);
2014     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
2015     {
2016       assert(0);
2017     }
2018     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
2019     {
2020       assert(0);
2021     }
2022     dirty_reg(current,dops[i].rt1);
2023     // LWL/LWR need a temporary register for the old value
2024     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2025     {
2026       alloc_reg(current,i,FTEMP);
2027       alloc_reg_temp(current,i,-1);
2028       minimum_free_regs[i]=1;
2029     }
2030   }
2031   else
2032   {
2033     // Load to r0 or unneeded register (dummy load)
2034     // but we still need a register to calculate the address
2035     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2036     {
2037       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
2038     }
2039     alloc_reg_temp(current,i,-1);
2040     minimum_free_regs[i]=1;
2041     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
2042     {
2043       assert(0);
2044     }
2045   }
2046 }
2047
2048 static void store_alloc(struct regstat *current,int i)
2049 {
2050   clear_const(current,dops[i].rs2);
2051   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
2052   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2053   alloc_reg(current,i,dops[i].rs2);
2054   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
2055     assert(0);
2056   }
2057   if (ram_offset)
2058     alloc_reg(current, i, ROREG);
2059   #if defined(HOST_IMM8)
2060   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2061   alloc_reg(current, i, INVCP);
2062   #endif
2063   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
2064     alloc_reg(current,i,FTEMP);
2065   }
2066   // We need a temporary register for address generation
2067   alloc_reg_temp(current,i,-1);
2068   minimum_free_regs[i]=1;
2069 }
2070
2071 static void c1ls_alloc(struct regstat *current,int i)
2072 {
2073   clear_const(current,dops[i].rt1);
2074   alloc_reg(current,i,CSREG); // Status
2075 }
2076
2077 static void c2ls_alloc(struct regstat *current,int i)
2078 {
2079   clear_const(current,dops[i].rt1);
2080   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2081   alloc_reg(current,i,FTEMP);
2082   if (ram_offset)
2083     alloc_reg(current, i, ROREG);
2084   #if defined(HOST_IMM8)
2085   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2086   if (dops[i].opcode == 0x3a) // SWC2
2087     alloc_reg(current,i,INVCP);
2088   #endif
2089   // We need a temporary register for address generation
2090   alloc_reg_temp(current,i,-1);
2091   minimum_free_regs[i]=1;
2092 }
2093
2094 #ifndef multdiv_alloc
2095 static void multdiv_alloc(struct regstat *current,int i)
2096 {
2097   //  case 0x18: MULT
2098   //  case 0x19: MULTU
2099   //  case 0x1A: DIV
2100   //  case 0x1B: DIVU
2101   //  case 0x1C: DMULT
2102   //  case 0x1D: DMULTU
2103   //  case 0x1E: DDIV
2104   //  case 0x1F: DDIVU
2105   clear_const(current,dops[i].rs1);
2106   clear_const(current,dops[i].rs2);
2107   alloc_cc(current,i); // for stalls
2108   if(dops[i].rs1&&dops[i].rs2)
2109   {
2110     if((dops[i].opcode2&4)==0) // 32-bit
2111     {
2112       current->u&=~(1LL<<HIREG);
2113       current->u&=~(1LL<<LOREG);
2114       alloc_reg(current,i,HIREG);
2115       alloc_reg(current,i,LOREG);
2116       alloc_reg(current,i,dops[i].rs1);
2117       alloc_reg(current,i,dops[i].rs2);
2118       dirty_reg(current,HIREG);
2119       dirty_reg(current,LOREG);
2120     }
2121     else // 64-bit
2122     {
2123       assert(0);
2124     }
2125   }
2126   else
2127   {
2128     // Multiply by zero is zero.
2129     // MIPS does not have a divide by zero exception.
2130     // The result is undefined, we return zero.
2131     alloc_reg(current,i,HIREG);
2132     alloc_reg(current,i,LOREG);
2133     dirty_reg(current,HIREG);
2134     dirty_reg(current,LOREG);
2135   }
2136 }
2137 #endif
2138
2139 static void cop0_alloc(struct regstat *current,int i)
2140 {
2141   if(dops[i].opcode2==0) // MFC0
2142   {
2143     if(dops[i].rt1) {
2144       clear_const(current,dops[i].rt1);
2145       alloc_all(current,i);
2146       alloc_reg(current,i,dops[i].rt1);
2147       dirty_reg(current,dops[i].rt1);
2148     }
2149   }
2150   else if(dops[i].opcode2==4) // MTC0
2151   {
2152     if(dops[i].rs1){
2153       clear_const(current,dops[i].rs1);
2154       alloc_reg(current,i,dops[i].rs1);
2155       alloc_all(current,i);
2156     }
2157     else {
2158       alloc_all(current,i); // FIXME: Keep r0
2159       current->u&=~1LL;
2160       alloc_reg(current,i,0);
2161     }
2162   }
2163   else
2164   {
2165     // RFE
2166     assert(dops[i].opcode2==0x10);
2167     alloc_all(current,i);
2168   }
2169   minimum_free_regs[i]=HOST_REGS;
2170 }
2171
2172 static void cop2_alloc(struct regstat *current,int i)
2173 {
2174   if (dops[i].opcode2 < 3) // MFC2/CFC2
2175   {
2176     alloc_cc(current,i); // for stalls
2177     dirty_reg(current,CCREG);
2178     if(dops[i].rt1){
2179       clear_const(current,dops[i].rt1);
2180       alloc_reg(current,i,dops[i].rt1);
2181       dirty_reg(current,dops[i].rt1);
2182     }
2183   }
2184   else if (dops[i].opcode2 > 3) // MTC2/CTC2
2185   {
2186     if(dops[i].rs1){
2187       clear_const(current,dops[i].rs1);
2188       alloc_reg(current,i,dops[i].rs1);
2189     }
2190     else {
2191       current->u&=~1LL;
2192       alloc_reg(current,i,0);
2193     }
2194   }
2195   alloc_reg_temp(current,i,-1);
2196   minimum_free_regs[i]=1;
2197 }
2198
2199 static void c2op_alloc(struct regstat *current,int i)
2200 {
2201   alloc_cc(current,i); // for stalls
2202   dirty_reg(current,CCREG);
2203   alloc_reg_temp(current,i,-1);
2204 }
2205
2206 static void syscall_alloc(struct regstat *current,int i)
2207 {
2208   alloc_cc(current,i);
2209   dirty_reg(current,CCREG);
2210   alloc_all(current,i);
2211   minimum_free_regs[i]=HOST_REGS;
2212   current->isconst=0;
2213 }
2214
2215 static void delayslot_alloc(struct regstat *current,int i)
2216 {
2217   switch(dops[i].itype) {
2218     case UJUMP:
2219     case CJUMP:
2220     case SJUMP:
2221     case RJUMP:
2222     case SYSCALL:
2223     case HLECALL:
2224     case IMM16:
2225       imm16_alloc(current,i);
2226       break;
2227     case LOAD:
2228     case LOADLR:
2229       load_alloc(current,i);
2230       break;
2231     case STORE:
2232     case STORELR:
2233       store_alloc(current,i);
2234       break;
2235     case ALU:
2236       alu_alloc(current,i);
2237       break;
2238     case SHIFT:
2239       shift_alloc(current,i);
2240       break;
2241     case MULTDIV:
2242       multdiv_alloc(current,i);
2243       break;
2244     case SHIFTIMM:
2245       shiftimm_alloc(current,i);
2246       break;
2247     case MOV:
2248       mov_alloc(current,i);
2249       break;
2250     case COP0:
2251       cop0_alloc(current,i);
2252       break;
2253     case COP1:
2254       break;
2255     case COP2:
2256       cop2_alloc(current,i);
2257       break;
2258     case C1LS:
2259       c1ls_alloc(current,i);
2260       break;
2261     case C2LS:
2262       c2ls_alloc(current,i);
2263       break;
2264     case C2OP:
2265       c2op_alloc(current,i);
2266       break;
2267   }
2268 }
2269
2270 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2271   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2272 {
2273   assert(stubcount < ARRAY_SIZE(stubs));
2274   stubs[stubcount].type = type;
2275   stubs[stubcount].addr = addr;
2276   stubs[stubcount].retaddr = retaddr;
2277   stubs[stubcount].a = a;
2278   stubs[stubcount].b = b;
2279   stubs[stubcount].c = c;
2280   stubs[stubcount].d = d;
2281   stubs[stubcount].e = e;
2282   stubcount++;
2283 }
2284
2285 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2286   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2287 {
2288   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2289 }
2290
2291 // Write out a single register
2292 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty)
2293 {
2294   int hr;
2295   for(hr=0;hr<HOST_REGS;hr++) {
2296     if(hr!=EXCLUDE_REG) {
2297       if(regmap[hr]==r) {
2298         if((dirty>>hr)&1) {
2299           assert(regmap[hr]<64);
2300           emit_storereg(r,hr);
2301         }
2302       }
2303     }
2304   }
2305 }
2306
2307 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2308 {
2309   //if(dirty_pre==dirty) return;
2310   int hr, r;
2311   for (hr = 0; hr < HOST_REGS; hr++) {
2312     r = pre[hr];
2313     if (r < 1 || r > 33 || ((u >> r) & 1))
2314       continue;
2315     if (((dirty_pre & ~dirty) >> hr) & 1)
2316       emit_storereg(r, hr);
2317   }
2318 }
2319
2320 // trashes r2
2321 static void pass_args(int a0, int a1)
2322 {
2323   if(a0==1&&a1==0) {
2324     // must swap
2325     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2326   }
2327   else if(a0!=0&&a1==0) {
2328     emit_mov(a1,1);
2329     if (a0>=0) emit_mov(a0,0);
2330   }
2331   else {
2332     if(a0>=0&&a0!=0) emit_mov(a0,0);
2333     if(a1>=0&&a1!=1) emit_mov(a1,1);
2334   }
2335 }
2336
2337 static void alu_assemble(int i, const struct regstat *i_regs)
2338 {
2339   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2340     if(dops[i].rt1) {
2341       signed char s1,s2,t;
2342       t=get_reg(i_regs->regmap,dops[i].rt1);
2343       if(t>=0) {
2344         s1=get_reg(i_regs->regmap,dops[i].rs1);
2345         s2=get_reg(i_regs->regmap,dops[i].rs2);
2346         if(dops[i].rs1&&dops[i].rs2) {
2347           assert(s1>=0);
2348           assert(s2>=0);
2349           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2350           else emit_add(s1,s2,t);
2351         }
2352         else if(dops[i].rs1) {
2353           if(s1>=0) emit_mov(s1,t);
2354           else emit_loadreg(dops[i].rs1,t);
2355         }
2356         else if(dops[i].rs2) {
2357           if(s2>=0) {
2358             if(dops[i].opcode2&2) emit_neg(s2,t);
2359             else emit_mov(s2,t);
2360           }
2361           else {
2362             emit_loadreg(dops[i].rs2,t);
2363             if(dops[i].opcode2&2) emit_neg(t,t);
2364           }
2365         }
2366         else emit_zeroreg(t);
2367       }
2368     }
2369   }
2370   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2371     assert(0);
2372   }
2373   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2374     if(dops[i].rt1) {
2375       signed char s1l,s2l,t;
2376       {
2377         t=get_reg(i_regs->regmap,dops[i].rt1);
2378         //assert(t>=0);
2379         if(t>=0) {
2380           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2381           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2382           if(dops[i].rs2==0) // rx<r0
2383           {
2384             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2385               assert(s1l>=0);
2386               emit_shrimm(s1l,31,t);
2387             }
2388             else // SLTU (unsigned can not be less than zero, 0<0)
2389               emit_zeroreg(t);
2390           }
2391           else if(dops[i].rs1==0) // r0<rx
2392           {
2393             assert(s2l>=0);
2394             if(dops[i].opcode2==0x2a) // SLT
2395               emit_set_gz32(s2l,t);
2396             else // SLTU (set if not zero)
2397               emit_set_nz32(s2l,t);
2398           }
2399           else{
2400             assert(s1l>=0);assert(s2l>=0);
2401             if(dops[i].opcode2==0x2a) // SLT
2402               emit_set_if_less32(s1l,s2l,t);
2403             else // SLTU
2404               emit_set_if_carry32(s1l,s2l,t);
2405           }
2406         }
2407       }
2408     }
2409   }
2410   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2411     if(dops[i].rt1) {
2412       signed char s1l,s2l,tl;
2413       tl=get_reg(i_regs->regmap,dops[i].rt1);
2414       {
2415         if(tl>=0) {
2416           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2417           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2418           if(dops[i].rs1&&dops[i].rs2) {
2419             assert(s1l>=0);
2420             assert(s2l>=0);
2421             if(dops[i].opcode2==0x24) { // AND
2422               emit_and(s1l,s2l,tl);
2423             } else
2424             if(dops[i].opcode2==0x25) { // OR
2425               emit_or(s1l,s2l,tl);
2426             } else
2427             if(dops[i].opcode2==0x26) { // XOR
2428               emit_xor(s1l,s2l,tl);
2429             } else
2430             if(dops[i].opcode2==0x27) { // NOR
2431               emit_or(s1l,s2l,tl);
2432               emit_not(tl,tl);
2433             }
2434           }
2435           else
2436           {
2437             if(dops[i].opcode2==0x24) { // AND
2438               emit_zeroreg(tl);
2439             } else
2440             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2441               if(dops[i].rs1){
2442                 if(s1l>=0) emit_mov(s1l,tl);
2443                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2444               }
2445               else
2446               if(dops[i].rs2){
2447                 if(s2l>=0) emit_mov(s2l,tl);
2448                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2449               }
2450               else emit_zeroreg(tl);
2451             } else
2452             if(dops[i].opcode2==0x27) { // NOR
2453               if(dops[i].rs1){
2454                 if(s1l>=0) emit_not(s1l,tl);
2455                 else {
2456                   emit_loadreg(dops[i].rs1,tl);
2457                   emit_not(tl,tl);
2458                 }
2459               }
2460               else
2461               if(dops[i].rs2){
2462                 if(s2l>=0) emit_not(s2l,tl);
2463                 else {
2464                   emit_loadreg(dops[i].rs2,tl);
2465                   emit_not(tl,tl);
2466                 }
2467               }
2468               else emit_movimm(-1,tl);
2469             }
2470           }
2471         }
2472       }
2473     }
2474   }
2475 }
2476
2477 static void imm16_assemble(int i, const struct regstat *i_regs)
2478 {
2479   if (dops[i].opcode==0x0f) { // LUI
2480     if(dops[i].rt1) {
2481       signed char t;
2482       t=get_reg(i_regs->regmap,dops[i].rt1);
2483       //assert(t>=0);
2484       if(t>=0) {
2485         if(!((i_regs->isconst>>t)&1))
2486           emit_movimm(imm[i]<<16,t);
2487       }
2488     }
2489   }
2490   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2491     if(dops[i].rt1) {
2492       signed char s,t;
2493       t=get_reg(i_regs->regmap,dops[i].rt1);
2494       s=get_reg(i_regs->regmap,dops[i].rs1);
2495       if(dops[i].rs1) {
2496         //assert(t>=0);
2497         //assert(s>=0);
2498         if(t>=0) {
2499           if(!((i_regs->isconst>>t)&1)) {
2500             if(s<0) {
2501               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2502               emit_addimm(t,imm[i],t);
2503             }else{
2504               if(!((i_regs->wasconst>>s)&1))
2505                 emit_addimm(s,imm[i],t);
2506               else
2507                 emit_movimm(constmap[i][s]+imm[i],t);
2508             }
2509           }
2510         }
2511       } else {
2512         if(t>=0) {
2513           if(!((i_regs->isconst>>t)&1))
2514             emit_movimm(imm[i],t);
2515         }
2516       }
2517     }
2518   }
2519   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2520     if(dops[i].rt1) {
2521       signed char sl,tl;
2522       tl=get_reg(i_regs->regmap,dops[i].rt1);
2523       sl=get_reg(i_regs->regmap,dops[i].rs1);
2524       if(tl>=0) {
2525         if(dops[i].rs1) {
2526           assert(sl>=0);
2527           emit_addimm(sl,imm[i],tl);
2528         } else {
2529           emit_movimm(imm[i],tl);
2530         }
2531       }
2532     }
2533   }
2534   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2535     if(dops[i].rt1) {
2536       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2537       signed char sl,t;
2538       t=get_reg(i_regs->regmap,dops[i].rt1);
2539       sl=get_reg(i_regs->regmap,dops[i].rs1);
2540       //assert(t>=0);
2541       if(t>=0) {
2542         if(dops[i].rs1>0) {
2543             if(dops[i].opcode==0x0a) { // SLTI
2544               if(sl<0) {
2545                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2546                 emit_slti32(t,imm[i],t);
2547               }else{
2548                 emit_slti32(sl,imm[i],t);
2549               }
2550             }
2551             else { // SLTIU
2552               if(sl<0) {
2553                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2554                 emit_sltiu32(t,imm[i],t);
2555               }else{
2556                 emit_sltiu32(sl,imm[i],t);
2557               }
2558             }
2559         }else{
2560           // SLTI(U) with r0 is just stupid,
2561           // nonetheless examples can be found
2562           if(dops[i].opcode==0x0a) // SLTI
2563             if(0<imm[i]) emit_movimm(1,t);
2564             else emit_zeroreg(t);
2565           else // SLTIU
2566           {
2567             if(imm[i]) emit_movimm(1,t);
2568             else emit_zeroreg(t);
2569           }
2570         }
2571       }
2572     }
2573   }
2574   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2575     if(dops[i].rt1) {
2576       signed char sl,tl;
2577       tl=get_reg(i_regs->regmap,dops[i].rt1);
2578       sl=get_reg(i_regs->regmap,dops[i].rs1);
2579       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2580         if(dops[i].opcode==0x0c) //ANDI
2581         {
2582           if(dops[i].rs1) {
2583             if(sl<0) {
2584               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2585               emit_andimm(tl,imm[i],tl);
2586             }else{
2587               if(!((i_regs->wasconst>>sl)&1))
2588                 emit_andimm(sl,imm[i],tl);
2589               else
2590                 emit_movimm(constmap[i][sl]&imm[i],tl);
2591             }
2592           }
2593           else
2594             emit_zeroreg(tl);
2595         }
2596         else
2597         {
2598           if(dops[i].rs1) {
2599             if(sl<0) {
2600               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2601             }
2602             if(dops[i].opcode==0x0d) { // ORI
2603               if(sl<0) {
2604                 emit_orimm(tl,imm[i],tl);
2605               }else{
2606                 if(!((i_regs->wasconst>>sl)&1))
2607                   emit_orimm(sl,imm[i],tl);
2608                 else
2609                   emit_movimm(constmap[i][sl]|imm[i],tl);
2610               }
2611             }
2612             if(dops[i].opcode==0x0e) { // XORI
2613               if(sl<0) {
2614                 emit_xorimm(tl,imm[i],tl);
2615               }else{
2616                 if(!((i_regs->wasconst>>sl)&1))
2617                   emit_xorimm(sl,imm[i],tl);
2618                 else
2619                   emit_movimm(constmap[i][sl]^imm[i],tl);
2620               }
2621             }
2622           }
2623           else {
2624             emit_movimm(imm[i],tl);
2625           }
2626         }
2627       }
2628     }
2629   }
2630 }
2631
2632 static void shiftimm_assemble(int i, const struct regstat *i_regs)
2633 {
2634   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2635   {
2636     if(dops[i].rt1) {
2637       signed char s,t;
2638       t=get_reg(i_regs->regmap,dops[i].rt1);
2639       s=get_reg(i_regs->regmap,dops[i].rs1);
2640       //assert(t>=0);
2641       if(t>=0&&!((i_regs->isconst>>t)&1)){
2642         if(dops[i].rs1==0)
2643         {
2644           emit_zeroreg(t);
2645         }
2646         else
2647         {
2648           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2649           if(imm[i]) {
2650             if(dops[i].opcode2==0) // SLL
2651             {
2652               emit_shlimm(s<0?t:s,imm[i],t);
2653             }
2654             if(dops[i].opcode2==2) // SRL
2655             {
2656               emit_shrimm(s<0?t:s,imm[i],t);
2657             }
2658             if(dops[i].opcode2==3) // SRA
2659             {
2660               emit_sarimm(s<0?t:s,imm[i],t);
2661             }
2662           }else{
2663             // Shift by zero
2664             if(s>=0 && s!=t) emit_mov(s,t);
2665           }
2666         }
2667       }
2668       //emit_storereg(dops[i].rt1,t); //DEBUG
2669     }
2670   }
2671   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2672   {
2673     assert(0);
2674   }
2675   if(dops[i].opcode2==0x3c) // DSLL32
2676   {
2677     assert(0);
2678   }
2679   if(dops[i].opcode2==0x3e) // DSRL32
2680   {
2681     assert(0);
2682   }
2683   if(dops[i].opcode2==0x3f) // DSRA32
2684   {
2685     assert(0);
2686   }
2687 }
2688
2689 #ifndef shift_assemble
2690 static void shift_assemble(int i, const struct regstat *i_regs)
2691 {
2692   signed char s,t,shift;
2693   if (dops[i].rt1 == 0)
2694     return;
2695   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2696   t = get_reg(i_regs->regmap, dops[i].rt1);
2697   s = get_reg(i_regs->regmap, dops[i].rs1);
2698   shift = get_reg(i_regs->regmap, dops[i].rs2);
2699   if (t < 0)
2700     return;
2701
2702   if(dops[i].rs1==0)
2703     emit_zeroreg(t);
2704   else if(dops[i].rs2==0) {
2705     assert(s>=0);
2706     if(s!=t) emit_mov(s,t);
2707   }
2708   else {
2709     host_tempreg_acquire();
2710     emit_andimm(shift,31,HOST_TEMPREG);
2711     switch(dops[i].opcode2) {
2712     case 4: // SLLV
2713       emit_shl(s,HOST_TEMPREG,t);
2714       break;
2715     case 6: // SRLV
2716       emit_shr(s,HOST_TEMPREG,t);
2717       break;
2718     case 7: // SRAV
2719       emit_sar(s,HOST_TEMPREG,t);
2720       break;
2721     default:
2722       assert(0);
2723     }
2724     host_tempreg_release();
2725   }
2726 }
2727
2728 #endif
2729
2730 enum {
2731   MTYPE_8000 = 0,
2732   MTYPE_8020,
2733   MTYPE_0000,
2734   MTYPE_A000,
2735   MTYPE_1F80,
2736 };
2737
2738 static int get_ptr_mem_type(u_int a)
2739 {
2740   if(a < 0x00200000) {
2741     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2742       // return wrong, must use memhandler for BIOS self-test to pass
2743       // 007 does similar stuff from a00 mirror, weird stuff
2744       return MTYPE_8000;
2745     return MTYPE_0000;
2746   }
2747   if(0x1f800000 <= a && a < 0x1f801000)
2748     return MTYPE_1F80;
2749   if(0x80200000 <= a && a < 0x80800000)
2750     return MTYPE_8020;
2751   if(0xa0000000 <= a && a < 0xa0200000)
2752     return MTYPE_A000;
2753   return MTYPE_8000;
2754 }
2755
2756 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2757 {
2758   int r = get_reg(i_regs->regmap, ROREG);
2759   if (r < 0 && host_tempreg_free) {
2760     host_tempreg_acquire();
2761     emit_loadreg(ROREG, r = HOST_TEMPREG);
2762   }
2763   if (r < 0)
2764     abort();
2765   return r;
2766 }
2767
2768 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2769   int addr, int *offset_reg, int *addr_reg_override)
2770 {
2771   void *jaddr = NULL;
2772   int type = 0;
2773   int mr = dops[i].rs1;
2774   *offset_reg = -1;
2775   if(((smrv_strong|smrv_weak)>>mr)&1) {
2776     type=get_ptr_mem_type(smrv[mr]);
2777     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2778   }
2779   else {
2780     // use the mirror we are running on
2781     type=get_ptr_mem_type(start);
2782     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2783   }
2784
2785   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2786     host_tempreg_acquire();
2787     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2788     addr=*addr_reg_override=HOST_TEMPREG;
2789     type=0;
2790   }
2791   else if(type==MTYPE_0000) { // RAM 0 mirror
2792     host_tempreg_acquire();
2793     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2794     addr=*addr_reg_override=HOST_TEMPREG;
2795     type=0;
2796   }
2797   else if(type==MTYPE_A000) { // RAM A mirror
2798     host_tempreg_acquire();
2799     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2800     addr=*addr_reg_override=HOST_TEMPREG;
2801     type=0;
2802   }
2803   else if(type==MTYPE_1F80) { // scratchpad
2804     if (psxH == (void *)0x1f800000) {
2805       host_tempreg_acquire();
2806       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2807       emit_cmpimm(HOST_TEMPREG,0x1000);
2808       host_tempreg_release();
2809       jaddr=out;
2810       emit_jc(0);
2811     }
2812     else {
2813       // do the usual RAM check, jump will go to the right handler
2814       type=0;
2815     }
2816   }
2817
2818   if (type == 0) // need ram check
2819   {
2820     emit_cmpimm(addr,RAM_SIZE);
2821     jaddr = out;
2822     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2823     // Hint to branch predictor that the branch is unlikely to be taken
2824     if (dops[i].rs1 >= 28)
2825       emit_jno_unlikely(0);
2826     else
2827     #endif
2828       emit_jno(0);
2829     if (ram_offset != 0)
2830       *offset_reg = get_ro_reg(i_regs, 0);
2831   }
2832
2833   return jaddr;
2834 }
2835
2836 // return memhandler, or get directly accessable address and return 0
2837 static void *get_direct_memhandler(void *table, u_int addr,
2838   enum stub_type type, uintptr_t *addr_host)
2839 {
2840   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2841   uintptr_t l1, l2 = 0;
2842   l1 = ((uintptr_t *)table)[addr>>12];
2843   if (!(l1 & msb)) {
2844     uintptr_t v = l1 << 1;
2845     *addr_host = v + addr;
2846     return NULL;
2847   }
2848   else {
2849     l1 <<= 1;
2850     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2851       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2852     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2853       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2854     else
2855       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2856     if (!(l2 & msb)) {
2857       uintptr_t v = l2 << 1;
2858       *addr_host = v + (addr&0xfff);
2859       return NULL;
2860     }
2861     return (void *)(l2 << 1);
2862   }
2863 }
2864
2865 static u_int get_host_reglist(const signed char *regmap)
2866 {
2867   u_int reglist = 0, hr;
2868   for (hr = 0; hr < HOST_REGS; hr++) {
2869     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2870       reglist |= 1 << hr;
2871   }
2872   return reglist;
2873 }
2874
2875 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2876 {
2877   if (r1 >= 0)
2878     reglist &= ~(1u << r1);
2879   if (r2 >= 0)
2880     reglist &= ~(1u << r2);
2881   return reglist;
2882 }
2883
2884 // find a temp caller-saved register not in reglist (so assumed to be free)
2885 static int reglist_find_free(u_int reglist)
2886 {
2887   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2888   if (free_regs == 0)
2889     return -1;
2890   return __builtin_ctz(free_regs);
2891 }
2892
2893 static void do_load_word(int a, int rt, int offset_reg)
2894 {
2895   if (offset_reg >= 0)
2896     emit_ldr_dualindexed(offset_reg, a, rt);
2897   else
2898     emit_readword_indexed(0, a, rt);
2899 }
2900
2901 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2902 {
2903   if (offset_reg < 0) {
2904     emit_writeword_indexed(rt, ofs, a);
2905     return;
2906   }
2907   if (ofs != 0)
2908     emit_addimm(a, ofs, a);
2909   emit_str_dualindexed(offset_reg, a, rt);
2910   if (ofs != 0 && preseve_a)
2911     emit_addimm(a, -ofs, a);
2912 }
2913
2914 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2915 {
2916   if (offset_reg < 0) {
2917     emit_writehword_indexed(rt, ofs, a);
2918     return;
2919   }
2920   if (ofs != 0)
2921     emit_addimm(a, ofs, a);
2922   emit_strh_dualindexed(offset_reg, a, rt);
2923   if (ofs != 0 && preseve_a)
2924     emit_addimm(a, -ofs, a);
2925 }
2926
2927 static void do_store_byte(int a, int rt, int offset_reg)
2928 {
2929   if (offset_reg >= 0)
2930     emit_strb_dualindexed(offset_reg, a, rt);
2931   else
2932     emit_writebyte_indexed(rt, 0, a);
2933 }
2934
2935 static void load_assemble(int i, const struct regstat *i_regs, int ccadj_)
2936 {
2937   int s,tl,addr;
2938   int offset;
2939   void *jaddr=0;
2940   int memtarget=0,c=0;
2941   int offset_reg = -1;
2942   int fastio_reg_override = -1;
2943   u_int reglist=get_host_reglist(i_regs->regmap);
2944   tl=get_reg(i_regs->regmap,dops[i].rt1);
2945   s=get_reg(i_regs->regmap,dops[i].rs1);
2946   offset=imm[i];
2947   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2948   if(s>=0) {
2949     c=(i_regs->wasconst>>s)&1;
2950     if (c) {
2951       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2952     }
2953   }
2954   //printf("load_assemble: c=%d\n",c);
2955   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2956   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2957   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2958     ||dops[i].rt1==0) {
2959       // could be FIFO, must perform the read
2960       // ||dummy read
2961       assem_debug("(forced read)\n");
2962       tl=get_reg_temp(i_regs->regmap);
2963       assert(tl>=0);
2964   }
2965   if(offset||s<0||c) addr=tl;
2966   else addr=s;
2967   //if(tl<0) tl=get_reg_temp(i_regs->regmap);
2968  if(tl>=0) {
2969   //printf("load_assemble: c=%d\n",c);
2970   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2971   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2972   reglist&=~(1<<tl);
2973   if(!c) {
2974     #ifdef R29_HACK
2975     // Strmnnrmn's speed hack
2976     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2977     #endif
2978     {
2979       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2980                 &offset_reg, &fastio_reg_override);
2981     }
2982   }
2983   else if (ram_offset && memtarget) {
2984     offset_reg = get_ro_reg(i_regs, 0);
2985   }
2986   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2987   switch (dops[i].opcode) {
2988   case 0x20: // LB
2989     if(!c||memtarget) {
2990       if(!dummy) {
2991         int a = tl;
2992         if (!c) a = addr;
2993         if (fastio_reg_override >= 0)
2994           a = fastio_reg_override;
2995
2996         if (offset_reg >= 0)
2997           emit_ldrsb_dualindexed(offset_reg, a, tl);
2998         else
2999           emit_movsbl_indexed(0, a, tl);
3000       }
3001       if(jaddr)
3002         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3003     }
3004     else
3005       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3006     break;
3007   case 0x21: // LH
3008     if(!c||memtarget) {
3009       if(!dummy) {
3010         int a = tl;
3011         if (!c) a = addr;
3012         if (fastio_reg_override >= 0)
3013           a = fastio_reg_override;
3014         if (offset_reg >= 0)
3015           emit_ldrsh_dualindexed(offset_reg, a, tl);
3016         else
3017           emit_movswl_indexed(0, a, tl);
3018       }
3019       if(jaddr)
3020         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3021     }
3022     else
3023       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3024     break;
3025   case 0x23: // LW
3026     if(!c||memtarget) {
3027       if(!dummy) {
3028         int a = addr;
3029         if (fastio_reg_override >= 0)
3030           a = fastio_reg_override;
3031         do_load_word(a, tl, offset_reg);
3032       }
3033       if(jaddr)
3034         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3035     }
3036     else
3037       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3038     break;
3039   case 0x24: // LBU
3040     if(!c||memtarget) {
3041       if(!dummy) {
3042         int a = tl;
3043         if (!c) a = addr;
3044         if (fastio_reg_override >= 0)
3045           a = fastio_reg_override;
3046
3047         if (offset_reg >= 0)
3048           emit_ldrb_dualindexed(offset_reg, a, tl);
3049         else
3050           emit_movzbl_indexed(0, a, tl);
3051       }
3052       if(jaddr)
3053         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3054     }
3055     else
3056       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3057     break;
3058   case 0x25: // LHU
3059     if(!c||memtarget) {
3060       if(!dummy) {
3061         int a = tl;
3062         if(!c) a = addr;
3063         if (fastio_reg_override >= 0)
3064           a = fastio_reg_override;
3065         if (offset_reg >= 0)
3066           emit_ldrh_dualindexed(offset_reg, a, tl);
3067         else
3068           emit_movzwl_indexed(0, a, tl);
3069       }
3070       if(jaddr)
3071         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3072     }
3073     else
3074       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3075     break;
3076   case 0x27: // LWU
3077   case 0x37: // LD
3078   default:
3079     assert(0);
3080   }
3081  }
3082  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3083    host_tempreg_release();
3084 }
3085
3086 #ifndef loadlr_assemble
3087 static void loadlr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3088 {
3089   int s,tl,temp,temp2,addr;
3090   int offset;
3091   void *jaddr=0;
3092   int memtarget=0,c=0;
3093   int offset_reg = -1;
3094   int fastio_reg_override = -1;
3095   u_int reglist=get_host_reglist(i_regs->regmap);
3096   tl=get_reg(i_regs->regmap,dops[i].rt1);
3097   s=get_reg(i_regs->regmap,dops[i].rs1);
3098   temp=get_reg_temp(i_regs->regmap);
3099   temp2=get_reg(i_regs->regmap,FTEMP);
3100   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
3101   assert(addr<0);
3102   offset=imm[i];
3103   reglist|=1<<temp;
3104   if(offset||s<0||c) addr=temp2;
3105   else addr=s;
3106   if(s>=0) {
3107     c=(i_regs->wasconst>>s)&1;
3108     if(c) {
3109       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3110     }
3111   }
3112   if(!c) {
3113     emit_shlimm(addr,3,temp);
3114     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3115       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
3116     }else{
3117       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
3118     }
3119     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
3120               &offset_reg, &fastio_reg_override);
3121   }
3122   else {
3123     if (ram_offset && memtarget) {
3124       offset_reg = get_ro_reg(i_regs, 0);
3125     }
3126     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3127       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
3128     }else{
3129       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
3130     }
3131   }
3132   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
3133     if(!c||memtarget) {
3134       int a = temp2;
3135       if (fastio_reg_override >= 0)
3136         a = fastio_reg_override;
3137       do_load_word(a, temp2, offset_reg);
3138       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3139         host_tempreg_release();
3140       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj_,reglist);
3141     }
3142     else
3143       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj_,reglist);
3144     if(dops[i].rt1) {
3145       assert(tl>=0);
3146       emit_andimm(temp,24,temp);
3147       if (dops[i].opcode==0x22) // LWL
3148         emit_xorimm(temp,24,temp);
3149       host_tempreg_acquire();
3150       emit_movimm(-1,HOST_TEMPREG);
3151       if (dops[i].opcode==0x26) {
3152         emit_shr(temp2,temp,temp2);
3153         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
3154       }else{
3155         emit_shl(temp2,temp,temp2);
3156         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
3157       }
3158       host_tempreg_release();
3159       emit_or(temp2,tl,tl);
3160     }
3161     //emit_storereg(dops[i].rt1,tl); // DEBUG
3162   }
3163   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
3164     assert(0);
3165   }
3166 }
3167 #endif
3168
3169 static void do_invstub(int n)
3170 {
3171   literal_pool(20);
3172   assem_debug("do_invstub\n");
3173   u_int reglist = stubs[n].a;
3174   u_int addrr = stubs[n].b;
3175   int ofs_start = stubs[n].c;
3176   int ofs_end = stubs[n].d;
3177   int len = ofs_end - ofs_start;
3178   u_int rightr = 0;
3179
3180   set_jump_target(stubs[n].addr, out);
3181   save_regs(reglist);
3182   if (addrr != 0 || ofs_start != 0)
3183     emit_addimm(addrr, ofs_start, 0);
3184   emit_readword(&inv_code_start, 2);
3185   emit_readword(&inv_code_end, 3);
3186   if (len != 0)
3187     emit_addimm(0, len + 4, (rightr = 1));
3188   emit_cmp(0, 2);
3189   emit_cmpcs(3, rightr);
3190   void *jaddr = out;
3191   emit_jc(0);
3192   void *func = (len != 0)
3193     ? (void *)ndrc_write_invalidate_many
3194     : (void *)ndrc_write_invalidate_one;
3195   emit_far_call(func);
3196   set_jump_target(jaddr, out);
3197   restore_regs(reglist);
3198   emit_jmp(stubs[n].retaddr);
3199 }
3200
3201 static void do_store_smc_check(int i, const struct regstat *i_regs, u_int reglist, int addr)
3202 {
3203   if (HACK_ENABLED(NDHACK_NO_SMC_CHECK))
3204     return;
3205   // this can't be used any more since we started to check exact
3206   // block boundaries in invalidate_range()
3207   //if (i_regs->waswritten & (1<<dops[i].rs1))
3208   //  return;
3209   // (naively) assume nobody will run code from stack
3210   if (dops[i].rs1 == 29)
3211     return;
3212
3213   int j, imm_maxdiff = 32, imm_min = imm[i], imm_max = imm[i], count = 1;
3214   if (i < slen - 1 && dops[i+1].is_store && dops[i+1].rs1 == dops[i].rs1
3215       && abs(imm[i+1] - imm[i]) <= imm_maxdiff)
3216     return;
3217   for (j = i - 1; j >= 0; j--) {
3218     if (!dops[j].is_store || dops[j].rs1 != dops[i].rs1
3219         || abs(imm[j] - imm[j+1]) > imm_maxdiff)
3220       break;
3221     count++;
3222     if (imm_min > imm[j])
3223       imm_min = imm[j];
3224     if (imm_max < imm[j])
3225       imm_max = imm[j];
3226   }
3227 #if defined(HOST_IMM8)
3228   int ir = get_reg(i_regs->regmap, INVCP);
3229   assert(ir >= 0);
3230   host_tempreg_acquire();
3231   emit_ldrb_indexedsr12_reg(ir, addr, HOST_TEMPREG);
3232 #else
3233   emit_cmpmem_indexedsr12_imm(invalid_code, addr, 1);
3234   #error not handled
3235 #endif
3236 #ifdef INVALIDATE_USE_COND_CALL
3237   if (count == 1) {
3238     emit_cmpimm(HOST_TEMPREG, 1);
3239     emit_callne(invalidate_addr_reg[addr]);
3240     host_tempreg_release();
3241     return;
3242   }
3243 #endif
3244   void *jaddr = emit_cbz(HOST_TEMPREG, 0);
3245   host_tempreg_release();
3246   imm_min -= imm[i];
3247   imm_max -= imm[i];
3248   add_stub(INVCODE_STUB, jaddr, out, reglist|(1<<HOST_CCREG),
3249     addr, imm_min, imm_max, 0);
3250 }
3251
3252 static void store_assemble(int i, const struct regstat *i_regs, int ccadj_)
3253 {
3254   int s,tl;
3255   int addr,temp;
3256   int offset;
3257   void *jaddr=0;
3258   enum stub_type type=0;
3259   int memtarget=0,c=0;
3260   int agr=AGEN1+(i&1);
3261   int offset_reg = -1;
3262   int fastio_reg_override = -1;
3263   u_int reglist=get_host_reglist(i_regs->regmap);
3264   tl=get_reg(i_regs->regmap,dops[i].rs2);
3265   s=get_reg(i_regs->regmap,dops[i].rs1);
3266   temp=get_reg(i_regs->regmap,agr);
3267   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3268   offset=imm[i];
3269   if(s>=0) {
3270     c=(i_regs->wasconst>>s)&1;
3271     if(c) {
3272       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3273     }
3274   }
3275   assert(tl>=0);
3276   assert(temp>=0);
3277   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
3278   if(offset||s<0||c) addr=temp;
3279   else addr=s;
3280   if (!c) {
3281     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3282               &offset_reg, &fastio_reg_override);
3283   }
3284   else if (ram_offset && memtarget) {
3285     offset_reg = get_ro_reg(i_regs, 0);
3286   }
3287
3288   switch (dops[i].opcode) {
3289   case 0x28: // SB
3290     if(!c||memtarget) {
3291       int a = temp;
3292       if (!c) a = addr;
3293       if (fastio_reg_override >= 0)
3294         a = fastio_reg_override;
3295       do_store_byte(a, tl, offset_reg);
3296     }
3297     type = STOREB_STUB;
3298     break;
3299   case 0x29: // SH
3300     if(!c||memtarget) {
3301       int a = temp;
3302       if (!c) a = addr;
3303       if (fastio_reg_override >= 0)
3304         a = fastio_reg_override;
3305       do_store_hword(a, 0, tl, offset_reg, 1);
3306     }
3307     type = STOREH_STUB;
3308     break;
3309   case 0x2B: // SW
3310     if(!c||memtarget) {
3311       int a = addr;
3312       if (fastio_reg_override >= 0)
3313         a = fastio_reg_override;
3314       do_store_word(a, 0, tl, offset_reg, 1);
3315     }
3316     type = STOREW_STUB;
3317     break;
3318   case 0x3F: // SD
3319   default:
3320     assert(0);
3321   }
3322   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3323     host_tempreg_release();
3324   if(jaddr) {
3325     // PCSX store handlers don't check invcode again
3326     reglist|=1<<addr;
3327     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3328     jaddr=0;
3329   }
3330   {
3331     if(!c||memtarget) {
3332       #ifdef DESTRUCTIVE_SHIFT
3333       // The x86 shift operation is 'destructive'; it overwrites the
3334       // source register, so we need to make a copy first and use that.
3335       addr=temp;
3336       #endif
3337       do_store_smc_check(i, i_regs, reglist, addr);
3338     }
3339   }
3340   u_int addr_val=constmap[i][s]+offset;
3341   if(jaddr) {
3342     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3343   } else if(c&&!memtarget) {
3344     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj_,reglist);
3345   }
3346   // basic current block modification detection..
3347   // not looking back as that should be in mips cache already
3348   // (see Spyro2 title->attract mode)
3349   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3350     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3351     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3352     if(i_regs->regmap==regs[i].regmap) {
3353       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3354       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3355       emit_movimm(start+i*4+4,0);
3356       emit_writeword(0,&pcaddr);
3357       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3358       emit_far_call(ndrc_get_addr_ht);
3359       emit_jmpreg(0);
3360     }
3361   }
3362 }
3363
3364 static void storelr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3365 {
3366   int s,tl;
3367   int temp;
3368   int offset;
3369   void *jaddr=0;
3370   void *case1, *case23, *case3;
3371   void *done0, *done1, *done2;
3372   int memtarget=0,c=0;
3373   int agr=AGEN1+(i&1);
3374   int offset_reg = -1;
3375   u_int reglist=get_host_reglist(i_regs->regmap);
3376   tl=get_reg(i_regs->regmap,dops[i].rs2);
3377   s=get_reg(i_regs->regmap,dops[i].rs1);
3378   temp=get_reg(i_regs->regmap,agr);
3379   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3380   offset=imm[i];
3381   if(s>=0) {
3382     c=(i_regs->isconst>>s)&1;
3383     if(c) {
3384       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3385     }
3386   }
3387   assert(tl>=0);
3388   assert(temp>=0);
3389   if(!c) {
3390     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3391     if(!offset&&s!=temp) emit_mov(s,temp);
3392     jaddr=out;
3393     emit_jno(0);
3394   }
3395   else
3396   {
3397     if(!memtarget||!dops[i].rs1) {
3398       jaddr=out;
3399       emit_jmp(0);
3400     }
3401   }
3402   if (ram_offset)
3403     offset_reg = get_ro_reg(i_regs, 0);
3404
3405   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3406     assert(0);
3407   }
3408
3409   emit_testimm(temp,2);
3410   case23=out;
3411   emit_jne(0);
3412   emit_testimm(temp,1);
3413   case1=out;
3414   emit_jne(0);
3415   // 0
3416   if (dops[i].opcode == 0x2A) { // SWL
3417     // Write msb into least significant byte
3418     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3419     do_store_byte(temp, tl, offset_reg);
3420     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3421   }
3422   else if (dops[i].opcode == 0x2E) { // SWR
3423     // Write entire word
3424     do_store_word(temp, 0, tl, offset_reg, 1);
3425   }
3426   done0 = out;
3427   emit_jmp(0);
3428   // 1
3429   set_jump_target(case1, out);
3430   if (dops[i].opcode == 0x2A) { // SWL
3431     // Write two msb into two least significant bytes
3432     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3433     do_store_hword(temp, -1, tl, offset_reg, 0);
3434     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3435   }
3436   else if (dops[i].opcode == 0x2E) { // SWR
3437     // Write 3 lsb into three most significant bytes
3438     do_store_byte(temp, tl, offset_reg);
3439     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3440     do_store_hword(temp, 1, tl, offset_reg, 0);
3441     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3442   }
3443   done1=out;
3444   emit_jmp(0);
3445   // 2,3
3446   set_jump_target(case23, out);
3447   emit_testimm(temp,1);
3448   case3 = out;
3449   emit_jne(0);
3450   // 2
3451   if (dops[i].opcode==0x2A) { // SWL
3452     // Write 3 msb into three least significant bytes
3453     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3454     do_store_hword(temp, -2, tl, offset_reg, 1);
3455     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3456     do_store_byte(temp, tl, offset_reg);
3457     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3458   }
3459   else if (dops[i].opcode == 0x2E) { // SWR
3460     // Write two lsb into two most significant bytes
3461     do_store_hword(temp, 0, tl, offset_reg, 1);
3462   }
3463   done2 = out;
3464   emit_jmp(0);
3465   // 3
3466   set_jump_target(case3, out);
3467   if (dops[i].opcode == 0x2A) { // SWL
3468     do_store_word(temp, -3, tl, offset_reg, 0);
3469   }
3470   else if (dops[i].opcode == 0x2E) { // SWR
3471     do_store_byte(temp, tl, offset_reg);
3472   }
3473   set_jump_target(done0, out);
3474   set_jump_target(done1, out);
3475   set_jump_target(done2, out);
3476   if (offset_reg == HOST_TEMPREG)
3477     host_tempreg_release();
3478   if(!c||!memtarget)
3479     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj_,reglist);
3480   do_store_smc_check(i, i_regs, reglist, temp);
3481 }
3482
3483 static void cop0_assemble(int i, const struct regstat *i_regs, int ccadj_)
3484 {
3485   if(dops[i].opcode2==0) // MFC0
3486   {
3487     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3488     u_int copr=(source[i]>>11)&0x1f;
3489     //assert(t>=0); // Why does this happen?  OOT is weird
3490     if(t>=0&&dops[i].rt1!=0) {
3491       emit_readword(&reg_cop0[copr],t);
3492     }
3493   }
3494   else if(dops[i].opcode2==4) // MTC0
3495   {
3496     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3497     char copr=(source[i]>>11)&0x1f;
3498     assert(s>=0);
3499     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3500     if(copr==9||copr==11||copr==12||copr==13) {
3501       emit_readword(&last_count,HOST_TEMPREG);
3502       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3503       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3504       emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3505       emit_writeword(HOST_CCREG,&Count);
3506     }
3507     // What a mess.  The status register (12) can enable interrupts,
3508     // so needs a special case to handle a pending interrupt.
3509     // The interrupt must be taken immediately, because a subsequent
3510     // instruction might disable interrupts again.
3511     if(copr==12||copr==13) {
3512       if (is_delayslot) {
3513         // burn cycles to cause cc_interrupt, which will
3514         // reschedule next_interupt. Relies on CCREG from above.
3515         assem_debug("MTC0 DS %d\n", copr);
3516         emit_writeword(HOST_CCREG,&last_count);
3517         emit_movimm(0,HOST_CCREG);
3518         emit_storereg(CCREG,HOST_CCREG);
3519         emit_loadreg(dops[i].rs1,1);
3520         emit_movimm(copr,0);
3521         emit_far_call(pcsx_mtc0_ds);
3522         emit_loadreg(dops[i].rs1,s);
3523         return;
3524       }
3525       emit_movimm(start+i*4+4,HOST_TEMPREG);
3526       emit_writeword(HOST_TEMPREG,&pcaddr);
3527       emit_movimm(0,HOST_TEMPREG);
3528       emit_writeword(HOST_TEMPREG,&pending_exception);
3529     }
3530     if(s==HOST_CCREG)
3531       emit_loadreg(dops[i].rs1,1);
3532     else if(s!=1)
3533       emit_mov(s,1);
3534     emit_movimm(copr,0);
3535     emit_far_call(pcsx_mtc0);
3536     if(copr==9||copr==11||copr==12||copr==13) {
3537       emit_readword(&Count,HOST_CCREG);
3538       emit_readword(&next_interupt,HOST_TEMPREG);
3539       emit_addimm(HOST_CCREG,-ccadj_,HOST_CCREG);
3540       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3541       emit_writeword(HOST_TEMPREG,&last_count);
3542       emit_storereg(CCREG,HOST_CCREG);
3543     }
3544     if(copr==12||copr==13) {
3545       assert(!is_delayslot);
3546       emit_readword(&pending_exception,HOST_TEMPREG);
3547       emit_test(HOST_TEMPREG,HOST_TEMPREG);
3548       void *jaddr = out;
3549       emit_jeq(0);
3550       emit_readword(&pcaddr, 0);
3551       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3552       emit_far_call(ndrc_get_addr_ht);
3553       emit_jmpreg(0);
3554       set_jump_target(jaddr, out);
3555     }
3556     emit_loadreg(dops[i].rs1,s);
3557   }
3558   else
3559   {
3560     assert(dops[i].opcode2==0x10);
3561     //if((source[i]&0x3f)==0x10) // RFE
3562     {
3563       emit_readword(&Status,0);
3564       emit_andimm(0,0x3c,1);
3565       emit_andimm(0,~0xf,0);
3566       emit_orrshr_imm(1,2,0);
3567       emit_writeword(0,&Status);
3568     }
3569   }
3570 }
3571
3572 static void cop1_unusable(int i, const struct regstat *i_regs)
3573 {
3574   // XXX: should just just do the exception instead
3575   //if(!cop1_usable)
3576   {
3577     void *jaddr=out;
3578     emit_jmp(0);
3579     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3580   }
3581 }
3582
3583 static void cop1_assemble(int i, const struct regstat *i_regs)
3584 {
3585   cop1_unusable(i, i_regs);
3586 }
3587
3588 static void c1ls_assemble(int i, const struct regstat *i_regs)
3589 {
3590   cop1_unusable(i, i_regs);
3591 }
3592
3593 // FP_STUB
3594 static void do_cop1stub(int n)
3595 {
3596   literal_pool(256);
3597   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3598   set_jump_target(stubs[n].addr, out);
3599   int i=stubs[n].a;
3600 //  int rs=stubs[n].b;
3601   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3602   int ds=stubs[n].d;
3603   if(!ds) {
3604     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3605     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3606   }
3607   //else {printf("fp exception in delay slot\n");}
3608   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3609   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3610   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3611   emit_addimm(HOST_CCREG,ccadj[i],HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3612   emit_far_jump(ds?fp_exception_ds:fp_exception);
3613 }
3614
3615 static int cop2_is_stalling_op(int i, int *cycles)
3616 {
3617   if (dops[i].opcode == 0x3a) { // SWC2
3618     *cycles = 0;
3619     return 1;
3620   }
3621   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3622     *cycles = 0;
3623     return 1;
3624   }
3625   if (dops[i].itype == C2OP) {
3626     *cycles = gte_cycletab[source[i] & 0x3f];
3627     return 1;
3628   }
3629   // ... what about MTC2/CTC2/LWC2?
3630   return 0;
3631 }
3632
3633 #if 0
3634 static void log_gte_stall(int stall, u_int cycle)
3635 {
3636   if ((u_int)stall <= 44)
3637     printf("x    stall %2d %u\n", stall, cycle + last_count);
3638 }
3639
3640 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3641 {
3642   save_regs(reglist);
3643   if (stall > 0)
3644     emit_movimm(stall, 0);
3645   else
3646     emit_mov(HOST_TEMPREG, 0);
3647   emit_addimm(HOST_CCREG, ccadj[i], 1);
3648   emit_far_call(log_gte_stall);
3649   restore_regs(reglist);
3650 }
3651 #endif
3652
3653 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3654 {
3655   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3656   int rtmp = reglist_find_free(reglist);
3657
3658   if (HACK_ENABLED(NDHACK_NO_STALLS))
3659     return;
3660   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3661     // happens occasionally... cc evicted? Don't bother then
3662     //printf("no cc %08x\n", start + i*4);
3663     return;
3664   }
3665   if (!dops[i].bt) {
3666     for (j = i - 1; j >= 0; j--) {
3667       //if (dops[j].is_ds) break;
3668       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3669         break;
3670       if (j > 0 && ccadj[j - 1] > ccadj[j])
3671         break;
3672     }
3673     j = max(j, 0);
3674   }
3675   cycles_passed = ccadj[i] - ccadj[j];
3676   if (other_gte_op_cycles >= 0)
3677     stall = other_gte_op_cycles - cycles_passed;
3678   else if (cycles_passed >= 44)
3679     stall = 0; // can't stall
3680   if (stall == -MAXBLOCK && rtmp >= 0) {
3681     // unknown stall, do the expensive runtime check
3682     assem_debug("; cop2_do_stall_check\n");
3683 #if 0 // too slow
3684     save_regs(reglist);
3685     emit_movimm(gte_cycletab[op], 0);
3686     emit_addimm(HOST_CCREG, ccadj[i], 1);
3687     emit_far_call(call_gteStall);
3688     restore_regs(reglist);
3689 #else
3690     host_tempreg_acquire();
3691     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3692     emit_addimm(rtmp, -ccadj[i], rtmp);
3693     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3694     emit_cmpimm(HOST_TEMPREG, 44);
3695     emit_cmovb_reg(rtmp, HOST_CCREG);
3696     //emit_log_gte_stall(i, 0, reglist);
3697     host_tempreg_release();
3698 #endif
3699   }
3700   else if (stall > 0) {
3701     //emit_log_gte_stall(i, stall, reglist);
3702     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3703   }
3704
3705   // save gteBusyCycle, if needed
3706   if (gte_cycletab[op] == 0)
3707     return;
3708   other_gte_op_cycles = -1;
3709   for (j = i + 1; j < slen; j++) {
3710     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3711       break;
3712     if (dops[j].is_jump) {
3713       // check ds
3714       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3715         j++;
3716       break;
3717     }
3718   }
3719   if (other_gte_op_cycles >= 0)
3720     // will handle stall when assembling that op
3721     return;
3722   cycles_passed = ccadj[min(j, slen -1)] - ccadj[i];
3723   if (cycles_passed >= 44)
3724     return;
3725   assem_debug("; save gteBusyCycle\n");
3726   host_tempreg_acquire();
3727 #if 0
3728   emit_readword(&last_count, HOST_TEMPREG);
3729   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3730   emit_addimm(HOST_TEMPREG, ccadj[i], HOST_TEMPREG);
3731   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3732   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3733 #else
3734   emit_addimm(HOST_CCREG, ccadj[i] + gte_cycletab[op], HOST_TEMPREG);
3735   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3736 #endif
3737   host_tempreg_release();
3738 }
3739
3740 static int is_mflohi(int i)
3741 {
3742   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3743 }
3744
3745 static int check_multdiv(int i, int *cycles)
3746 {
3747   if (dops[i].itype != MULTDIV)
3748     return 0;
3749   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3750     *cycles = 11; // approx from 7 11 14
3751   else
3752     *cycles = 37;
3753   return 1;
3754 }
3755
3756 static void multdiv_prepare_stall(int i, const struct regstat *i_regs, int ccadj_)
3757 {
3758   int j, found = 0, c = 0;
3759   if (HACK_ENABLED(NDHACK_NO_STALLS))
3760     return;
3761   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3762     // happens occasionally... cc evicted? Don't bother then
3763     return;
3764   }
3765   for (j = i + 1; j < slen; j++) {
3766     if (dops[j].bt)
3767       break;
3768     if ((found = is_mflohi(j)))
3769       break;
3770     if (dops[j].is_jump) {
3771       // check ds
3772       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3773         j++;
3774       break;
3775     }
3776   }
3777   if (found)
3778     // handle all in multdiv_do_stall()
3779     return;
3780   check_multdiv(i, &c);
3781   assert(c > 0);
3782   assem_debug("; muldiv prepare stall %d\n", c);
3783   host_tempreg_acquire();
3784   emit_addimm(HOST_CCREG, ccadj_ + c, HOST_TEMPREG);
3785   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3786   host_tempreg_release();
3787 }
3788
3789 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3790 {
3791   int j, known_cycles = 0;
3792   u_int reglist = get_host_reglist(i_regs->regmap);
3793   int rtmp = get_reg_temp(i_regs->regmap);
3794   if (rtmp < 0)
3795     rtmp = reglist_find_free(reglist);
3796   if (HACK_ENABLED(NDHACK_NO_STALLS))
3797     return;
3798   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3799     // happens occasionally... cc evicted? Don't bother then
3800     //printf("no cc/rtmp %08x\n", start + i*4);
3801     return;
3802   }
3803   if (!dops[i].bt) {
3804     for (j = i - 1; j >= 0; j--) {
3805       if (dops[j].is_ds) break;
3806       if (check_multdiv(j, &known_cycles))
3807         break;
3808       if (is_mflohi(j))
3809         // already handled by this op
3810         return;
3811       if (dops[j].bt || (j > 0 && ccadj[j - 1] > ccadj[j]))
3812         break;
3813     }
3814     j = max(j, 0);
3815   }
3816   if (known_cycles > 0) {
3817     known_cycles -= ccadj[i] - ccadj[j];
3818     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3819     if (known_cycles > 0)
3820       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3821     return;
3822   }
3823   assem_debug("; muldiv stall unresolved\n");
3824   host_tempreg_acquire();
3825   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3826   emit_addimm(rtmp, -ccadj[i], rtmp);
3827   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3828   emit_cmpimm(HOST_TEMPREG, 37);
3829   emit_cmovb_reg(rtmp, HOST_CCREG);
3830   //emit_log_gte_stall(i, 0, reglist);
3831   host_tempreg_release();
3832 }
3833
3834 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3835 {
3836   switch (copr) {
3837     case 1:
3838     case 3:
3839     case 5:
3840     case 8:
3841     case 9:
3842     case 10:
3843     case 11:
3844       emit_readword(&reg_cop2d[copr],tl);
3845       emit_signextend16(tl,tl);
3846       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3847       break;
3848     case 7:
3849     case 16:
3850     case 17:
3851     case 18:
3852     case 19:
3853       emit_readword(&reg_cop2d[copr],tl);
3854       emit_andimm(tl,0xffff,tl);
3855       emit_writeword(tl,&reg_cop2d[copr]);
3856       break;
3857     case 15:
3858       emit_readword(&reg_cop2d[14],tl); // SXY2
3859       emit_writeword(tl,&reg_cop2d[copr]);
3860       break;
3861     case 28:
3862     case 29:
3863       c2op_mfc2_29_assemble(tl,temp);
3864       break;
3865     default:
3866       emit_readword(&reg_cop2d[copr],tl);
3867       break;
3868   }
3869 }
3870
3871 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3872 {
3873   switch (copr) {
3874     case 15:
3875       emit_readword(&reg_cop2d[13],temp);  // SXY1
3876       emit_writeword(sl,&reg_cop2d[copr]);
3877       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3878       emit_readword(&reg_cop2d[14],temp);  // SXY2
3879       emit_writeword(sl,&reg_cop2d[14]);
3880       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3881       break;
3882     case 28:
3883       emit_andimm(sl,0x001f,temp);
3884       emit_shlimm(temp,7,temp);
3885       emit_writeword(temp,&reg_cop2d[9]);
3886       emit_andimm(sl,0x03e0,temp);
3887       emit_shlimm(temp,2,temp);
3888       emit_writeword(temp,&reg_cop2d[10]);
3889       emit_andimm(sl,0x7c00,temp);
3890       emit_shrimm(temp,3,temp);
3891       emit_writeword(temp,&reg_cop2d[11]);
3892       emit_writeword(sl,&reg_cop2d[28]);
3893       break;
3894     case 30:
3895       emit_xorsar_imm(sl,sl,31,temp);
3896 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3897       emit_clz(temp,temp);
3898 #else
3899       emit_movs(temp,HOST_TEMPREG);
3900       emit_movimm(0,temp);
3901       emit_jeq((int)out+4*4);
3902       emit_addpl_imm(temp,1,temp);
3903       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3904       emit_jns((int)out-2*4);
3905 #endif
3906       emit_writeword(sl,&reg_cop2d[30]);
3907       emit_writeword(temp,&reg_cop2d[31]);
3908       break;
3909     case 31:
3910       break;
3911     default:
3912       emit_writeword(sl,&reg_cop2d[copr]);
3913       break;
3914   }
3915 }
3916
3917 static void c2ls_assemble(int i, const struct regstat *i_regs, int ccadj_)
3918 {
3919   int s,tl;
3920   int ar;
3921   int offset;
3922   int memtarget=0,c=0;
3923   void *jaddr2=NULL;
3924   enum stub_type type;
3925   int agr=AGEN1+(i&1);
3926   int offset_reg = -1;
3927   int fastio_reg_override = -1;
3928   u_int reglist=get_host_reglist(i_regs->regmap);
3929   u_int copr=(source[i]>>16)&0x1f;
3930   s=get_reg(i_regs->regmap,dops[i].rs1);
3931   tl=get_reg(i_regs->regmap,FTEMP);
3932   offset=imm[i];
3933   assert(dops[i].rs1>0);
3934   assert(tl>=0);
3935
3936   if(i_regs->regmap[HOST_CCREG]==CCREG)
3937     reglist&=~(1<<HOST_CCREG);
3938
3939   // get the address
3940   if (dops[i].opcode==0x3a) { // SWC2
3941     ar=get_reg(i_regs->regmap,agr);
3942     if(ar<0) ar=get_reg_temp(i_regs->regmap);
3943     reglist|=1<<ar;
3944   } else { // LWC2
3945     ar=tl;
3946   }
3947   if(s>=0) c=(i_regs->wasconst>>s)&1;
3948   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3949   if (!offset&&!c&&s>=0) ar=s;
3950   assert(ar>=0);
3951
3952   cop2_do_stall_check(0, i, i_regs, reglist);
3953
3954   if (dops[i].opcode==0x3a) { // SWC2
3955     cop2_get_dreg(copr,tl,-1);
3956     type=STOREW_STUB;
3957   }
3958   else
3959     type=LOADW_STUB;
3960
3961   if(c&&!memtarget) {
3962     jaddr2=out;
3963     emit_jmp(0); // inline_readstub/inline_writestub?
3964   }
3965   else {
3966     if(!c) {
3967       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3968                 &offset_reg, &fastio_reg_override);
3969     }
3970     else if (ram_offset && memtarget) {
3971       offset_reg = get_ro_reg(i_regs, 0);
3972     }
3973     switch (dops[i].opcode) {
3974     case 0x32: { // LWC2
3975       int a = ar;
3976       if (fastio_reg_override >= 0)
3977         a = fastio_reg_override;
3978       do_load_word(a, tl, offset_reg);
3979       break;
3980     }
3981     case 0x3a: { // SWC2
3982       #ifdef DESTRUCTIVE_SHIFT
3983       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3984       #endif
3985       int a = ar;
3986       if (fastio_reg_override >= 0)
3987         a = fastio_reg_override;
3988       do_store_word(a, 0, tl, offset_reg, 1);
3989       break;
3990     }
3991     default:
3992       assert(0);
3993     }
3994   }
3995   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3996     host_tempreg_release();
3997   if(jaddr2)
3998     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj_,reglist);
3999   if(dops[i].opcode==0x3a) // SWC2
4000     do_store_smc_check(i, i_regs, reglist, ar);
4001   if (dops[i].opcode==0x32) { // LWC2
4002     host_tempreg_acquire();
4003     cop2_put_dreg(copr,tl,HOST_TEMPREG);
4004     host_tempreg_release();
4005   }
4006 }
4007
4008 static void cop2_assemble(int i, const struct regstat *i_regs)
4009 {
4010   u_int copr = (source[i]>>11) & 0x1f;
4011   signed char temp = get_reg_temp(i_regs->regmap);
4012
4013   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
4014     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
4015     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
4016       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
4017       reglist = reglist_exclude(reglist, tl, -1);
4018     }
4019     cop2_do_stall_check(0, i, i_regs, reglist);
4020   }
4021   if (dops[i].opcode2==0) { // MFC2
4022     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
4023     if(tl>=0&&dops[i].rt1!=0)
4024       cop2_get_dreg(copr,tl,temp);
4025   }
4026   else if (dops[i].opcode2==4) { // MTC2
4027     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
4028     cop2_put_dreg(copr,sl,temp);
4029   }
4030   else if (dops[i].opcode2==2) // CFC2
4031   {
4032     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
4033     if(tl>=0&&dops[i].rt1!=0)
4034       emit_readword(&reg_cop2c[copr],tl);
4035   }
4036   else if (dops[i].opcode2==6) // CTC2
4037   {
4038     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
4039     switch(copr) {
4040       case 4:
4041       case 12:
4042       case 20:
4043       case 26:
4044       case 27:
4045       case 29:
4046       case 30:
4047         emit_signextend16(sl,temp);
4048         break;
4049       case 31:
4050         c2op_ctc2_31_assemble(sl,temp);
4051         break;
4052       default:
4053         temp=sl;
4054         break;
4055     }
4056     emit_writeword(temp,&reg_cop2c[copr]);
4057     assert(sl>=0);
4058   }
4059 }
4060
4061 static void do_unalignedwritestub(int n)
4062 {
4063   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
4064   literal_pool(256);
4065   set_jump_target(stubs[n].addr, out);
4066
4067   int i=stubs[n].a;
4068   struct regstat *i_regs=(struct regstat *)stubs[n].c;
4069   int addr=stubs[n].b;
4070   u_int reglist=stubs[n].e;
4071   signed char *i_regmap=i_regs->regmap;
4072   int temp2=get_reg(i_regmap,FTEMP);
4073   int rt;
4074   rt=get_reg(i_regmap,dops[i].rs2);
4075   assert(rt>=0);
4076   assert(addr>=0);
4077   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
4078   reglist|=(1<<addr);
4079   reglist&=~(1<<temp2);
4080
4081   // don't bother with it and call write handler
4082   save_regs(reglist);
4083   pass_args(addr,rt);
4084   int cc=get_reg(i_regmap,CCREG);
4085   if(cc<0)
4086     emit_loadreg(CCREG,2);
4087   emit_addimm(cc<0?2:cc,(int)stubs[n].d+1,2);
4088   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
4089   emit_addimm(0,-((int)stubs[n].d+1),cc<0?2:cc);
4090   if(cc<0)
4091     emit_storereg(CCREG,2);
4092   restore_regs(reglist);
4093   emit_jmp(stubs[n].retaddr); // return address
4094 }
4095
4096 #ifndef multdiv_assemble
4097 void multdiv_assemble(int i,struct regstat *i_regs)
4098 {
4099   printf("Need multdiv_assemble for this architecture.\n");
4100   abort();
4101 }
4102 #endif
4103
4104 static void mov_assemble(int i, const struct regstat *i_regs)
4105 {
4106   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
4107   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
4108   if(dops[i].rt1) {
4109     signed char sl,tl;
4110     tl=get_reg(i_regs->regmap,dops[i].rt1);
4111     //assert(tl>=0);
4112     if(tl>=0) {
4113       sl=get_reg(i_regs->regmap,dops[i].rs1);
4114       if(sl>=0) emit_mov(sl,tl);
4115       else emit_loadreg(dops[i].rs1,tl);
4116     }
4117   }
4118   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
4119     multdiv_do_stall(i, i_regs);
4120 }
4121
4122 // call interpreter, exception handler, things that change pc/regs/cycles ...
4123 static void call_c_cpu_handler(int i, const struct regstat *i_regs, int ccadj_, u_int pc, void *func)
4124 {
4125   signed char ccreg=get_reg(i_regs->regmap,CCREG);
4126   assert(ccreg==HOST_CCREG);
4127   assert(!is_delayslot);
4128   (void)ccreg;
4129
4130   emit_movimm(pc,3); // Get PC
4131   emit_readword(&last_count,2);
4132   emit_writeword(3,&psxRegs.pc);
4133   emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
4134   emit_add(2,HOST_CCREG,2);
4135   emit_writeword(2,&psxRegs.cycle);
4136   emit_far_call(func);
4137   emit_far_jump(jump_to_new_pc);
4138 }
4139
4140 static void syscall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4141 {
4142   // 'break' tends to be littered around to catch things like
4143   // division by 0 and is almost never executed, so don't emit much code here
4144   void *func = (dops[i].opcode2 == 0x0C)
4145     ? (is_delayslot ? jump_syscall_ds : jump_syscall)
4146     : (is_delayslot ? jump_break_ds : jump_break);
4147   assert(get_reg(i_regs->regmap, CCREG) == HOST_CCREG);
4148   emit_movimm(start + i*4, 2); // pc
4149   emit_addimm(HOST_CCREG, ccadj_ + CLOCK_ADJUST(1), HOST_CCREG);
4150   emit_far_jump(func);
4151 }
4152
4153 static void hlecall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4154 {
4155   void *hlefunc = psxNULL;
4156   uint32_t hleCode = source[i] & 0x03ffffff;
4157   if (hleCode < ARRAY_SIZE(psxHLEt))
4158     hlefunc = psxHLEt[hleCode];
4159
4160   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4+4, hlefunc);
4161 }
4162
4163 static void intcall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4164 {
4165   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4, execI);
4166 }
4167
4168 static void speculate_mov(int rs,int rt)
4169 {
4170   if(rt!=0) {
4171     smrv_strong_next|=1<<rt;
4172     smrv[rt]=smrv[rs];
4173   }
4174 }
4175
4176 static void speculate_mov_weak(int rs,int rt)
4177 {
4178   if(rt!=0) {
4179     smrv_weak_next|=1<<rt;
4180     smrv[rt]=smrv[rs];
4181   }
4182 }
4183
4184 static void speculate_register_values(int i)
4185 {
4186   if(i==0) {
4187     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
4188     // gp,sp are likely to stay the same throughout the block
4189     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
4190     smrv_weak_next=~smrv_strong_next;
4191     //printf(" llr %08x\n", smrv[4]);
4192   }
4193   smrv_strong=smrv_strong_next;
4194   smrv_weak=smrv_weak_next;
4195   switch(dops[i].itype) {
4196     case ALU:
4197       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4198       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
4199       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4200       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
4201       else {
4202         smrv_strong_next&=~(1<<dops[i].rt1);
4203         smrv_weak_next&=~(1<<dops[i].rt1);
4204       }
4205       break;
4206     case SHIFTIMM:
4207       smrv_strong_next&=~(1<<dops[i].rt1);
4208       smrv_weak_next&=~(1<<dops[i].rt1);
4209       // fallthrough
4210     case IMM16:
4211       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
4212         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
4213         if(hr>=0) {
4214           if(get_final_value(hr,i,&value))
4215                smrv[dops[i].rt1]=value;
4216           else smrv[dops[i].rt1]=constmap[i][hr];
4217           smrv_strong_next|=1<<dops[i].rt1;
4218         }
4219       }
4220       else {
4221         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4222         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4223       }
4224       break;
4225     case LOAD:
4226       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
4227         // special case for BIOS
4228         smrv[dops[i].rt1]=0xa0000000;
4229         smrv_strong_next|=1<<dops[i].rt1;
4230         break;
4231       }
4232       // fallthrough
4233     case SHIFT:
4234     case LOADLR:
4235     case MOV:
4236       smrv_strong_next&=~(1<<dops[i].rt1);
4237       smrv_weak_next&=~(1<<dops[i].rt1);
4238       break;
4239     case COP0:
4240     case COP2:
4241       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
4242         smrv_strong_next&=~(1<<dops[i].rt1);
4243         smrv_weak_next&=~(1<<dops[i].rt1);
4244       }
4245       break;
4246     case C2LS:
4247       if (dops[i].opcode==0x32) { // LWC2
4248         smrv_strong_next&=~(1<<dops[i].rt1);
4249         smrv_weak_next&=~(1<<dops[i].rt1);
4250       }
4251       break;
4252   }
4253 #if 0
4254   int r=4;
4255   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4256     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4257 #endif
4258 }
4259
4260 static void ujump_assemble(int i, const struct regstat *i_regs);
4261 static void rjump_assemble(int i, const struct regstat *i_regs);
4262 static void cjump_assemble(int i, const struct regstat *i_regs);
4263 static void sjump_assemble(int i, const struct regstat *i_regs);
4264
4265 static int assemble(int i, const struct regstat *i_regs, int ccadj_)
4266 {
4267   int ds = 0;
4268   switch (dops[i].itype) {
4269     case ALU:
4270       alu_assemble(i, i_regs);
4271       break;
4272     case IMM16:
4273       imm16_assemble(i, i_regs);
4274       break;
4275     case SHIFT:
4276       shift_assemble(i, i_regs);
4277       break;
4278     case SHIFTIMM:
4279       shiftimm_assemble(i, i_regs);
4280       break;
4281     case LOAD:
4282       load_assemble(i, i_regs, ccadj_);
4283       break;
4284     case LOADLR:
4285       loadlr_assemble(i, i_regs, ccadj_);
4286       break;
4287     case STORE:
4288       store_assemble(i, i_regs, ccadj_);
4289       break;
4290     case STORELR:
4291       storelr_assemble(i, i_regs, ccadj_);
4292       break;
4293     case COP0:
4294       cop0_assemble(i, i_regs, ccadj_);
4295       break;
4296     case COP1:
4297       cop1_assemble(i, i_regs);
4298       break;
4299     case C1LS:
4300       c1ls_assemble(i, i_regs);
4301       break;
4302     case COP2:
4303       cop2_assemble(i, i_regs);
4304       break;
4305     case C2LS:
4306       c2ls_assemble(i, i_regs, ccadj_);
4307       break;
4308     case C2OP:
4309       c2op_assemble(i, i_regs);
4310       break;
4311     case MULTDIV:
4312       multdiv_assemble(i, i_regs);
4313       multdiv_prepare_stall(i, i_regs, ccadj_);
4314       break;
4315     case MOV:
4316       mov_assemble(i, i_regs);
4317       break;
4318     case SYSCALL:
4319       syscall_assemble(i, i_regs, ccadj_);
4320       break;
4321     case HLECALL:
4322       hlecall_assemble(i, i_regs, ccadj_);
4323       break;
4324     case INTCALL:
4325       intcall_assemble(i, i_regs, ccadj_);
4326       break;
4327     case UJUMP:
4328       ujump_assemble(i, i_regs);
4329       ds = 1;
4330       break;
4331     case RJUMP:
4332       rjump_assemble(i, i_regs);
4333       ds = 1;
4334       break;
4335     case CJUMP:
4336       cjump_assemble(i, i_regs);
4337       ds = 1;
4338       break;
4339     case SJUMP:
4340       sjump_assemble(i, i_regs);
4341       ds = 1;
4342       break;
4343     case NOP:
4344     case OTHER:
4345     case NI:
4346       // not handled, just skip
4347       break;
4348     default:
4349       assert(0);
4350   }
4351   return ds;
4352 }
4353
4354 static void ds_assemble(int i, const struct regstat *i_regs)
4355 {
4356   speculate_register_values(i);
4357   is_delayslot = 1;
4358   switch (dops[i].itype) {
4359     case SYSCALL:
4360     case HLECALL:
4361     case INTCALL:
4362     case UJUMP:
4363     case RJUMP:
4364     case CJUMP:
4365     case SJUMP:
4366       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4367       break;
4368     default:
4369       assemble(i, i_regs, ccadj[i]);
4370   }
4371   is_delayslot = 0;
4372 }
4373
4374 // Is the branch target a valid internal jump?
4375 static int internal_branch(int addr)
4376 {
4377   if(addr&1) return 0; // Indirect (register) jump
4378   if(addr>=start && addr<start+slen*4-4)
4379   {
4380     return 1;
4381   }
4382   return 0;
4383 }
4384
4385 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4386 {
4387   int hr;
4388   for(hr=0;hr<HOST_REGS;hr++) {
4389     if(hr!=EXCLUDE_REG) {
4390       if(pre[hr]!=entry[hr]) {
4391         if(pre[hr]>=0) {
4392           if((dirty>>hr)&1) {
4393             if(get_reg(entry,pre[hr])<0) {
4394               assert(pre[hr]<64);
4395               if(!((u>>pre[hr])&1))
4396                 emit_storereg(pre[hr],hr);
4397             }
4398           }
4399         }
4400       }
4401     }
4402   }
4403   // Move from one register to another (no writeback)
4404   for(hr=0;hr<HOST_REGS;hr++) {
4405     if(hr!=EXCLUDE_REG) {
4406       if(pre[hr]!=entry[hr]) {
4407         if(pre[hr]>=0&&pre[hr]<TEMPREG) {
4408           int nr;
4409           if((nr=get_reg(entry,pre[hr]))>=0) {
4410             emit_mov(hr,nr);
4411           }
4412         }
4413       }
4414     }
4415   }
4416 }
4417
4418 // Load the specified registers
4419 // This only loads the registers given as arguments because
4420 // we don't want to load things that will be overwritten
4421 static inline void load_reg(signed char entry[], signed char regmap[], int rs)
4422 {
4423   int hr = get_reg(regmap, rs);
4424   if (hr >= 0 && entry[hr] != regmap[hr])
4425     emit_loadreg(regmap[hr], hr);
4426 }
4427
4428 static void load_regs(signed char entry[], signed char regmap[], int rs1, int rs2)
4429 {
4430   load_reg(entry, regmap, rs1);
4431   if (rs1 != rs2)
4432     load_reg(entry, regmap, rs2);
4433 }
4434
4435 // Load registers prior to the start of a loop
4436 // so that they are not loaded within the loop
4437 static void loop_preload(signed char pre[],signed char entry[])
4438 {
4439   int hr;
4440   for (hr = 0; hr < HOST_REGS; hr++) {
4441     int r = entry[hr];
4442     if (r >= 0 && pre[hr] != r && get_reg(pre, r) < 0) {
4443       assem_debug("loop preload:\n");
4444       if (r < TEMPREG)
4445         emit_loadreg(r, hr);
4446     }
4447   }
4448 }
4449
4450 // Generate address for load/store instruction
4451 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4452 static void address_generation(int i, const struct regstat *i_regs, signed char entry[])
4453 {
4454   if (dops[i].is_load || dops[i].is_store) {
4455     int ra=-1;
4456     int agr=AGEN1+(i&1);
4457     if(dops[i].itype==LOAD) {
4458       ra=get_reg(i_regs->regmap,dops[i].rt1);
4459       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4460       assert(ra>=0);
4461     }
4462     if(dops[i].itype==LOADLR) {
4463       ra=get_reg(i_regs->regmap,FTEMP);
4464     }
4465     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4466       ra=get_reg(i_regs->regmap,agr);
4467       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4468     }
4469     if(dops[i].itype==C2LS) {
4470       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4471         ra=get_reg(i_regs->regmap,FTEMP);
4472       else { // SWC1/SDC1/SWC2/SDC2
4473         ra=get_reg(i_regs->regmap,agr);
4474         if(ra<0) ra=get_reg_temp(i_regs->regmap);
4475       }
4476     }
4477     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4478     if(ra>=0) {
4479       int offset=imm[i];
4480       int c=(i_regs->wasconst>>rs)&1;
4481       if(dops[i].rs1==0) {
4482         // Using r0 as a base address
4483         if(!entry||entry[ra]!=agr) {
4484           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4485             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4486           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4487             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4488           }else{
4489             emit_movimm(offset,ra);
4490           }
4491         } // else did it in the previous cycle
4492       }
4493       else if(rs<0) {
4494         if(!entry||entry[ra]!=dops[i].rs1)
4495           emit_loadreg(dops[i].rs1,ra);
4496         //if(!entry||entry[ra]!=dops[i].rs1)
4497         //  printf("poor load scheduling!\n");
4498       }
4499       else if(c) {
4500         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4501           if(!entry||entry[ra]!=agr) {
4502             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4503               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4504             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4505               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4506             }else{
4507               emit_movimm(constmap[i][rs]+offset,ra);
4508               regs[i].loadedconst|=1<<ra;
4509             }
4510           } // else did it in the previous cycle
4511         } // else load_consts already did it
4512       }
4513       if(offset&&!c&&dops[i].rs1) {
4514         if(rs>=0) {
4515           emit_addimm(rs,offset,ra);
4516         }else{
4517           emit_addimm(ra,offset,ra);
4518         }
4519       }
4520     }
4521   }
4522   // Preload constants for next instruction
4523   if (dops[i+1].is_load || dops[i+1].is_store) {
4524     int agr,ra;
4525     // Actual address
4526     agr=AGEN1+((i+1)&1);
4527     ra=get_reg(i_regs->regmap,agr);
4528     if(ra>=0) {
4529       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4530       int offset=imm[i+1];
4531       int c=(regs[i+1].wasconst>>rs)&1;
4532       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4533         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4534           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4535         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4536           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4537         }else{
4538           emit_movimm(constmap[i+1][rs]+offset,ra);
4539           regs[i+1].loadedconst|=1<<ra;
4540         }
4541       }
4542       else if(dops[i+1].rs1==0) {
4543         // Using r0 as a base address
4544         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4545           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4546         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4547           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4548         }else{
4549           emit_movimm(offset,ra);
4550         }
4551       }
4552     }
4553   }
4554 }
4555
4556 static int get_final_value(int hr, int i, int *value)
4557 {
4558   int reg=regs[i].regmap[hr];
4559   while(i<slen-1) {
4560     if(regs[i+1].regmap[hr]!=reg) break;
4561     if(!((regs[i+1].isconst>>hr)&1)) break;
4562     if(dops[i+1].bt) break;
4563     i++;
4564   }
4565   if(i<slen-1) {
4566     if (dops[i].is_jump) {
4567       *value=constmap[i][hr];
4568       return 1;
4569     }
4570     if(!dops[i+1].bt) {
4571       if (dops[i+1].is_jump) {
4572         // Load in delay slot, out-of-order execution
4573         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4574         {
4575           // Precompute load address
4576           *value=constmap[i][hr]+imm[i+2];
4577           return 1;
4578         }
4579       }
4580       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4581       {
4582         // Precompute load address
4583         *value=constmap[i][hr]+imm[i+1];
4584         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4585         return 1;
4586       }
4587     }
4588   }
4589   *value=constmap[i][hr];
4590   //printf("c=%lx\n",(long)constmap[i][hr]);
4591   if(i==slen-1) return 1;
4592   assert(reg < 64);
4593   return !((unneeded_reg[i+1]>>reg)&1);
4594 }
4595
4596 // Load registers with known constants
4597 static void load_consts(signed char pre[],signed char regmap[],int i)
4598 {
4599   int hr,hr2;
4600   // propagate loaded constant flags
4601   if(i==0||dops[i].bt)
4602     regs[i].loadedconst=0;
4603   else {
4604     for(hr=0;hr<HOST_REGS;hr++) {
4605       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4606          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4607       {
4608         regs[i].loadedconst|=1<<hr;
4609       }
4610     }
4611   }
4612   // Load 32-bit regs
4613   for(hr=0;hr<HOST_REGS;hr++) {
4614     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4615       //if(entry[hr]!=regmap[hr]) {
4616       if(!((regs[i].loadedconst>>hr)&1)) {
4617         assert(regmap[hr]<64);
4618         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4619           int value,similar=0;
4620           if(get_final_value(hr,i,&value)) {
4621             // see if some other register has similar value
4622             for(hr2=0;hr2<HOST_REGS;hr2++) {
4623               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4624                 if(is_similar_value(value,constmap[i][hr2])) {
4625                   similar=1;
4626                   break;
4627                 }
4628               }
4629             }
4630             if(similar) {
4631               int value2;
4632               if(get_final_value(hr2,i,&value2)) // is this needed?
4633                 emit_movimm_from(value2,hr2,value,hr);
4634               else
4635                 emit_movimm(value,hr);
4636             }
4637             else if(value==0) {
4638               emit_zeroreg(hr);
4639             }
4640             else {
4641               emit_movimm(value,hr);
4642             }
4643           }
4644           regs[i].loadedconst|=1<<hr;
4645         }
4646       }
4647     }
4648   }
4649 }
4650
4651 static void load_all_consts(const signed char regmap[], u_int dirty, int i)
4652 {
4653   int hr;
4654   // Load 32-bit regs
4655   for(hr=0;hr<HOST_REGS;hr++) {
4656     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4657       assert(regmap[hr] < 64);
4658       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4659         int value=constmap[i][hr];
4660         if(value==0) {
4661           emit_zeroreg(hr);
4662         }
4663         else {
4664           emit_movimm(value,hr);
4665         }
4666       }
4667     }
4668   }
4669 }
4670
4671 // Write out all dirty registers (except cycle count)
4672 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty)
4673 {
4674   int hr;
4675   for(hr=0;hr<HOST_REGS;hr++) {
4676     if(hr!=EXCLUDE_REG) {
4677       if(i_regmap[hr]>0) {
4678         if(i_regmap[hr]!=CCREG) {
4679           if((i_dirty>>hr)&1) {
4680             assert(i_regmap[hr]<64);
4681             emit_storereg(i_regmap[hr],hr);
4682           }
4683         }
4684       }
4685     }
4686   }
4687 }
4688
4689 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4690 // This writes the registers not written by store_regs_bt
4691 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr)
4692 {
4693   int hr;
4694   int t=(addr-start)>>2;
4695   for(hr=0;hr<HOST_REGS;hr++) {
4696     if(hr!=EXCLUDE_REG) {
4697       if(i_regmap[hr]>0) {
4698         if(i_regmap[hr]!=CCREG) {
4699           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4700             if((i_dirty>>hr)&1) {
4701               assert(i_regmap[hr]<64);
4702               emit_storereg(i_regmap[hr],hr);
4703             }
4704           }
4705         }
4706       }
4707     }
4708   }
4709 }
4710
4711 // Load all registers (except cycle count)
4712 static void load_all_regs(const signed char i_regmap[])
4713 {
4714   int hr;
4715   for(hr=0;hr<HOST_REGS;hr++) {
4716     if(hr!=EXCLUDE_REG) {
4717       if(i_regmap[hr]==0) {
4718         emit_zeroreg(hr);
4719       }
4720       else
4721       if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4722       {
4723         emit_loadreg(i_regmap[hr],hr);
4724       }
4725     }
4726   }
4727 }
4728
4729 // Load all current registers also needed by next instruction
4730 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[])
4731 {
4732   int hr;
4733   for(hr=0;hr<HOST_REGS;hr++) {
4734     if(hr!=EXCLUDE_REG) {
4735       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4736         if(i_regmap[hr]==0) {
4737           emit_zeroreg(hr);
4738         }
4739         else
4740         if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4741         {
4742           emit_loadreg(i_regmap[hr],hr);
4743         }
4744       }
4745     }
4746   }
4747 }
4748
4749 // Load all regs, storing cycle count if necessary
4750 static void load_regs_entry(int t)
4751 {
4752   int hr;
4753   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4754   else if(ccadj[t]) emit_addimm(HOST_CCREG,-ccadj[t],HOST_CCREG);
4755   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4756     emit_storereg(CCREG,HOST_CCREG);
4757   }
4758   // Load 32-bit regs
4759   for(hr=0;hr<HOST_REGS;hr++) {
4760     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4761       if(regs[t].regmap_entry[hr]==0) {
4762         emit_zeroreg(hr);
4763       }
4764       else if(regs[t].regmap_entry[hr]!=CCREG)
4765       {
4766         emit_loadreg(regs[t].regmap_entry[hr],hr);
4767       }
4768     }
4769   }
4770 }
4771
4772 // Store dirty registers prior to branch
4773 static void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4774 {
4775   if(internal_branch(addr))
4776   {
4777     int t=(addr-start)>>2;
4778     int hr;
4779     for(hr=0;hr<HOST_REGS;hr++) {
4780       if(hr!=EXCLUDE_REG) {
4781         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4782           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4783             if((i_dirty>>hr)&1) {
4784               assert(i_regmap[hr]<64);
4785               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4786                 emit_storereg(i_regmap[hr],hr);
4787             }
4788           }
4789         }
4790       }
4791     }
4792   }
4793   else
4794   {
4795     // Branch out of this block, write out all dirty regs
4796     wb_dirtys(i_regmap,i_dirty);
4797   }
4798 }
4799
4800 // Load all needed registers for branch target
4801 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4802 {
4803   //if(addr>=start && addr<(start+slen*4))
4804   if(internal_branch(addr))
4805   {
4806     int t=(addr-start)>>2;
4807     int hr;
4808     // Store the cycle count before loading something else
4809     if(i_regmap[HOST_CCREG]!=CCREG) {
4810       assert(i_regmap[HOST_CCREG]==-1);
4811     }
4812     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4813       emit_storereg(CCREG,HOST_CCREG);
4814     }
4815     // Load 32-bit regs
4816     for(hr=0;hr<HOST_REGS;hr++) {
4817       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4818         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4819           if(regs[t].regmap_entry[hr]==0) {
4820             emit_zeroreg(hr);
4821           }
4822           else if(regs[t].regmap_entry[hr]!=CCREG)
4823           {
4824             emit_loadreg(regs[t].regmap_entry[hr],hr);
4825           }
4826         }
4827       }
4828     }
4829   }
4830 }
4831
4832 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4833 {
4834   if(addr>=start && addr<start+slen*4-4)
4835   {
4836     int t=(addr-start)>>2;
4837     int hr;
4838     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4839     for(hr=0;hr<HOST_REGS;hr++)
4840     {
4841       if(hr!=EXCLUDE_REG)
4842       {
4843         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4844         {
4845           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4846           {
4847             return 0;
4848           }
4849           else
4850           if((i_dirty>>hr)&1)
4851           {
4852             if(i_regmap[hr]<TEMPREG)
4853             {
4854               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4855                 return 0;
4856             }
4857             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4858             {
4859               assert(0);
4860             }
4861           }
4862         }
4863         else // Same register but is it 32-bit or dirty?
4864         if(i_regmap[hr]>=0)
4865         {
4866           if(!((regs[t].dirty>>hr)&1))
4867           {
4868             if((i_dirty>>hr)&1)
4869             {
4870               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4871               {
4872                 //printf("%x: dirty no match\n",addr);
4873                 return 0;
4874               }
4875             }
4876           }
4877         }
4878       }
4879     }
4880     // Delay slots are not valid branch targets
4881     //if(t>0&&(dops[t-1].is_jump) return 0;
4882     // Delay slots require additional processing, so do not match
4883     if(dops[t].is_ds) return 0;
4884   }
4885   else
4886   {
4887     int hr;
4888     for(hr=0;hr<HOST_REGS;hr++)
4889     {
4890       if(hr!=EXCLUDE_REG)
4891       {
4892         if(i_regmap[hr]>=0)
4893         {
4894           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4895           {
4896             if((i_dirty>>hr)&1)
4897             {
4898               return 0;
4899             }
4900           }
4901         }
4902       }
4903     }
4904   }
4905   return 1;
4906 }
4907
4908 #ifdef DRC_DBG
4909 static void drc_dbg_emit_do_cmp(int i, int ccadj_)
4910 {
4911   extern void do_insn_cmp();
4912   //extern int cycle;
4913   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4914
4915   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4916   save_regs(reglist);
4917   // write out changed consts to match the interpreter
4918   if (i > 0 && !dops[i].bt) {
4919     for (hr = 0; hr < HOST_REGS; hr++) {
4920       int reg = regs[i].regmap_entry[hr]; // regs[i-1].regmap[hr];
4921       if (hr == EXCLUDE_REG || reg < 0)
4922         continue;
4923       if (!((regs[i-1].isconst >> hr) & 1))
4924         continue;
4925       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4926         continue;
4927       emit_movimm(constmap[i-1][hr],0);
4928       emit_storereg(reg, 0);
4929     }
4930   }
4931   emit_movimm(start+i*4,0);
4932   emit_writeword(0,&pcaddr);
4933   int cc = get_reg(regs[i].regmap_entry, CCREG);
4934   if (cc < 0)
4935     emit_loadreg(CCREG, cc = 0);
4936   emit_addimm(cc, ccadj_, 0);
4937   emit_writeword(0, &psxRegs.cycle);
4938   emit_far_call(do_insn_cmp);
4939   //emit_readword(&cycle,0);
4940   //emit_addimm(0,2,0);
4941   //emit_writeword(0,&cycle);
4942   (void)get_reg2;
4943   restore_regs(reglist);
4944   assem_debug("\\\\do_insn_cmp\n");
4945 }
4946 #else
4947 #define drc_dbg_emit_do_cmp(x,y)
4948 #endif
4949
4950 // Used when a branch jumps into the delay slot of another branch
4951 static void ds_assemble_entry(int i)
4952 {
4953   int t = (ba[i] - start) >> 2;
4954   int ccadj_ = -CLOCK_ADJUST(1);
4955   if (!instr_addr[t])
4956     instr_addr[t] = out;
4957   assem_debug("Assemble delay slot at %x\n",ba[i]);
4958   assem_debug("<->\n");
4959   drc_dbg_emit_do_cmp(t, ccadj_);
4960   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4961     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4962   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4963   address_generation(t,&regs[t],regs[t].regmap_entry);
4964   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4965     load_reg(regs[t].regmap_entry,regs[t].regmap,ROREG);
4966   if (dops[t].is_store)
4967     load_reg(regs[t].regmap_entry,regs[t].regmap,INVCP);
4968   is_delayslot=0;
4969   switch (dops[t].itype) {
4970     case SYSCALL:
4971     case HLECALL:
4972     case INTCALL:
4973     case UJUMP:
4974     case RJUMP:
4975     case CJUMP:
4976     case SJUMP:
4977       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4978       break;
4979     default:
4980       assemble(t, &regs[t], ccadj_);
4981   }
4982   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4983   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4984   if(internal_branch(ba[i]+4))
4985     assem_debug("branch: internal\n");
4986   else
4987     assem_debug("branch: external\n");
4988   assert(internal_branch(ba[i]+4));
4989   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4990   emit_jmp(0);
4991 }
4992
4993 // Load 2 immediates optimizing for small code size
4994 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4995 {
4996   emit_movimm(imm1,rt1);
4997   emit_movimm_from(imm1,rt1,imm2,rt2);
4998 }
4999
5000 static void do_cc(int i, const signed char i_regmap[], int *adj,
5001   int addr, int taken, int invert)
5002 {
5003   int count, count_plus2;
5004   void *jaddr;
5005   void *idle=NULL;
5006   int t=0;
5007   if(dops[i].itype==RJUMP)
5008   {
5009     *adj=0;
5010   }
5011   //if(ba[i]>=start && ba[i]<(start+slen*4))
5012   if(internal_branch(ba[i]))
5013   {
5014     t=(ba[i]-start)>>2;
5015     if(dops[t].is_ds) *adj=-CLOCK_ADJUST(1); // Branch into delay slot adds an extra cycle
5016     else *adj=ccadj[t];
5017   }
5018   else
5019   {
5020     *adj=0;
5021   }
5022   count = ccadj[i];
5023   count_plus2 = count + CLOCK_ADJUST(2);
5024   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
5025     // Idle loop
5026     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
5027     idle=out;
5028     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
5029     emit_andimm(HOST_CCREG,3,HOST_CCREG);
5030     jaddr=out;
5031     emit_jmp(0);
5032   }
5033   else if(*adj==0||invert) {
5034     int cycles = count_plus2;
5035     // faster loop HACK
5036 #if 0
5037     if (t&&*adj) {
5038       int rel=t-i;
5039       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
5040         cycles=*adj+count+2-*adj;
5041     }
5042 #endif
5043     emit_addimm_and_set_flags(cycles, HOST_CCREG);
5044     jaddr = out;
5045     emit_jns(0);
5046   }
5047   else
5048   {
5049     emit_cmpimm(HOST_CCREG, -count_plus2);
5050     jaddr = out;
5051     emit_jns(0);
5052   }
5053   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:count_plus2,i,addr,taken,0);
5054 }
5055
5056 static void do_ccstub(int n)
5057 {
5058   literal_pool(256);
5059   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
5060   set_jump_target(stubs[n].addr, out);
5061   int i=stubs[n].b;
5062   if(stubs[n].d==NULLDS) {
5063     // Delay slot instruction is nullified ("likely" branch)
5064     wb_dirtys(regs[i].regmap,regs[i].dirty);
5065   }
5066   else if(stubs[n].d!=TAKEN) {
5067     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
5068   }
5069   else {
5070     if(internal_branch(ba[i]))
5071       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5072   }
5073   if(stubs[n].c!=-1)
5074   {
5075     // Save PC as return address
5076     emit_movimm(stubs[n].c,EAX);
5077     emit_writeword(EAX,&pcaddr);
5078   }
5079   else
5080   {
5081     // Return address depends on which way the branch goes
5082     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
5083     {
5084       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5085       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5086       if(dops[i].rs1==0)
5087       {
5088         s1l=s2l;
5089         s2l=-1;
5090       }
5091       else if(dops[i].rs2==0)
5092       {
5093         s2l=-1;
5094       }
5095       assert(s1l>=0);
5096       #ifdef DESTRUCTIVE_WRITEBACK
5097       if(dops[i].rs1) {
5098         if((branch_regs[i].dirty>>s1l)&&1)
5099           emit_loadreg(dops[i].rs1,s1l);
5100       }
5101       else {
5102         if((branch_regs[i].dirty>>s1l)&1)
5103           emit_loadreg(dops[i].rs2,s1l);
5104       }
5105       if(s2l>=0)
5106         if((branch_regs[i].dirty>>s2l)&1)
5107           emit_loadreg(dops[i].rs2,s2l);
5108       #endif
5109       int hr=0;
5110       int addr=-1,alt=-1,ntaddr=-1;
5111       while(hr<HOST_REGS)
5112       {
5113         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5114            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5115            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5116         {
5117           addr=hr++;break;
5118         }
5119         hr++;
5120       }
5121       while(hr<HOST_REGS)
5122       {
5123         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5124            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5125            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5126         {
5127           alt=hr++;break;
5128         }
5129         hr++;
5130       }
5131       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5132       {
5133         while(hr<HOST_REGS)
5134         {
5135           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5136              branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5137              branch_regs[i].regmap[hr]!=dops[i].rs2 )
5138           {
5139             ntaddr=hr;break;
5140           }
5141           hr++;
5142         }
5143         assert(hr<HOST_REGS);
5144       }
5145       if((dops[i].opcode&0x2f)==4) // BEQ
5146       {
5147         #ifdef HAVE_CMOV_IMM
5148         if(s2l>=0) emit_cmp(s1l,s2l);
5149         else emit_test(s1l,s1l);
5150         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5151         #else
5152         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5153         if(s2l>=0) emit_cmp(s1l,s2l);
5154         else emit_test(s1l,s1l);
5155         emit_cmovne_reg(alt,addr);
5156         #endif
5157       }
5158       if((dops[i].opcode&0x2f)==5) // BNE
5159       {
5160         #ifdef HAVE_CMOV_IMM
5161         if(s2l>=0) emit_cmp(s1l,s2l);
5162         else emit_test(s1l,s1l);
5163         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5164         #else
5165         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5166         if(s2l>=0) emit_cmp(s1l,s2l);
5167         else emit_test(s1l,s1l);
5168         emit_cmovne_reg(alt,addr);
5169         #endif
5170       }
5171       if((dops[i].opcode&0x2f)==6) // BLEZ
5172       {
5173         //emit_movimm(ba[i],alt);
5174         //emit_movimm(start+i*4+8,addr);
5175         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5176         emit_cmpimm(s1l,1);
5177         emit_cmovl_reg(alt,addr);
5178       }
5179       if((dops[i].opcode&0x2f)==7) // BGTZ
5180       {
5181         //emit_movimm(ba[i],addr);
5182         //emit_movimm(start+i*4+8,ntaddr);
5183         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5184         emit_cmpimm(s1l,1);
5185         emit_cmovl_reg(ntaddr,addr);
5186       }
5187       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
5188       {
5189         //emit_movimm(ba[i],alt);
5190         //emit_movimm(start+i*4+8,addr);
5191         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5192         emit_test(s1l,s1l);
5193         emit_cmovs_reg(alt,addr);
5194       }
5195       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
5196       {
5197         //emit_movimm(ba[i],addr);
5198         //emit_movimm(start+i*4+8,alt);
5199         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5200         emit_test(s1l,s1l);
5201         emit_cmovs_reg(alt,addr);
5202       }
5203       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5204         if(source[i]&0x10000) // BC1T
5205         {
5206           //emit_movimm(ba[i],alt);
5207           //emit_movimm(start+i*4+8,addr);
5208           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5209           emit_testimm(s1l,0x800000);
5210           emit_cmovne_reg(alt,addr);
5211         }
5212         else // BC1F
5213         {
5214           //emit_movimm(ba[i],addr);
5215           //emit_movimm(start+i*4+8,alt);
5216           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5217           emit_testimm(s1l,0x800000);
5218           emit_cmovne_reg(alt,addr);
5219         }
5220       }
5221       emit_writeword(addr,&pcaddr);
5222     }
5223     else
5224     if(dops[i].itype==RJUMP)
5225     {
5226       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
5227       if (ds_writes_rjump_rs(i)) {
5228         r=get_reg(branch_regs[i].regmap,RTEMP);
5229       }
5230       emit_writeword(r,&pcaddr);
5231     }
5232     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
5233   }
5234   // Update cycle count
5235   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
5236   if(stubs[n].a) emit_addimm(HOST_CCREG,(int)stubs[n].a,HOST_CCREG);
5237   emit_far_call(cc_interrupt);
5238   if(stubs[n].a) emit_addimm(HOST_CCREG,-(int)stubs[n].a,HOST_CCREG);
5239   if(stubs[n].d==TAKEN) {
5240     if(internal_branch(ba[i]))
5241       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
5242     else if(dops[i].itype==RJUMP) {
5243       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
5244         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
5245       else
5246         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
5247     }
5248   }else if(stubs[n].d==NOTTAKEN) {
5249     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
5250     else load_all_regs(branch_regs[i].regmap);
5251   }else if(stubs[n].d==NULLDS) {
5252     // Delay slot instruction is nullified ("likely" branch)
5253     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5254     else load_all_regs(regs[i].regmap);
5255   }else{
5256     load_all_regs(branch_regs[i].regmap);
5257   }
5258   if (stubs[n].retaddr)
5259     emit_jmp(stubs[n].retaddr);
5260   else
5261     do_jump_vaddr(stubs[n].e);
5262 }
5263
5264 static void add_to_linker(void *addr, u_int target, int is_internal)
5265 {
5266   assert(linkcount < ARRAY_SIZE(link_addr));
5267   link_addr[linkcount].addr = addr;
5268   link_addr[linkcount].target = target;
5269   link_addr[linkcount].internal = is_internal;
5270   linkcount++;
5271 }
5272
5273 static void ujump_assemble_write_ra(int i)
5274 {
5275   int rt;
5276   unsigned int return_address;
5277   rt=get_reg(branch_regs[i].regmap,31);
5278   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5279   //assert(rt>=0);
5280   return_address=start+i*4+8;
5281   if(rt>=0) {
5282     #ifdef USE_MINI_HT
5283     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5284       int temp=-1; // note: must be ds-safe
5285       #ifdef HOST_TEMPREG
5286       temp=HOST_TEMPREG;
5287       #endif
5288       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5289       else emit_movimm(return_address,rt);
5290     }
5291     else
5292     #endif
5293     {
5294       #ifdef REG_PREFETCH
5295       if(temp>=0)
5296       {
5297         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5298       }
5299       #endif
5300       emit_movimm(return_address,rt); // PC into link register
5301       #ifdef IMM_PREFETCH
5302       emit_prefetch(hash_table_get(return_address));
5303       #endif
5304     }
5305   }
5306 }
5307
5308 static void ujump_assemble(int i, const struct regstat *i_regs)
5309 {
5310   int ra_done=0;
5311   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5312   address_generation(i+1,i_regs,regs[i].regmap_entry);
5313   #ifdef REG_PREFETCH
5314   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5315   if(dops[i].rt1==31&&temp>=0)
5316   {
5317     signed char *i_regmap=i_regs->regmap;
5318     int return_address=start+i*4+8;
5319     if(get_reg(branch_regs[i].regmap,31)>0)
5320     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5321   }
5322   #endif
5323   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5324     ujump_assemble_write_ra(i); // writeback ra for DS
5325     ra_done=1;
5326   }
5327   ds_assemble(i+1,i_regs);
5328   uint64_t bc_unneeded=branch_regs[i].u;
5329   bc_unneeded|=1|(1LL<<dops[i].rt1);
5330   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5331   load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5332   if(!ra_done&&dops[i].rt1==31)
5333     ujump_assemble_write_ra(i);
5334   int cc,adj;
5335   cc=get_reg(branch_regs[i].regmap,CCREG);
5336   assert(cc==HOST_CCREG);
5337   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5338   #ifdef REG_PREFETCH
5339   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5340   #endif
5341   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5342   if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5343   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5344   if(internal_branch(ba[i]))
5345     assem_debug("branch: internal\n");
5346   else
5347     assem_debug("branch: external\n");
5348   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5349     ds_assemble_entry(i);
5350   }
5351   else {
5352     add_to_linker(out,ba[i],internal_branch(ba[i]));
5353     emit_jmp(0);
5354   }
5355 }
5356
5357 static void rjump_assemble_write_ra(int i)
5358 {
5359   int rt,return_address;
5360   assert(dops[i+1].rt1!=dops[i].rt1);
5361   assert(dops[i+1].rt2!=dops[i].rt1);
5362   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5363   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5364   assert(rt>=0);
5365   return_address=start+i*4+8;
5366   #ifdef REG_PREFETCH
5367   if(temp>=0)
5368   {
5369     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5370   }
5371   #endif
5372   emit_movimm(return_address,rt); // PC into link register
5373   #ifdef IMM_PREFETCH
5374   emit_prefetch(hash_table_get(return_address));
5375   #endif
5376 }
5377
5378 static void rjump_assemble(int i, const struct regstat *i_regs)
5379 {
5380   int temp;
5381   int rs,cc;
5382   int ra_done=0;
5383   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5384   assert(rs>=0);
5385   if (ds_writes_rjump_rs(i)) {
5386     // Delay slot abuse, make a copy of the branch address register
5387     temp=get_reg(branch_regs[i].regmap,RTEMP);
5388     assert(temp>=0);
5389     assert(regs[i].regmap[temp]==RTEMP);
5390     emit_mov(rs,temp);
5391     rs=temp;
5392   }
5393   address_generation(i+1,i_regs,regs[i].regmap_entry);
5394   #ifdef REG_PREFETCH
5395   if(dops[i].rt1==31)
5396   {
5397     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5398       signed char *i_regmap=i_regs->regmap;
5399       int return_address=start+i*4+8;
5400       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5401     }
5402   }
5403   #endif
5404   #ifdef USE_MINI_HT
5405   if(dops[i].rs1==31) {
5406     int rh=get_reg(regs[i].regmap,RHASH);
5407     if(rh>=0) do_preload_rhash(rh);
5408   }
5409   #endif
5410   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5411     rjump_assemble_write_ra(i);
5412     ra_done=1;
5413   }
5414   ds_assemble(i+1,i_regs);
5415   uint64_t bc_unneeded=branch_regs[i].u;
5416   bc_unneeded|=1|(1LL<<dops[i].rt1);
5417   bc_unneeded&=~(1LL<<dops[i].rs1);
5418   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5419   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5420   if(!ra_done&&dops[i].rt1!=0)
5421     rjump_assemble_write_ra(i);
5422   cc=get_reg(branch_regs[i].regmap,CCREG);
5423   assert(cc==HOST_CCREG);
5424   (void)cc;
5425   #ifdef USE_MINI_HT
5426   int rh=get_reg(branch_regs[i].regmap,RHASH);
5427   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5428   if(dops[i].rs1==31) {
5429     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5430     do_preload_rhtbl(ht);
5431     do_rhash(rs,rh);
5432   }
5433   #endif
5434   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5435   #ifdef DESTRUCTIVE_WRITEBACK
5436   if((branch_regs[i].dirty>>rs)&1) {
5437     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5438       emit_loadreg(dops[i].rs1,rs);
5439     }
5440   }
5441   #endif
5442   #ifdef REG_PREFETCH
5443   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5444   #endif
5445   #ifdef USE_MINI_HT
5446   if(dops[i].rs1==31) {
5447     do_miniht_load(ht,rh);
5448   }
5449   #endif
5450   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5451   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5452   //assert(adj==0);
5453   emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5454   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5455   if(dops[i+1].itype==COP0 && dops[i+1].opcode2==0x10)
5456     // special case for RFE
5457     emit_jmp(0);
5458   else
5459     emit_jns(0);
5460   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5461   #ifdef USE_MINI_HT
5462   if(dops[i].rs1==31) {
5463     do_miniht_jump(rs,rh,ht);
5464   }
5465   else
5466   #endif
5467   {
5468     do_jump_vaddr(rs);
5469   }
5470   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5471   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5472   #endif
5473 }
5474
5475 static void cjump_assemble(int i, const struct regstat *i_regs)
5476 {
5477   const signed char *i_regmap = i_regs->regmap;
5478   int cc;
5479   int match;
5480   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5481   assem_debug("match=%d\n",match);
5482   int s1l,s2l;
5483   int unconditional=0,nop=0;
5484   int invert=0;
5485   int internal=internal_branch(ba[i]);
5486   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5487   if(!match) invert=1;
5488   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5489   if(i>(ba[i]-start)>>2) invert=1;
5490   #endif
5491   #ifdef __aarch64__
5492   invert=1; // because of near cond. branches
5493   #endif
5494
5495   if(dops[i].ooo) {
5496     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5497     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5498   }
5499   else {
5500     s1l=get_reg(i_regmap,dops[i].rs1);
5501     s2l=get_reg(i_regmap,dops[i].rs2);
5502   }
5503   if(dops[i].rs1==0&&dops[i].rs2==0)
5504   {
5505     if(dops[i].opcode&1) nop=1;
5506     else unconditional=1;
5507     //assert(dops[i].opcode!=5);
5508     //assert(dops[i].opcode!=7);
5509     //assert(dops[i].opcode!=0x15);
5510     //assert(dops[i].opcode!=0x17);
5511   }
5512   else if(dops[i].rs1==0)
5513   {
5514     s1l=s2l;
5515     s2l=-1;
5516   }
5517   else if(dops[i].rs2==0)
5518   {
5519     s2l=-1;
5520   }
5521
5522   if(dops[i].ooo) {
5523     // Out of order execution (delay slot first)
5524     //printf("OOOE\n");
5525     address_generation(i+1,i_regs,regs[i].regmap_entry);
5526     ds_assemble(i+1,i_regs);
5527     int adj;
5528     uint64_t bc_unneeded=branch_regs[i].u;
5529     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5530     bc_unneeded|=1;
5531     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5532     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5533     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5534     cc=get_reg(branch_regs[i].regmap,CCREG);
5535     assert(cc==HOST_CCREG);
5536     if(unconditional)
5537       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5538     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5539     //assem_debug("cycle count (adj)\n");
5540     if(unconditional) {
5541       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5542       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5543         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5544         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5545         if(internal)
5546           assem_debug("branch: internal\n");
5547         else
5548           assem_debug("branch: external\n");
5549         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5550           ds_assemble_entry(i);
5551         }
5552         else {
5553           add_to_linker(out,ba[i],internal);
5554           emit_jmp(0);
5555         }
5556         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5557         if(((u_int)out)&7) emit_addnop(0);
5558         #endif
5559       }
5560     }
5561     else if(nop) {
5562       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5563       void *jaddr=out;
5564       emit_jns(0);
5565       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5566     }
5567     else {
5568       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5569       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5570       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5571
5572       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5573       assert(s1l>=0);
5574       if(dops[i].opcode==4) // BEQ
5575       {
5576         if(s2l>=0) emit_cmp(s1l,s2l);
5577         else emit_test(s1l,s1l);
5578         if(invert){
5579           nottaken=out;
5580           emit_jne(DJT_1);
5581         }else{
5582           add_to_linker(out,ba[i],internal);
5583           emit_jeq(0);
5584         }
5585       }
5586       if(dops[i].opcode==5) // BNE
5587       {
5588         if(s2l>=0) emit_cmp(s1l,s2l);
5589         else emit_test(s1l,s1l);
5590         if(invert){
5591           nottaken=out;
5592           emit_jeq(DJT_1);
5593         }else{
5594           add_to_linker(out,ba[i],internal);
5595           emit_jne(0);
5596         }
5597       }
5598       if(dops[i].opcode==6) // BLEZ
5599       {
5600         emit_cmpimm(s1l,1);
5601         if(invert){
5602           nottaken=out;
5603           emit_jge(DJT_1);
5604         }else{
5605           add_to_linker(out,ba[i],internal);
5606           emit_jl(0);
5607         }
5608       }
5609       if(dops[i].opcode==7) // BGTZ
5610       {
5611         emit_cmpimm(s1l,1);
5612         if(invert){
5613           nottaken=out;
5614           emit_jl(DJT_1);
5615         }else{
5616           add_to_linker(out,ba[i],internal);
5617           emit_jge(0);
5618         }
5619       }
5620       if(invert) {
5621         if(taken) set_jump_target(taken, out);
5622         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5623         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5624           if(adj) {
5625             emit_addimm(cc,-adj,cc);
5626             add_to_linker(out,ba[i],internal);
5627           }else{
5628             emit_addnop(13);
5629             add_to_linker(out,ba[i],internal*2);
5630           }
5631           emit_jmp(0);
5632         }else
5633         #endif
5634         {
5635           if(adj) emit_addimm(cc,-adj,cc);
5636           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5637           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5638           if(internal)
5639             assem_debug("branch: internal\n");
5640           else
5641             assem_debug("branch: external\n");
5642           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5643             ds_assemble_entry(i);
5644           }
5645           else {
5646             add_to_linker(out,ba[i],internal);
5647             emit_jmp(0);
5648           }
5649         }
5650         set_jump_target(nottaken, out);
5651       }
5652
5653       if(nottaken1) set_jump_target(nottaken1, out);
5654       if(adj) {
5655         if(!invert) emit_addimm(cc,adj,cc);
5656       }
5657     } // (!unconditional)
5658   } // if(ooo)
5659   else
5660   {
5661     // In-order execution (branch first)
5662     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5663     if(!unconditional&&!nop) {
5664       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5665       assert(s1l>=0);
5666       if((dops[i].opcode&0x2f)==4) // BEQ
5667       {
5668         if(s2l>=0) emit_cmp(s1l,s2l);
5669         else emit_test(s1l,s1l);
5670         nottaken=out;
5671         emit_jne(DJT_2);
5672       }
5673       if((dops[i].opcode&0x2f)==5) // BNE
5674       {
5675         if(s2l>=0) emit_cmp(s1l,s2l);
5676         else emit_test(s1l,s1l);
5677         nottaken=out;
5678         emit_jeq(DJT_2);
5679       }
5680       if((dops[i].opcode&0x2f)==6) // BLEZ
5681       {
5682         emit_cmpimm(s1l,1);
5683         nottaken=out;
5684         emit_jge(DJT_2);
5685       }
5686       if((dops[i].opcode&0x2f)==7) // BGTZ
5687       {
5688         emit_cmpimm(s1l,1);
5689         nottaken=out;
5690         emit_jl(DJT_2);
5691       }
5692     } // if(!unconditional)
5693     int adj;
5694     uint64_t ds_unneeded=branch_regs[i].u;
5695     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5696     ds_unneeded|=1;
5697     // branch taken
5698     if(!nop) {
5699       if(taken) set_jump_target(taken, out);
5700       assem_debug("1:\n");
5701       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5702       // load regs
5703       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5704       address_generation(i+1,&branch_regs[i],0);
5705       if (ram_offset)
5706         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5707       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5708       ds_assemble(i+1,&branch_regs[i]);
5709       cc=get_reg(branch_regs[i].regmap,CCREG);
5710       if(cc==-1) {
5711         emit_loadreg(CCREG,cc=HOST_CCREG);
5712         // CHECK: Is the following instruction (fall thru) allocated ok?
5713       }
5714       assert(cc==HOST_CCREG);
5715       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5716       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5717       assem_debug("cycle count (adj)\n");
5718       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5719       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5720       if(internal)
5721         assem_debug("branch: internal\n");
5722       else
5723         assem_debug("branch: external\n");
5724       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5725         ds_assemble_entry(i);
5726       }
5727       else {
5728         add_to_linker(out,ba[i],internal);
5729         emit_jmp(0);
5730       }
5731     }
5732     // branch not taken
5733     if(!unconditional) {
5734       if(nottaken1) set_jump_target(nottaken1, out);
5735       set_jump_target(nottaken, out);
5736       assem_debug("2:\n");
5737       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5738       // load regs
5739       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5740       address_generation(i+1,&branch_regs[i],0);
5741       if (ram_offset)
5742         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5743       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5744       ds_assemble(i+1,&branch_regs[i]);
5745       cc=get_reg(branch_regs[i].regmap,CCREG);
5746       if (cc == -1) {
5747         // Cycle count isn't in a register, temporarily load it then write it out
5748         emit_loadreg(CCREG,HOST_CCREG);
5749         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5750         void *jaddr=out;
5751         emit_jns(0);
5752         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5753         emit_storereg(CCREG,HOST_CCREG);
5754       }
5755       else{
5756         cc=get_reg(i_regmap,CCREG);
5757         assert(cc==HOST_CCREG);
5758         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5759         void *jaddr=out;
5760         emit_jns(0);
5761         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5762       }
5763     }
5764   }
5765 }
5766
5767 static void sjump_assemble(int i, const struct regstat *i_regs)
5768 {
5769   const signed char *i_regmap = i_regs->regmap;
5770   int cc;
5771   int match;
5772   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5773   assem_debug("smatch=%d ooo=%d\n", match, dops[i].ooo);
5774   int s1l;
5775   int unconditional=0,nevertaken=0;
5776   int invert=0;
5777   int internal=internal_branch(ba[i]);
5778   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5779   if(!match) invert=1;
5780   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5781   if(i>(ba[i]-start)>>2) invert=1;
5782   #endif
5783   #ifdef __aarch64__
5784   invert=1; // because of near cond. branches
5785   #endif
5786
5787   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5788   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5789
5790   if(dops[i].ooo) {
5791     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5792   }
5793   else {
5794     s1l=get_reg(i_regmap,dops[i].rs1);
5795   }
5796   if(dops[i].rs1==0)
5797   {
5798     if(dops[i].opcode2&1) unconditional=1;
5799     else nevertaken=1;
5800     // These are never taken (r0 is never less than zero)
5801     //assert(dops[i].opcode2!=0);
5802     //assert(dops[i].opcode2!=2);
5803     //assert(dops[i].opcode2!=0x10);
5804     //assert(dops[i].opcode2!=0x12);
5805   }
5806
5807   if(dops[i].ooo) {
5808     // Out of order execution (delay slot first)
5809     //printf("OOOE\n");
5810     address_generation(i+1,i_regs,regs[i].regmap_entry);
5811     ds_assemble(i+1,i_regs);
5812     int adj;
5813     uint64_t bc_unneeded=branch_regs[i].u;
5814     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5815     bc_unneeded|=1;
5816     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5817     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5818     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5819     if(dops[i].rt1==31) {
5820       int rt,return_address;
5821       rt=get_reg(branch_regs[i].regmap,31);
5822       assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5823       if(rt>=0) {
5824         // Save the PC even if the branch is not taken
5825         return_address=start+i*4+8;
5826         emit_movimm(return_address,rt); // PC into link register
5827         #ifdef IMM_PREFETCH
5828         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5829         #endif
5830       }
5831     }
5832     cc=get_reg(branch_regs[i].regmap,CCREG);
5833     assert(cc==HOST_CCREG);
5834     if(unconditional)
5835       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5836     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5837     assem_debug("cycle count (adj)\n");
5838     if(unconditional) {
5839       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5840       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5841         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5842         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5843         if(internal)
5844           assem_debug("branch: internal\n");
5845         else
5846           assem_debug("branch: external\n");
5847         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5848           ds_assemble_entry(i);
5849         }
5850         else {
5851           add_to_linker(out,ba[i],internal);
5852           emit_jmp(0);
5853         }
5854         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5855         if(((u_int)out)&7) emit_addnop(0);
5856         #endif
5857       }
5858     }
5859     else if(nevertaken) {
5860       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5861       void *jaddr=out;
5862       emit_jns(0);
5863       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5864     }
5865     else {
5866       void *nottaken = NULL;
5867       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5868       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5869       {
5870         assert(s1l>=0);
5871         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5872         {
5873           emit_test(s1l,s1l);
5874           if(invert){
5875             nottaken=out;
5876             emit_jns(DJT_1);
5877           }else{
5878             add_to_linker(out,ba[i],internal);
5879             emit_js(0);
5880           }
5881         }
5882         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5883         {
5884           emit_test(s1l,s1l);
5885           if(invert){
5886             nottaken=out;
5887             emit_js(DJT_1);
5888           }else{
5889             add_to_linker(out,ba[i],internal);
5890             emit_jns(0);
5891           }
5892         }
5893       }
5894
5895       if(invert) {
5896         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5897         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5898           if(adj) {
5899             emit_addimm(cc,-adj,cc);
5900             add_to_linker(out,ba[i],internal);
5901           }else{
5902             emit_addnop(13);
5903             add_to_linker(out,ba[i],internal*2);
5904           }
5905           emit_jmp(0);
5906         }else
5907         #endif
5908         {
5909           if(adj) emit_addimm(cc,-adj,cc);
5910           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5911           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5912           if(internal)
5913             assem_debug("branch: internal\n");
5914           else
5915             assem_debug("branch: external\n");
5916           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5917             ds_assemble_entry(i);
5918           }
5919           else {
5920             add_to_linker(out,ba[i],internal);
5921             emit_jmp(0);
5922           }
5923         }
5924         set_jump_target(nottaken, out);
5925       }
5926
5927       if(adj) {
5928         if(!invert) emit_addimm(cc,adj,cc);
5929       }
5930     } // (!unconditional)
5931   } // if(ooo)
5932   else
5933   {
5934     // In-order execution (branch first)
5935     //printf("IOE\n");
5936     void *nottaken = NULL;
5937     if(dops[i].rt1==31) {
5938       int rt,return_address;
5939       rt=get_reg(branch_regs[i].regmap,31);
5940       if(rt>=0) {
5941         // Save the PC even if the branch is not taken
5942         return_address=start+i*4+8;
5943         emit_movimm(return_address,rt); // PC into link register
5944         #ifdef IMM_PREFETCH
5945         emit_prefetch(hash_table_get(return_address));
5946         #endif
5947       }
5948     }
5949     if(!unconditional) {
5950       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5951         assert(s1l>=0);
5952         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5953         {
5954           emit_test(s1l,s1l);
5955           nottaken=out;
5956           emit_jns(DJT_1);
5957         }
5958         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5959         {
5960           emit_test(s1l,s1l);
5961           nottaken=out;
5962           emit_js(DJT_1);
5963         }
5964     } // if(!unconditional)
5965     int adj;
5966     uint64_t ds_unneeded=branch_regs[i].u;
5967     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5968     ds_unneeded|=1;
5969     // branch taken
5970     if(!nevertaken) {
5971       //assem_debug("1:\n");
5972       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5973       // load regs
5974       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5975       address_generation(i+1,&branch_regs[i],0);
5976       if (ram_offset)
5977         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5978       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5979       ds_assemble(i+1,&branch_regs[i]);
5980       cc=get_reg(branch_regs[i].regmap,CCREG);
5981       if(cc==-1) {
5982         emit_loadreg(CCREG,cc=HOST_CCREG);
5983         // CHECK: Is the following instruction (fall thru) allocated ok?
5984       }
5985       assert(cc==HOST_CCREG);
5986       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5987       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5988       assem_debug("cycle count (adj)\n");
5989       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5990       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5991       if(internal)
5992         assem_debug("branch: internal\n");
5993       else
5994         assem_debug("branch: external\n");
5995       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5996         ds_assemble_entry(i);
5997       }
5998       else {
5999         add_to_linker(out,ba[i],internal);
6000         emit_jmp(0);
6001       }
6002     }
6003     // branch not taken
6004     if(!unconditional) {
6005       set_jump_target(nottaken, out);
6006       assem_debug("1:\n");
6007       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
6008       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
6009       address_generation(i+1,&branch_regs[i],0);
6010       if (ram_offset)
6011         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
6012       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
6013       ds_assemble(i+1,&branch_regs[i]);
6014       cc=get_reg(branch_regs[i].regmap,CCREG);
6015       if (cc == -1) {
6016         // Cycle count isn't in a register, temporarily load it then write it out
6017         emit_loadreg(CCREG,HOST_CCREG);
6018         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
6019         void *jaddr=out;
6020         emit_jns(0);
6021         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
6022         emit_storereg(CCREG,HOST_CCREG);
6023       }
6024       else{
6025         cc=get_reg(i_regmap,CCREG);
6026         assert(cc==HOST_CCREG);
6027         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
6028         void *jaddr=out;
6029         emit_jns(0);
6030         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
6031       }
6032     }
6033   }
6034 }
6035
6036 static void check_regmap(signed char *regmap)
6037 {
6038 #ifndef NDEBUG
6039   int i,j;
6040   for (i = 0; i < HOST_REGS; i++) {
6041     if (regmap[i] < 0)
6042       continue;
6043     for (j = i + 1; j < HOST_REGS; j++)
6044       assert(regmap[i] != regmap[j]);
6045   }
6046 #endif
6047 }
6048
6049 #ifdef DISASM
6050 #include <inttypes.h>
6051 static char insn[MAXBLOCK][10];
6052
6053 #define set_mnemonic(i_, n_) \
6054   strcpy(insn[i_], n_)
6055
6056 void print_regmap(const char *name, const signed char *regmap)
6057 {
6058   char buf[5];
6059   int i, l;
6060   fputs(name, stdout);
6061   for (i = 0; i < HOST_REGS; i++) {
6062     l = 0;
6063     if (regmap[i] >= 0)
6064       l = snprintf(buf, sizeof(buf), "$%d", regmap[i]);
6065     for (; l < 3; l++)
6066       buf[l] = ' ';
6067     buf[l] = 0;
6068     printf(" r%d=%s", i, buf);
6069   }
6070   fputs("\n", stdout);
6071 }
6072
6073   /* disassembly */
6074 void disassemble_inst(int i)
6075 {
6076     if (dops[i].bt) printf("*"); else printf(" ");
6077     switch(dops[i].itype) {
6078       case UJUMP:
6079         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6080       case CJUMP:
6081         printf (" %x: %s r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,i?start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14):*ba);break;
6082       case SJUMP:
6083         printf (" %x: %s r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14));break;
6084       case RJUMP:
6085         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6086           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6087         else
6088           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6089         break;
6090       case IMM16:
6091         if(dops[i].opcode==0xf) //LUI
6092           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6093         else
6094           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6095         break;
6096       case LOAD:
6097       case LOADLR:
6098         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6099         break;
6100       case STORE:
6101       case STORELR:
6102         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6103         break;
6104       case ALU:
6105       case SHIFT:
6106         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6107         break;
6108       case MULTDIV:
6109         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6110         break;
6111       case SHIFTIMM:
6112         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6113         break;
6114       case MOV:
6115         if((dops[i].opcode2&0x1d)==0x10)
6116           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6117         else if((dops[i].opcode2&0x1d)==0x11)
6118           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6119         else
6120           printf (" %x: %s\n",start+i*4,insn[i]);
6121         break;
6122       case COP0:
6123         if(dops[i].opcode2==0)
6124           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6125         else if(dops[i].opcode2==4)
6126           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6127         else printf (" %x: %s\n",start+i*4,insn[i]);
6128         break;
6129       case COP1:
6130         if(dops[i].opcode2<3)
6131           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6132         else if(dops[i].opcode2>3)
6133           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6134         else printf (" %x: %s\n",start+i*4,insn[i]);
6135         break;
6136       case COP2:
6137         if(dops[i].opcode2<3)
6138           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6139         else if(dops[i].opcode2>3)
6140           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6141         else printf (" %x: %s\n",start+i*4,insn[i]);
6142         break;
6143       case C1LS:
6144         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6145         break;
6146       case C2LS:
6147         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6148         break;
6149       case INTCALL:
6150         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6151         break;
6152       default:
6153         //printf (" %s %8x\n",insn[i],source[i]);
6154         printf (" %x: %s\n",start+i*4,insn[i]);
6155     }
6156     return;
6157     printf("D: %"PRIu64"  WD: %"PRIu64"  U: %"PRIu64"\n",
6158       regs[i].dirty, regs[i].wasdirty, unneeded_reg[i]);
6159     print_regmap("pre:   ", regmap_pre[i]);
6160     print_regmap("entry: ", regs[i].regmap_entry);
6161     print_regmap("map:   ", regs[i].regmap);
6162     if (dops[i].is_jump) {
6163       print_regmap("bentry:", branch_regs[i].regmap_entry);
6164       print_regmap("bmap:  ", branch_regs[i].regmap);
6165     }
6166 }
6167 #else
6168 #define set_mnemonic(i_, n_)
6169 static void disassemble_inst(int i) {}
6170 #endif // DISASM
6171
6172 #define DRC_TEST_VAL 0x74657374
6173
6174 static noinline void new_dynarec_test(void)
6175 {
6176   int (*testfunc)(void);
6177   void *beginning;
6178   int ret[2];
6179   size_t i;
6180
6181   // check structure linkage
6182   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6183   {
6184     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6185   }
6186
6187   SysPrintf("(%p) testing if we can run recompiled code @%p...\n",
6188     new_dynarec_test, out);
6189   ((volatile u_int *)NDRC_WRITE_OFFSET(out))[0]++; // make the cache dirty
6190
6191   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6192     out = ndrc->translation_cache;
6193     beginning = start_block();
6194     emit_movimm(DRC_TEST_VAL + i, 0); // test
6195     emit_ret();
6196     literal_pool(0);
6197     end_block(beginning);
6198     testfunc = beginning;
6199     ret[i] = testfunc();
6200   }
6201
6202   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6203     SysPrintf("test passed.\n");
6204   else
6205     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6206   out = ndrc->translation_cache;
6207 }
6208
6209 // clear the state completely, instead of just marking
6210 // things invalid like invalidate_all_pages() does
6211 void new_dynarec_clear_full(void)
6212 {
6213   int n;
6214   out = ndrc->translation_cache;
6215   memset(invalid_code,1,sizeof(invalid_code));
6216   memset(hash_table,0xff,sizeof(hash_table));
6217   memset(mini_ht,-1,sizeof(mini_ht));
6218   memset(shadow,0,sizeof(shadow));
6219   copy=shadow;
6220   expirep = EXPIRITY_OFFSET;
6221   pending_exception=0;
6222   literalcount=0;
6223   stop_after_jal=0;
6224   inv_code_start=inv_code_end=~0;
6225   hack_addr=0;
6226   f1_hack=0;
6227   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6228     blocks_clear(&blocks[n]);
6229   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6230     free(jumps[n]);
6231     jumps[n] = NULL;
6232   }
6233   stat_clear(stat_blocks);
6234   stat_clear(stat_links);
6235
6236   cycle_multiplier_old = cycle_multiplier;
6237   new_dynarec_hacks_old = new_dynarec_hacks;
6238 }
6239
6240 void new_dynarec_init(void)
6241 {
6242   SysPrintf("Init new dynarec, ndrc size %x\n", (int)sizeof(*ndrc));
6243
6244 #ifdef _3DS
6245   check_rosalina();
6246 #endif
6247 #ifdef BASE_ADDR_DYNAMIC
6248   #ifdef VITA
6249   sceBlock = getVMBlock(); //sceKernelAllocMemBlockForVM("code", sizeof(*ndrc));
6250   if (sceBlock <= 0)
6251     SysPrintf("sceKernelAllocMemBlockForVM failed: %x\n", sceBlock);
6252   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6253   if (ret < 0)
6254     SysPrintf("sceKernelGetMemBlockBase failed: %x\n", ret);
6255   sceKernelOpenVMDomain();
6256   sceClibPrintf("translation_cache = 0x%08lx\n ", (long)ndrc->translation_cache);
6257   #elif defined(_MSC_VER)
6258   ndrc = VirtualAlloc(NULL, sizeof(*ndrc), MEM_COMMIT | MEM_RESERVE,
6259     PAGE_EXECUTE_READWRITE);
6260   #elif defined(HAVE_LIBNX)
6261   Result rc = jitCreate(&g_jit, sizeof(*ndrc));
6262   if (R_FAILED(rc))
6263     SysPrintf("jitCreate failed: %08x\n", rc);
6264   SysPrintf("jitCreate: RX: %p RW: %p type: %d\n", g_jit.rx_addr, g_jit.rw_addr, g_jit.type);
6265   jitTransitionToWritable(&g_jit);
6266   ndrc = g_jit.rx_addr;
6267   ndrc_write_ofs = (char *)g_jit.rw_addr - (char *)ndrc;
6268   memset(NDRC_WRITE_OFFSET(&ndrc->tramp), 0, sizeof(ndrc->tramp));
6269   #else
6270   uintptr_t desired_addr = 0;
6271   int prot = PROT_READ | PROT_WRITE | PROT_EXEC;
6272   int flags = MAP_PRIVATE | MAP_ANONYMOUS;
6273   int fd = -1;
6274   #ifdef __ELF__
6275   extern char _end;
6276   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6277   #endif
6278   #ifdef TC_WRITE_OFFSET
6279   // mostly for testing
6280   fd = open("/dev/shm/pcsxr", O_CREAT | O_RDWR, 0600);
6281   ftruncate(fd, sizeof(*ndrc));
6282   void *mw = mmap(NULL, sizeof(*ndrc), PROT_READ | PROT_WRITE,
6283                   (flags = MAP_SHARED), fd, 0);
6284   assert(mw != MAP_FAILED);
6285   prot = PROT_READ | PROT_EXEC;
6286   #endif
6287   ndrc = mmap((void *)desired_addr, sizeof(*ndrc), prot, flags, fd, 0);
6288   if (ndrc == MAP_FAILED) {
6289     SysPrintf("mmap() failed: %s\n", strerror(errno));
6290     abort();
6291   }
6292   #ifdef TC_WRITE_OFFSET
6293   ndrc_write_ofs = (char *)mw - (char *)ndrc;
6294   #endif
6295   #endif
6296 #else
6297   #ifndef NO_WRITE_EXEC
6298   // not all systems allow execute in data segment by default
6299   // size must be 4K aligned for 3DS?
6300   if (mprotect(ndrc, sizeof(*ndrc),
6301                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6302     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6303   #endif
6304 #endif
6305   out = ndrc->translation_cache;
6306   cycle_multiplier=200;
6307   new_dynarec_clear_full();
6308 #ifdef HOST_IMM8
6309   // Copy this into local area so we don't have to put it in every literal pool
6310   invc_ptr=invalid_code;
6311 #endif
6312   arch_init();
6313   new_dynarec_test();
6314   ram_offset=(uintptr_t)rdram-0x80000000;
6315   if (ram_offset!=0)
6316     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6317   SysPrintf("Mapped (RAM/scrp/ROM/LUTs/TC):\n");
6318   SysPrintf("%p/%p/%p/%p/%p\n", psxM, psxH, psxR, mem_rtab, out);
6319 }
6320
6321 void new_dynarec_cleanup(void)
6322 {
6323   int n;
6324 #ifdef BASE_ADDR_DYNAMIC
6325   #ifdef VITA
6326   // sceBlock is managed by retroarch's bootstrap code
6327   //sceKernelFreeMemBlock(sceBlock);
6328   //sceBlock = -1;
6329   #elif defined(HAVE_LIBNX)
6330   jitClose(&g_jit);
6331   ndrc = NULL;
6332   #else
6333   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6334     SysPrintf("munmap() failed\n");
6335   ndrc = NULL;
6336   #endif
6337 #endif
6338   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6339     blocks_clear(&blocks[n]);
6340   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6341     free(jumps[n]);
6342     jumps[n] = NULL;
6343   }
6344   stat_clear(stat_blocks);
6345   stat_clear(stat_links);
6346   new_dynarec_print_stats();
6347 }
6348
6349 static u_int *get_source_start(u_int addr, u_int *limit)
6350 {
6351   if (addr < 0x00200000 ||
6352     (0xa0000000 <= addr && addr < 0xa0200000))
6353   {
6354     // used for BIOS calls mostly?
6355     *limit = (addr&0xa0000000)|0x00200000;
6356     return (u_int *)(rdram + (addr&0x1fffff));
6357   }
6358   else if (!Config.HLE && (
6359     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6360     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6361   {
6362     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6363     // but timings in PCSX are too tied to the interpreter's BIAS
6364     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6365       cycle_multiplier_active = 200;
6366
6367     *limit = (addr & 0xfff00000) | 0x80000;
6368     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6369   }
6370   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6371     *limit = (addr & 0x80600000) + 0x00200000;
6372     return (u_int *)(rdram + (addr&0x1fffff));
6373   }
6374   return NULL;
6375 }
6376
6377 static u_int scan_for_ret(u_int addr)
6378 {
6379   u_int limit = 0;
6380   u_int *mem;
6381
6382   mem = get_source_start(addr, &limit);
6383   if (mem == NULL)
6384     return addr;
6385
6386   if (limit > addr + 0x1000)
6387     limit = addr + 0x1000;
6388   for (; addr < limit; addr += 4, mem++) {
6389     if (*mem == 0x03e00008) // jr $ra
6390       return addr + 8;
6391   }
6392   return addr;
6393 }
6394
6395 struct savestate_block {
6396   uint32_t addr;
6397   uint32_t regflags;
6398 };
6399
6400 static int addr_cmp(const void *p1_, const void *p2_)
6401 {
6402   const struct savestate_block *p1 = p1_, *p2 = p2_;
6403   return p1->addr - p2->addr;
6404 }
6405
6406 int new_dynarec_save_blocks(void *save, int size)
6407 {
6408   struct savestate_block *sblocks = save;
6409   int maxcount = size / sizeof(sblocks[0]);
6410   struct savestate_block tmp_blocks[1024];
6411   struct block_info *block;
6412   int p, s, d, o, bcnt;
6413   u_int addr;
6414
6415   o = 0;
6416   for (p = 0; p < ARRAY_SIZE(blocks); p++) {
6417     bcnt = 0;
6418     for (block = blocks[p]; block != NULL; block = block->next) {
6419       if (block->is_dirty)
6420         continue;
6421       tmp_blocks[bcnt].addr = block->start;
6422       tmp_blocks[bcnt].regflags = block->reg_sv_flags;
6423       bcnt++;
6424     }
6425     if (bcnt < 1)
6426       continue;
6427     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6428
6429     addr = tmp_blocks[0].addr;
6430     for (s = d = 0; s < bcnt; s++) {
6431       if (tmp_blocks[s].addr < addr)
6432         continue;
6433       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6434         tmp_blocks[d++] = tmp_blocks[s];
6435       addr = scan_for_ret(tmp_blocks[s].addr);
6436     }
6437
6438     if (o + d > maxcount)
6439       d = maxcount - o;
6440     memcpy(&sblocks[o], tmp_blocks, d * sizeof(sblocks[0]));
6441     o += d;
6442   }
6443
6444   return o * sizeof(sblocks[0]);
6445 }
6446
6447 void new_dynarec_load_blocks(const void *save, int size)
6448 {
6449   const struct savestate_block *sblocks = save;
6450   int count = size / sizeof(sblocks[0]);
6451   struct block_info *block;
6452   u_int regs_save[32];
6453   u_int page;
6454   uint32_t f;
6455   int i, b;
6456
6457   // restore clean blocks, if any
6458   for (page = 0, b = i = 0; page < ARRAY_SIZE(blocks); page++) {
6459     for (block = blocks[page]; block != NULL; block = block->next, b++) {
6460       if (!block->is_dirty)
6461         continue;
6462       assert(block->source && block->copy);
6463       if (memcmp(block->source, block->copy, block->len))
6464         continue;
6465
6466       // see try_restore_block
6467       block->is_dirty = 0;
6468       mark_invalid_code(block->start, block->len, 0);
6469       i++;
6470     }
6471   }
6472   inv_debug("load_blocks: %d/%d clean blocks\n", i, b);
6473
6474   // change GPRs for speculation to at least partially work..
6475   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6476   for (i = 1; i < 32; i++)
6477     psxRegs.GPR.r[i] = 0x80000000;
6478
6479   for (b = 0; b < count; b++) {
6480     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6481       if (f & 1)
6482         psxRegs.GPR.r[i] = 0x1f800000;
6483     }
6484
6485     ndrc_get_addr_ht(sblocks[b].addr);
6486
6487     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6488       if (f & 1)
6489         psxRegs.GPR.r[i] = 0x80000000;
6490     }
6491   }
6492
6493   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6494 }
6495
6496 void new_dynarec_print_stats(void)
6497 {
6498 #ifdef STAT_PRINT
6499   printf("cc %3d,%3d,%3d lu%6d,%3d,%3d c%3d inv%3d,%3d tc_offs %zu b %u,%u\n",
6500     stat_bc_pre, stat_bc_direct, stat_bc_restore,
6501     stat_ht_lookups, stat_jump_in_lookups, stat_restore_tries,
6502     stat_restore_compares, stat_inv_addr_calls, stat_inv_hits,
6503     out - ndrc->translation_cache, stat_blocks, stat_links);
6504   stat_bc_direct = stat_bc_pre = stat_bc_restore =
6505   stat_ht_lookups = stat_jump_in_lookups = stat_restore_tries =
6506   stat_restore_compares = stat_inv_addr_calls = stat_inv_hits = 0;
6507 #endif
6508 }
6509
6510 static int apply_hacks(void)
6511 {
6512   int i;
6513   if (HACK_ENABLED(NDHACK_NO_COMPAT_HACKS))
6514     return 0;
6515   /* special hack(s) */
6516   for (i = 0; i < slen - 4; i++)
6517   {
6518     // lui a4, 0xf200; jal <rcnt_read>; addu a0, 2; slti v0, 28224
6519     if (source[i] == 0x3c04f200 && dops[i+1].itype == UJUMP
6520         && source[i+2] == 0x34840002 && dops[i+3].opcode == 0x0a
6521         && imm[i+3] == 0x6e40 && dops[i+3].rs1 == 2)
6522     {
6523       SysPrintf("PE2 hack @%08x\n", start + (i+3)*4);
6524       dops[i + 3].itype = NOP;
6525     }
6526   }
6527   i = slen;
6528   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
6529       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
6530       && dops[i-7].itype == STORE)
6531   {
6532     i = i-8;
6533     if (dops[i].itype == IMM16)
6534       i--;
6535     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
6536     if (dops[i].itype == STORELR && dops[i].rs1 == 6
6537       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
6538     {
6539       SysPrintf("F1 hack from %08x, old dst %08x\n", start, hack_addr);
6540       f1_hack = 1;
6541       return 1;
6542     }
6543   }
6544   return 0;
6545 }
6546
6547 static noinline void pass1_disassemble(u_int pagelimit)
6548 {
6549   int i, j, done = 0, ni_count = 0;
6550   unsigned int type,op,op2;
6551
6552   for (i = 0; !done; i++)
6553   {
6554     memset(&dops[i], 0, sizeof(dops[i]));
6555     op2=0;
6556     minimum_free_regs[i]=0;
6557     dops[i].opcode=op=source[i]>>26;
6558     switch(op)
6559     {
6560       case 0x00: set_mnemonic(i, "special"); type=NI;
6561         op2=source[i]&0x3f;
6562         switch(op2)
6563         {
6564           case 0x00: set_mnemonic(i, "SLL"); type=SHIFTIMM; break;
6565           case 0x02: set_mnemonic(i, "SRL"); type=SHIFTIMM; break;
6566           case 0x03: set_mnemonic(i, "SRA"); type=SHIFTIMM; break;
6567           case 0x04: set_mnemonic(i, "SLLV"); type=SHIFT; break;
6568           case 0x06: set_mnemonic(i, "SRLV"); type=SHIFT; break;
6569           case 0x07: set_mnemonic(i, "SRAV"); type=SHIFT; break;
6570           case 0x08: set_mnemonic(i, "JR"); type=RJUMP; break;
6571           case 0x09: set_mnemonic(i, "JALR"); type=RJUMP; break;
6572           case 0x0C: set_mnemonic(i, "SYSCALL"); type=SYSCALL; break;
6573           case 0x0D: set_mnemonic(i, "BREAK"); type=SYSCALL; break;
6574           case 0x0F: set_mnemonic(i, "SYNC"); type=OTHER; break;
6575           case 0x10: set_mnemonic(i, "MFHI"); type=MOV; break;
6576           case 0x11: set_mnemonic(i, "MTHI"); type=MOV; break;
6577           case 0x12: set_mnemonic(i, "MFLO"); type=MOV; break;
6578           case 0x13: set_mnemonic(i, "MTLO"); type=MOV; break;
6579           case 0x18: set_mnemonic(i, "MULT"); type=MULTDIV; break;
6580           case 0x19: set_mnemonic(i, "MULTU"); type=MULTDIV; break;
6581           case 0x1A: set_mnemonic(i, "DIV"); type=MULTDIV; break;
6582           case 0x1B: set_mnemonic(i, "DIVU"); type=MULTDIV; break;
6583           case 0x20: set_mnemonic(i, "ADD"); type=ALU; break;
6584           case 0x21: set_mnemonic(i, "ADDU"); type=ALU; break;
6585           case 0x22: set_mnemonic(i, "SUB"); type=ALU; break;
6586           case 0x23: set_mnemonic(i, "SUBU"); type=ALU; break;
6587           case 0x24: set_mnemonic(i, "AND"); type=ALU; break;
6588           case 0x25: set_mnemonic(i, "OR"); type=ALU; break;
6589           case 0x26: set_mnemonic(i, "XOR"); type=ALU; break;
6590           case 0x27: set_mnemonic(i, "NOR"); type=ALU; break;
6591           case 0x2A: set_mnemonic(i, "SLT"); type=ALU; break;
6592           case 0x2B: set_mnemonic(i, "SLTU"); type=ALU; break;
6593           case 0x30: set_mnemonic(i, "TGE"); type=NI; break;
6594           case 0x31: set_mnemonic(i, "TGEU"); type=NI; break;
6595           case 0x32: set_mnemonic(i, "TLT"); type=NI; break;
6596           case 0x33: set_mnemonic(i, "TLTU"); type=NI; break;
6597           case 0x34: set_mnemonic(i, "TEQ"); type=NI; break;
6598           case 0x36: set_mnemonic(i, "TNE"); type=NI; break;
6599 #if 0
6600           case 0x14: set_mnemonic(i, "DSLLV"); type=SHIFT; break;
6601           case 0x16: set_mnemonic(i, "DSRLV"); type=SHIFT; break;
6602           case 0x17: set_mnemonic(i, "DSRAV"); type=SHIFT; break;
6603           case 0x1C: set_mnemonic(i, "DMULT"); type=MULTDIV; break;
6604           case 0x1D: set_mnemonic(i, "DMULTU"); type=MULTDIV; break;
6605           case 0x1E: set_mnemonic(i, "DDIV"); type=MULTDIV; break;
6606           case 0x1F: set_mnemonic(i, "DDIVU"); type=MULTDIV; break;
6607           case 0x2C: set_mnemonic(i, "DADD"); type=ALU; break;
6608           case 0x2D: set_mnemonic(i, "DADDU"); type=ALU; break;
6609           case 0x2E: set_mnemonic(i, "DSUB"); type=ALU; break;
6610           case 0x2F: set_mnemonic(i, "DSUBU"); type=ALU; break;
6611           case 0x38: set_mnemonic(i, "DSLL"); type=SHIFTIMM; break;
6612           case 0x3A: set_mnemonic(i, "DSRL"); type=SHIFTIMM; break;
6613           case 0x3B: set_mnemonic(i, "DSRA"); type=SHIFTIMM; break;
6614           case 0x3C: set_mnemonic(i, "DSLL32"); type=SHIFTIMM; break;
6615           case 0x3E: set_mnemonic(i, "DSRL32"); type=SHIFTIMM; break;
6616           case 0x3F: set_mnemonic(i, "DSRA32"); type=SHIFTIMM; break;
6617 #endif
6618         }
6619         break;
6620       case 0x01: set_mnemonic(i, "regimm"); type=NI;
6621         op2=(source[i]>>16)&0x1f;
6622         switch(op2)
6623         {
6624           case 0x00: set_mnemonic(i, "BLTZ"); type=SJUMP; break;
6625           case 0x01: set_mnemonic(i, "BGEZ"); type=SJUMP; break;
6626           //case 0x02: set_mnemonic(i, "BLTZL"); type=SJUMP; break;
6627           //case 0x03: set_mnemonic(i, "BGEZL"); type=SJUMP; break;
6628           //case 0x08: set_mnemonic(i, "TGEI"); type=NI; break;
6629           //case 0x09: set_mnemonic(i, "TGEIU"); type=NI; break;
6630           //case 0x0A: set_mnemonic(i, "TLTI"); type=NI; break;
6631           //case 0x0B: set_mnemonic(i, "TLTIU"); type=NI; break;
6632           //case 0x0C: set_mnemonic(i, "TEQI"); type=NI; break;
6633           //case 0x0E: set_mnemonic(i, "TNEI"); type=NI; break;
6634           case 0x10: set_mnemonic(i, "BLTZAL"); type=SJUMP; break;
6635           case 0x11: set_mnemonic(i, "BGEZAL"); type=SJUMP; break;
6636           //case 0x12: set_mnemonic(i, "BLTZALL"); type=SJUMP; break;
6637           //case 0x13: set_mnemonic(i, "BGEZALL"); type=SJUMP; break;
6638         }
6639         break;
6640       case 0x02: set_mnemonic(i, "J"); type=UJUMP; break;
6641       case 0x03: set_mnemonic(i, "JAL"); type=UJUMP; break;
6642       case 0x04: set_mnemonic(i, "BEQ"); type=CJUMP; break;
6643       case 0x05: set_mnemonic(i, "BNE"); type=CJUMP; break;
6644       case 0x06: set_mnemonic(i, "BLEZ"); type=CJUMP; break;
6645       case 0x07: set_mnemonic(i, "BGTZ"); type=CJUMP; break;
6646       case 0x08: set_mnemonic(i, "ADDI"); type=IMM16; break;
6647       case 0x09: set_mnemonic(i, "ADDIU"); type=IMM16; break;
6648       case 0x0A: set_mnemonic(i, "SLTI"); type=IMM16; break;
6649       case 0x0B: set_mnemonic(i, "SLTIU"); type=IMM16; break;
6650       case 0x0C: set_mnemonic(i, "ANDI"); type=IMM16; break;
6651       case 0x0D: set_mnemonic(i, "ORI"); type=IMM16; break;
6652       case 0x0E: set_mnemonic(i, "XORI"); type=IMM16; break;
6653       case 0x0F: set_mnemonic(i, "LUI"); type=IMM16; break;
6654       case 0x10: set_mnemonic(i, "cop0"); type=NI;
6655         op2=(source[i]>>21)&0x1f;
6656         switch(op2)
6657         {
6658           case 0x00: set_mnemonic(i, "MFC0"); type=COP0; break;
6659           case 0x02: set_mnemonic(i, "CFC0"); type=COP0; break;
6660           case 0x04: set_mnemonic(i, "MTC0"); type=COP0; break;
6661           case 0x06: set_mnemonic(i, "CTC0"); type=COP0; break;
6662           case 0x10: set_mnemonic(i, "RFE"); type=COP0; break;
6663         }
6664         break;
6665       case 0x11: set_mnemonic(i, "cop1"); type=COP1;
6666         op2=(source[i]>>21)&0x1f;
6667         break;
6668 #if 0
6669       case 0x14: set_mnemonic(i, "BEQL"); type=CJUMP; break;
6670       case 0x15: set_mnemonic(i, "BNEL"); type=CJUMP; break;
6671       case 0x16: set_mnemonic(i, "BLEZL"); type=CJUMP; break;
6672       case 0x17: set_mnemonic(i, "BGTZL"); type=CJUMP; break;
6673       case 0x18: set_mnemonic(i, "DADDI"); type=IMM16; break;
6674       case 0x19: set_mnemonic(i, "DADDIU"); type=IMM16; break;
6675       case 0x1A: set_mnemonic(i, "LDL"); type=LOADLR; break;
6676       case 0x1B: set_mnemonic(i, "LDR"); type=LOADLR; break;
6677 #endif
6678       case 0x20: set_mnemonic(i, "LB"); type=LOAD; break;
6679       case 0x21: set_mnemonic(i, "LH"); type=LOAD; break;
6680       case 0x22: set_mnemonic(i, "LWL"); type=LOADLR; break;
6681       case 0x23: set_mnemonic(i, "LW"); type=LOAD; break;
6682       case 0x24: set_mnemonic(i, "LBU"); type=LOAD; break;
6683       case 0x25: set_mnemonic(i, "LHU"); type=LOAD; break;
6684       case 0x26: set_mnemonic(i, "LWR"); type=LOADLR; break;
6685 #if 0
6686       case 0x27: set_mnemonic(i, "LWU"); type=LOAD; break;
6687 #endif
6688       case 0x28: set_mnemonic(i, "SB"); type=STORE; break;
6689       case 0x29: set_mnemonic(i, "SH"); type=STORE; break;
6690       case 0x2A: set_mnemonic(i, "SWL"); type=STORELR; break;
6691       case 0x2B: set_mnemonic(i, "SW"); type=STORE; break;
6692 #if 0
6693       case 0x2C: set_mnemonic(i, "SDL"); type=STORELR; break;
6694       case 0x2D: set_mnemonic(i, "SDR"); type=STORELR; break;
6695 #endif
6696       case 0x2E: set_mnemonic(i, "SWR"); type=STORELR; break;
6697       case 0x2F: set_mnemonic(i, "CACHE"); type=NOP; break;
6698       case 0x30: set_mnemonic(i, "LL"); type=NI; break;
6699       case 0x31: set_mnemonic(i, "LWC1"); type=C1LS; break;
6700 #if 0
6701       case 0x34: set_mnemonic(i, "LLD"); type=NI; break;
6702       case 0x35: set_mnemonic(i, "LDC1"); type=C1LS; break;
6703       case 0x37: set_mnemonic(i, "LD"); type=LOAD; break;
6704 #endif
6705       case 0x38: set_mnemonic(i, "SC"); type=NI; break;
6706       case 0x39: set_mnemonic(i, "SWC1"); type=C1LS; break;
6707 #if 0
6708       case 0x3C: set_mnemonic(i, "SCD"); type=NI; break;
6709       case 0x3D: set_mnemonic(i, "SDC1"); type=C1LS; break;
6710       case 0x3F: set_mnemonic(i, "SD"); type=STORE; break;
6711 #endif
6712       case 0x12: set_mnemonic(i, "COP2"); type=NI;
6713         op2=(source[i]>>21)&0x1f;
6714         //if (op2 & 0x10)
6715         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
6716           if (gte_handlers[source[i]&0x3f]!=NULL) {
6717 #ifdef DISASM
6718             if (gte_regnames[source[i]&0x3f]!=NULL)
6719               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
6720             else
6721               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
6722 #endif
6723             type=C2OP;
6724           }
6725         }
6726         else switch(op2)
6727         {
6728           case 0x00: set_mnemonic(i, "MFC2"); type=COP2; break;
6729           case 0x02: set_mnemonic(i, "CFC2"); type=COP2; break;
6730           case 0x04: set_mnemonic(i, "MTC2"); type=COP2; break;
6731           case 0x06: set_mnemonic(i, "CTC2"); type=COP2; break;
6732         }
6733         break;
6734       case 0x32: set_mnemonic(i, "LWC2"); type=C2LS; break;
6735       case 0x3A: set_mnemonic(i, "SWC2"); type=C2LS; break;
6736       case 0x3B: set_mnemonic(i, "HLECALL"); type=HLECALL; break;
6737       default: set_mnemonic(i, "???"); type=NI;
6738         SysPrintf("NI %08x @%08x (%08x)\n", source[i], start + i*4, start);
6739         break;
6740     }
6741     dops[i].itype=type;
6742     dops[i].opcode2=op2;
6743     /* Get registers/immediates */
6744     dops[i].use_lt1=0;
6745     gte_rs[i]=gte_rt[i]=0;
6746     switch(type) {
6747       case LOAD:
6748         dops[i].rs1=(source[i]>>21)&0x1f;
6749         dops[i].rs2=0;
6750         dops[i].rt1=(source[i]>>16)&0x1f;
6751         dops[i].rt2=0;
6752         imm[i]=(short)source[i];
6753         break;
6754       case STORE:
6755       case STORELR:
6756         dops[i].rs1=(source[i]>>21)&0x1f;
6757         dops[i].rs2=(source[i]>>16)&0x1f;
6758         dops[i].rt1=0;
6759         dops[i].rt2=0;
6760         imm[i]=(short)source[i];
6761         break;
6762       case LOADLR:
6763         // LWL/LWR only load part of the register,
6764         // therefore the target register must be treated as a source too
6765         dops[i].rs1=(source[i]>>21)&0x1f;
6766         dops[i].rs2=(source[i]>>16)&0x1f;
6767         dops[i].rt1=(source[i]>>16)&0x1f;
6768         dops[i].rt2=0;
6769         imm[i]=(short)source[i];
6770         break;
6771       case IMM16:
6772         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
6773         else dops[i].rs1=(source[i]>>21)&0x1f;
6774         dops[i].rs2=0;
6775         dops[i].rt1=(source[i]>>16)&0x1f;
6776         dops[i].rt2=0;
6777         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
6778           imm[i]=(unsigned short)source[i];
6779         }else{
6780           imm[i]=(short)source[i];
6781         }
6782         break;
6783       case UJUMP:
6784         dops[i].rs1=0;
6785         dops[i].rs2=0;
6786         dops[i].rt1=0;
6787         dops[i].rt2=0;
6788         // The JAL instruction writes to r31.
6789         if (op&1) {
6790           dops[i].rt1=31;
6791         }
6792         dops[i].rs2=CCREG;
6793         break;
6794       case RJUMP:
6795         dops[i].rs1=(source[i]>>21)&0x1f;
6796         dops[i].rs2=0;
6797         dops[i].rt1=0;
6798         dops[i].rt2=0;
6799         // The JALR instruction writes to rd.
6800         if (op2&1) {
6801           dops[i].rt1=(source[i]>>11)&0x1f;
6802         }
6803         dops[i].rs2=CCREG;
6804         break;
6805       case CJUMP:
6806         dops[i].rs1=(source[i]>>21)&0x1f;
6807         dops[i].rs2=(source[i]>>16)&0x1f;
6808         dops[i].rt1=0;
6809         dops[i].rt2=0;
6810         if(op&2) { // BGTZ/BLEZ
6811           dops[i].rs2=0;
6812         }
6813         break;
6814       case SJUMP:
6815         dops[i].rs1=(source[i]>>21)&0x1f;
6816         dops[i].rs2=CCREG;
6817         dops[i].rt1=0;
6818         dops[i].rt2=0;
6819         if(op2&0x10) { // BxxAL
6820           dops[i].rt1=31;
6821           // NOTE: If the branch is not taken, r31 is still overwritten
6822         }
6823         break;
6824       case ALU:
6825         dops[i].rs1=(source[i]>>21)&0x1f; // source
6826         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
6827         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6828         dops[i].rt2=0;
6829         break;
6830       case MULTDIV:
6831         dops[i].rs1=(source[i]>>21)&0x1f; // source
6832         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
6833         dops[i].rt1=HIREG;
6834         dops[i].rt2=LOREG;
6835         break;
6836       case MOV:
6837         dops[i].rs1=0;
6838         dops[i].rs2=0;
6839         dops[i].rt1=0;
6840         dops[i].rt2=0;
6841         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
6842         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
6843         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
6844         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
6845         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
6846         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
6847         break;
6848       case SHIFT:
6849         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
6850         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
6851         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6852         dops[i].rt2=0;
6853         break;
6854       case SHIFTIMM:
6855         dops[i].rs1=(source[i]>>16)&0x1f;
6856         dops[i].rs2=0;
6857         dops[i].rt1=(source[i]>>11)&0x1f;
6858         dops[i].rt2=0;
6859         imm[i]=(source[i]>>6)&0x1f;
6860         // DSxx32 instructions
6861         if(op2>=0x3c) imm[i]|=0x20;
6862         break;
6863       case COP0:
6864         dops[i].rs1=0;
6865         dops[i].rs2=0;
6866         dops[i].rt1=0;
6867         dops[i].rt2=0;
6868         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
6869         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
6870         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
6871         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
6872         break;
6873       case COP1:
6874         dops[i].rs1=0;
6875         dops[i].rs2=0;
6876         dops[i].rt1=0;
6877         dops[i].rt2=0;
6878         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
6879         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
6880         dops[i].rs2=CSREG;
6881         break;
6882       case COP2:
6883         dops[i].rs1=0;
6884         dops[i].rs2=0;
6885         dops[i].rt1=0;
6886         dops[i].rt2=0;
6887         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
6888         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
6889         dops[i].rs2=CSREG;
6890         int gr=(source[i]>>11)&0x1F;
6891         switch(op2)
6892         {
6893           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
6894           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
6895           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
6896           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
6897         }
6898         break;
6899       case C1LS:
6900         dops[i].rs1=(source[i]>>21)&0x1F;
6901         dops[i].rs2=CSREG;
6902         dops[i].rt1=0;
6903         dops[i].rt2=0;
6904         imm[i]=(short)source[i];
6905         break;
6906       case C2LS:
6907         dops[i].rs1=(source[i]>>21)&0x1F;
6908         dops[i].rs2=0;
6909         dops[i].rt1=0;
6910         dops[i].rt2=0;
6911         imm[i]=(short)source[i];
6912         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
6913         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
6914         break;
6915       case C2OP:
6916         dops[i].rs1=0;
6917         dops[i].rs2=0;
6918         dops[i].rt1=0;
6919         dops[i].rt2=0;
6920         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
6921         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
6922         gte_rt[i]|=1ll<<63; // every op changes flags
6923         if((source[i]&0x3f)==GTE_MVMVA) {
6924           int v = (source[i] >> 15) & 3;
6925           gte_rs[i]&=~0xe3fll;
6926           if(v==3) gte_rs[i]|=0xe00ll;
6927           else gte_rs[i]|=3ll<<(v*2);
6928         }
6929         break;
6930       case SYSCALL:
6931       case HLECALL:
6932       case INTCALL:
6933         dops[i].rs1=CCREG;
6934         dops[i].rs2=0;
6935         dops[i].rt1=0;
6936         dops[i].rt2=0;
6937         break;
6938       default:
6939         dops[i].rs1=0;
6940         dops[i].rs2=0;
6941         dops[i].rt1=0;
6942         dops[i].rt2=0;
6943     }
6944     /* Calculate branch target addresses */
6945     if(type==UJUMP)
6946       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
6947     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
6948       ba[i]=start+i*4+8; // Ignore never taken branch
6949     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
6950       ba[i]=start+i*4+8; // Ignore never taken branch
6951     else if(type==CJUMP||type==SJUMP)
6952       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
6953     else ba[i]=-1;
6954
6955     /* simplify always (not)taken branches */
6956     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
6957       dops[i].rs1 = dops[i].rs2 = 0;
6958       if (!(op & 1)) {
6959         dops[i].itype = type = UJUMP;
6960         dops[i].rs2 = CCREG;
6961       }
6962     }
6963     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
6964       dops[i].itype = type = UJUMP;
6965
6966     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
6967     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
6968     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
6969     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
6970
6971     /* messy cases to just pass over to the interpreter */
6972     if (i > 0 && dops[i-1].is_jump) {
6973       int do_in_intrp=0;
6974       // branch in delay slot?
6975       if (dops[i].is_jump) {
6976         // don't handle first branch and call interpreter if it's hit
6977         SysPrintf("branch in delay slot @%08x (%08x)\n", start + i*4, start);
6978         do_in_intrp=1;
6979       }
6980       // basic load delay detection
6981       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
6982         int t=(ba[i-1]-start)/4;
6983         if(0 <= t && t < i &&(dops[i].rt1==dops[t].rs1||dops[i].rt1==dops[t].rs2)&&dops[t].itype!=CJUMP&&dops[t].itype!=SJUMP) {
6984           // jump target wants DS result - potential load delay effect
6985           SysPrintf("load delay @%08x (%08x)\n", start + i*4, start);
6986           do_in_intrp=1;
6987           dops[t+1].bt=1; // expected return from interpreter
6988         }
6989         else if(i>=2&&dops[i-2].rt1==2&&dops[i].rt1==2&&dops[i].rs1!=2&&dops[i].rs2!=2&&dops[i-1].rs1!=2&&dops[i-1].rs2!=2&&
6990               !(i>=3&&dops[i-3].is_jump)) {
6991           // v0 overwrite like this is a sign of trouble, bail out
6992           SysPrintf("v0 overwrite @%08x (%08x)\n", start + i*4, start);
6993           do_in_intrp=1;
6994         }
6995       }
6996       if (do_in_intrp) {
6997         memset(&dops[i-1], 0, sizeof(dops[i-1]));
6998         dops[i-1].itype = INTCALL;
6999         dops[i-1].rs1 = CCREG;
7000         ba[i-1] = -1;
7001         done = 2;
7002         i--; // don't compile the DS
7003       }
7004     }
7005
7006     /* Is this the end of the block? */
7007     if (i > 0 && dops[i-1].is_ujump) {
7008       if (dops[i-1].rt1 == 0) { // not jal
7009         int found_bbranch = 0, t = (ba[i-1] - start) / 4;
7010         if ((u_int)(t - i) < 64 && start + (t+64)*4 < pagelimit) {
7011           // scan for a branch back to i+1
7012           for (j = t; j < t + 64; j++) {
7013             int tmpop = source[j] >> 26;
7014             if (tmpop == 1 || ((tmpop & ~3) == 4)) {
7015               int t2 = j + 1 + (int)(signed short)source[j];
7016               if (t2 == i + 1) {
7017                 //printf("blk expand %08x<-%08x\n", start + (i+1)*4, start + j*4);
7018                 found_bbranch = 1;
7019                 break;
7020               }
7021             }
7022           }
7023         }
7024         if (!found_bbranch)
7025           done = 2;
7026       }
7027       else {
7028         if(stop_after_jal) done=1;
7029         // Stop on BREAK
7030         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7031       }
7032       // Don't recompile stuff that's already compiled
7033       if(check_addr(start+i*4+4)) done=1;
7034       // Don't get too close to the limit
7035       if(i>MAXBLOCK/2) done=1;
7036     }
7037     if (dops[i].itype == SYSCALL || dops[i].itype == HLECALL || dops[i].itype == INTCALL)
7038       done = stop_after_jal ? 1 : 2;
7039     if (done == 2) {
7040       // Does the block continue due to a branch?
7041       for(j=i-1;j>=0;j--)
7042       {
7043         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7044         if(ba[j]==start+i*4+4) done=j=0;
7045         if(ba[j]==start+i*4+8) done=j=0;
7046       }
7047     }
7048     //assert(i<MAXBLOCK-1);
7049     if(start+i*4==pagelimit-4) done=1;
7050     assert(start+i*4<pagelimit);
7051     if (i==MAXBLOCK-1) done=1;
7052     // Stop if we're compiling junk
7053     if(dops[i].itype == NI && (++ni_count > 8 || dops[i].opcode == 0x11)) {
7054       done=stop_after_jal=1;
7055       SysPrintf("Disabled speculative precompilation\n");
7056     }
7057   }
7058   while (i > 0 && dops[i-1].is_jump)
7059     i--;
7060   assert(i > 0);
7061   assert(!dops[i-1].is_jump);
7062   slen = i;
7063 }
7064
7065 // Basic liveness analysis for MIPS registers
7066 static noinline void pass2_unneeded_regs(int istart,int iend,int r)
7067 {
7068   int i;
7069   uint64_t u,gte_u,b,gte_b;
7070   uint64_t temp_u,temp_gte_u=0;
7071   uint64_t gte_u_unknown=0;
7072   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
7073     gte_u_unknown=~0ll;
7074   if(iend==slen-1) {
7075     u=1;
7076     gte_u=gte_u_unknown;
7077   }else{
7078     //u=unneeded_reg[iend+1];
7079     u=1;
7080     gte_u=gte_unneeded[iend+1];
7081   }
7082
7083   for (i=iend;i>=istart;i--)
7084   {
7085     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
7086     if(dops[i].is_jump)
7087     {
7088       // If subroutine call, flag return address as a possible branch target
7089       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
7090
7091       if(ba[i]<start || ba[i]>=(start+slen*4))
7092       {
7093         // Branch out of this block, flush all regs
7094         u=1;
7095         gte_u=gte_u_unknown;
7096         branch_unneeded_reg[i]=u;
7097         // Merge in delay slot
7098         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7099         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7100         u|=1;
7101         gte_u|=gte_rt[i+1];
7102         gte_u&=~gte_rs[i+1];
7103       }
7104       else
7105       {
7106         // Internal branch, flag target
7107         dops[(ba[i]-start)>>2].bt=1;
7108         if(ba[i]<=start+i*4) {
7109           // Backward branch
7110           if(dops[i].is_ujump)
7111           {
7112             // Unconditional branch
7113             temp_u=1;
7114             temp_gte_u=0;
7115           } else {
7116             // Conditional branch (not taken case)
7117             temp_u=unneeded_reg[i+2];
7118             temp_gte_u&=gte_unneeded[i+2];
7119           }
7120           // Merge in delay slot
7121           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7122           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7123           temp_u|=1;
7124           temp_gte_u|=gte_rt[i+1];
7125           temp_gte_u&=~gte_rs[i+1];
7126           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
7127           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7128           temp_u|=1;
7129           temp_gte_u|=gte_rt[i];
7130           temp_gte_u&=~gte_rs[i];
7131           unneeded_reg[i]=temp_u;
7132           gte_unneeded[i]=temp_gte_u;
7133           // Only go three levels deep.  This recursion can take an
7134           // excessive amount of time if there are a lot of nested loops.
7135           if(r<2) {
7136             pass2_unneeded_regs((ba[i]-start)>>2,i-1,r+1);
7137           }else{
7138             unneeded_reg[(ba[i]-start)>>2]=1;
7139             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
7140           }
7141         } /*else*/ if(1) {
7142           if (dops[i].is_ujump)
7143           {
7144             // Unconditional branch
7145             u=unneeded_reg[(ba[i]-start)>>2];
7146             gte_u=gte_unneeded[(ba[i]-start)>>2];
7147             branch_unneeded_reg[i]=u;
7148             // Merge in delay slot
7149             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7150             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7151             u|=1;
7152             gte_u|=gte_rt[i+1];
7153             gte_u&=~gte_rs[i+1];
7154           } else {
7155             // Conditional branch
7156             b=unneeded_reg[(ba[i]-start)>>2];
7157             gte_b=gte_unneeded[(ba[i]-start)>>2];
7158             branch_unneeded_reg[i]=b;
7159             // Branch delay slot
7160             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7161             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7162             b|=1;
7163             gte_b|=gte_rt[i+1];
7164             gte_b&=~gte_rs[i+1];
7165             u&=b;
7166             gte_u&=gte_b;
7167             if(i<slen-1) {
7168               branch_unneeded_reg[i]&=unneeded_reg[i+2];
7169             } else {
7170               branch_unneeded_reg[i]=1;
7171             }
7172           }
7173         }
7174       }
7175     }
7176     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7177     {
7178       // SYSCALL instruction (software interrupt)
7179       u=1;
7180     }
7181     else if(dops[i].itype==COP0 && dops[i].opcode2==0x10)
7182     {
7183       // RFE
7184       u=1;
7185     }
7186     //u=1; // DEBUG
7187     // Written registers are unneeded
7188     u|=1LL<<dops[i].rt1;
7189     u|=1LL<<dops[i].rt2;
7190     gte_u|=gte_rt[i];
7191     // Accessed registers are needed
7192     u&=~(1LL<<dops[i].rs1);
7193     u&=~(1LL<<dops[i].rs2);
7194     gte_u&=~gte_rs[i];
7195     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
7196       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
7197     // Source-target dependencies
7198     // R0 is always unneeded
7199     u|=1;
7200     // Save it
7201     unneeded_reg[i]=u;
7202     gte_unneeded[i]=gte_u;
7203     /*
7204     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
7205     printf("U:");
7206     int r;
7207     for(r=1;r<=CCREG;r++) {
7208       if((unneeded_reg[i]>>r)&1) {
7209         if(r==HIREG) printf(" HI");
7210         else if(r==LOREG) printf(" LO");
7211         else printf(" r%d",r);
7212       }
7213     }
7214     printf("\n");
7215     */
7216   }
7217 }
7218
7219 static noinline void pass3_register_alloc(u_int addr)
7220 {
7221   struct regstat current; // Current register allocations/status
7222   clear_all_regs(current.regmap_entry);
7223   clear_all_regs(current.regmap);
7224   current.wasdirty = current.dirty = 0;
7225   current.u = unneeded_reg[0];
7226   alloc_reg(&current, 0, CCREG);
7227   dirty_reg(&current, CCREG);
7228   current.wasconst = 0;
7229   current.isconst = 0;
7230   current.loadedconst = 0;
7231   //current.waswritten = 0;
7232   int ds=0;
7233   int cc=0;
7234   int hr;
7235   int i, j;
7236
7237   if (addr & 1) {
7238     // First instruction is delay slot
7239     cc=-1;
7240     dops[1].bt=1;
7241     ds=1;
7242     unneeded_reg[0]=1;
7243     current.regmap[HOST_BTREG]=BTREG;
7244   }
7245
7246   for(i=0;i<slen;i++)
7247   {
7248     if(dops[i].bt)
7249     {
7250       for(hr=0;hr<HOST_REGS;hr++)
7251       {
7252         // Is this really necessary?
7253         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7254       }
7255       current.isconst=0;
7256       //current.waswritten=0;
7257     }
7258
7259     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7260     regs[i].wasconst=current.isconst;
7261     regs[i].wasdirty=current.dirty;
7262     regs[i].dirty=0;
7263     regs[i].u=0;
7264     regs[i].isconst=0;
7265     regs[i].loadedconst=0;
7266     if (!dops[i].is_jump) {
7267       if(i+1<slen) {
7268         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7269         current.u|=1;
7270       } else {
7271         current.u=1;
7272       }
7273     } else {
7274       if(i+1<slen) {
7275         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7276         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7277         current.u|=1;
7278       } else {
7279         SysPrintf("oops, branch at end of block with no delay slot @%08x\n", start + i*4);
7280         abort();
7281       }
7282     }
7283     dops[i].is_ds=ds;
7284     if(ds) {
7285       ds=0; // Skip delay slot, already allocated as part of branch
7286       // ...but we need to alloc it in case something jumps here
7287       if(i+1<slen) {
7288         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7289       }else{
7290         current.u=branch_unneeded_reg[i-1];
7291       }
7292       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7293       current.u|=1;
7294       struct regstat temp;
7295       memcpy(&temp,&current,sizeof(current));
7296       temp.wasdirty=temp.dirty;
7297       // TODO: Take into account unconditional branches, as below
7298       delayslot_alloc(&temp,i);
7299       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7300       regs[i].wasdirty=temp.wasdirty;
7301       regs[i].dirty=temp.dirty;
7302       regs[i].isconst=0;
7303       regs[i].wasconst=0;
7304       current.isconst=0;
7305       // Create entry (branch target) regmap
7306       for(hr=0;hr<HOST_REGS;hr++)
7307       {
7308         int r=temp.regmap[hr];
7309         if(r>=0) {
7310           if(r!=regmap_pre[i][hr]) {
7311             regs[i].regmap_entry[hr]=-1;
7312           }
7313           else
7314           {
7315               assert(r < 64);
7316               if((current.u>>r)&1) {
7317                 regs[i].regmap_entry[hr]=-1;
7318                 regs[i].regmap[hr]=-1;
7319                 //Don't clear regs in the delay slot as the branch might need them
7320                 //current.regmap[hr]=-1;
7321               }else
7322                 regs[i].regmap_entry[hr]=r;
7323           }
7324         } else {
7325           // First instruction expects CCREG to be allocated
7326           if(i==0&&hr==HOST_CCREG)
7327             regs[i].regmap_entry[hr]=CCREG;
7328           else
7329             regs[i].regmap_entry[hr]=-1;
7330         }
7331       }
7332     }
7333     else { // Not delay slot
7334       switch(dops[i].itype) {
7335         case UJUMP:
7336           //current.isconst=0; // DEBUG
7337           //current.wasconst=0; // DEBUG
7338           //regs[i].wasconst=0; // DEBUG
7339           clear_const(&current,dops[i].rt1);
7340           alloc_cc(&current,i);
7341           dirty_reg(&current,CCREG);
7342           if (dops[i].rt1==31) {
7343             alloc_reg(&current,i,31);
7344             dirty_reg(&current,31);
7345             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7346             //assert(dops[i+1].rt1!=dops[i].rt1);
7347             #ifdef REG_PREFETCH
7348             alloc_reg(&current,i,PTEMP);
7349             #endif
7350           }
7351           dops[i].ooo=1;
7352           delayslot_alloc(&current,i+1);
7353           //current.isconst=0; // DEBUG
7354           ds=1;
7355           //printf("i=%d, isconst=%x\n",i,current.isconst);
7356           break;
7357         case RJUMP:
7358           //current.isconst=0;
7359           //current.wasconst=0;
7360           //regs[i].wasconst=0;
7361           clear_const(&current,dops[i].rs1);
7362           clear_const(&current,dops[i].rt1);
7363           alloc_cc(&current,i);
7364           dirty_reg(&current,CCREG);
7365           if (!ds_writes_rjump_rs(i)) {
7366             alloc_reg(&current,i,dops[i].rs1);
7367             if (dops[i].rt1!=0) {
7368               alloc_reg(&current,i,dops[i].rt1);
7369               dirty_reg(&current,dops[i].rt1);
7370               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7371               assert(dops[i+1].rt1!=dops[i].rt1);
7372               #ifdef REG_PREFETCH
7373               alloc_reg(&current,i,PTEMP);
7374               #endif
7375             }
7376             #ifdef USE_MINI_HT
7377             if(dops[i].rs1==31) { // JALR
7378               alloc_reg(&current,i,RHASH);
7379               alloc_reg(&current,i,RHTBL);
7380             }
7381             #endif
7382             delayslot_alloc(&current,i+1);
7383           } else {
7384             // The delay slot overwrites our source register,
7385             // allocate a temporary register to hold the old value.
7386             current.isconst=0;
7387             current.wasconst=0;
7388             regs[i].wasconst=0;
7389             delayslot_alloc(&current,i+1);
7390             current.isconst=0;
7391             alloc_reg(&current,i,RTEMP);
7392           }
7393           //current.isconst=0; // DEBUG
7394           dops[i].ooo=1;
7395           ds=1;
7396           break;
7397         case CJUMP:
7398           //current.isconst=0;
7399           //current.wasconst=0;
7400           //regs[i].wasconst=0;
7401           clear_const(&current,dops[i].rs1);
7402           clear_const(&current,dops[i].rs2);
7403           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7404           {
7405             alloc_cc(&current,i);
7406             dirty_reg(&current,CCREG);
7407             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7408             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7409             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7410                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7411               // The delay slot overwrites one of our conditions.
7412               // Allocate the branch condition registers instead.
7413               current.isconst=0;
7414               current.wasconst=0;
7415               regs[i].wasconst=0;
7416               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7417               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7418             }
7419             else
7420             {
7421               dops[i].ooo=1;
7422               delayslot_alloc(&current,i+1);
7423             }
7424           }
7425           else
7426           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7427           {
7428             alloc_cc(&current,i);
7429             dirty_reg(&current,CCREG);
7430             alloc_reg(&current,i,dops[i].rs1);
7431             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7432               // The delay slot overwrites one of our conditions.
7433               // Allocate the branch condition registers instead.
7434               current.isconst=0;
7435               current.wasconst=0;
7436               regs[i].wasconst=0;
7437               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7438             }
7439             else
7440             {
7441               dops[i].ooo=1;
7442               delayslot_alloc(&current,i+1);
7443             }
7444           }
7445           else
7446           // Don't alloc the delay slot yet because we might not execute it
7447           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7448           {
7449             current.isconst=0;
7450             current.wasconst=0;
7451             regs[i].wasconst=0;
7452             alloc_cc(&current,i);
7453             dirty_reg(&current,CCREG);
7454             alloc_reg(&current,i,dops[i].rs1);
7455             alloc_reg(&current,i,dops[i].rs2);
7456           }
7457           else
7458           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7459           {
7460             current.isconst=0;
7461             current.wasconst=0;
7462             regs[i].wasconst=0;
7463             alloc_cc(&current,i);
7464             dirty_reg(&current,CCREG);
7465             alloc_reg(&current,i,dops[i].rs1);
7466           }
7467           ds=1;
7468           //current.isconst=0;
7469           break;
7470         case SJUMP:
7471           //current.isconst=0;
7472           //current.wasconst=0;
7473           //regs[i].wasconst=0;
7474           clear_const(&current,dops[i].rs1);
7475           clear_const(&current,dops[i].rt1);
7476           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7477           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7478           {
7479             alloc_cc(&current,i);
7480             dirty_reg(&current,CCREG);
7481             alloc_reg(&current,i,dops[i].rs1);
7482             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7483               alloc_reg(&current,i,31);
7484               dirty_reg(&current,31);
7485               //#ifdef REG_PREFETCH
7486               //alloc_reg(&current,i,PTEMP);
7487               //#endif
7488             }
7489             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) // The delay slot overwrites the branch condition.
7490                ||(dops[i].rt1==31&&(dops[i+1].rs1==31||dops[i+1].rs2==31||dops[i+1].rt1==31||dops[i+1].rt2==31))) { // DS touches $ra
7491               // Allocate the branch condition registers instead.
7492               current.isconst=0;
7493               current.wasconst=0;
7494               regs[i].wasconst=0;
7495               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7496             }
7497             else
7498             {
7499               dops[i].ooo=1;
7500               delayslot_alloc(&current,i+1);
7501             }
7502           }
7503           else
7504           // Don't alloc the delay slot yet because we might not execute it
7505           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7506           {
7507             current.isconst=0;
7508             current.wasconst=0;
7509             regs[i].wasconst=0;
7510             alloc_cc(&current,i);
7511             dirty_reg(&current,CCREG);
7512             alloc_reg(&current,i,dops[i].rs1);
7513           }
7514           ds=1;
7515           //current.isconst=0;
7516           break;
7517         case IMM16:
7518           imm16_alloc(&current,i);
7519           break;
7520         case LOAD:
7521         case LOADLR:
7522           load_alloc(&current,i);
7523           break;
7524         case STORE:
7525         case STORELR:
7526           store_alloc(&current,i);
7527           break;
7528         case ALU:
7529           alu_alloc(&current,i);
7530           break;
7531         case SHIFT:
7532           shift_alloc(&current,i);
7533           break;
7534         case MULTDIV:
7535           multdiv_alloc(&current,i);
7536           break;
7537         case SHIFTIMM:
7538           shiftimm_alloc(&current,i);
7539           break;
7540         case MOV:
7541           mov_alloc(&current,i);
7542           break;
7543         case COP0:
7544           cop0_alloc(&current,i);
7545           break;
7546         case COP1:
7547           break;
7548         case COP2:
7549           cop2_alloc(&current,i);
7550           break;
7551         case C1LS:
7552           c1ls_alloc(&current,i);
7553           break;
7554         case C2LS:
7555           c2ls_alloc(&current,i);
7556           break;
7557         case C2OP:
7558           c2op_alloc(&current,i);
7559           break;
7560         case SYSCALL:
7561         case HLECALL:
7562         case INTCALL:
7563           syscall_alloc(&current,i);
7564           break;
7565       }
7566
7567       // Create entry (branch target) regmap
7568       for(hr=0;hr<HOST_REGS;hr++)
7569       {
7570         int r,or;
7571         r=current.regmap[hr];
7572         if(r>=0) {
7573           if(r!=regmap_pre[i][hr]) {
7574             // TODO: delay slot (?)
7575             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7576             if(or<0||r>=TEMPREG){
7577               regs[i].regmap_entry[hr]=-1;
7578             }
7579             else
7580             {
7581               // Just move it to a different register
7582               regs[i].regmap_entry[hr]=r;
7583               // If it was dirty before, it's still dirty
7584               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r);
7585             }
7586           }
7587           else
7588           {
7589             // Unneeded
7590             if(r==0){
7591               regs[i].regmap_entry[hr]=0;
7592             }
7593             else
7594             {
7595               assert(r<64);
7596               if((current.u>>r)&1) {
7597                 regs[i].regmap_entry[hr]=-1;
7598                 //regs[i].regmap[hr]=-1;
7599                 current.regmap[hr]=-1;
7600               }else
7601                 regs[i].regmap_entry[hr]=r;
7602             }
7603           }
7604         } else {
7605           // Branches expect CCREG to be allocated at the target
7606           if(regmap_pre[i][hr]==CCREG)
7607             regs[i].regmap_entry[hr]=CCREG;
7608           else
7609             regs[i].regmap_entry[hr]=-1;
7610         }
7611       }
7612       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7613     }
7614
7615 #if 0 // see do_store_smc_check()
7616     if(i>0&&(dops[i-1].itype==STORE||dops[i-1].itype==STORELR||(dops[i-1].itype==C2LS&&dops[i-1].opcode==0x3a))&&(u_int)imm[i-1]<0x800)
7617       current.waswritten|=1<<dops[i-1].rs1;
7618     current.waswritten&=~(1<<dops[i].rt1);
7619     current.waswritten&=~(1<<dops[i].rt2);
7620     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
7621       current.waswritten&=~(1<<dops[i].rs1);
7622 #endif
7623
7624     /* Branch post-alloc */
7625     if(i>0)
7626     {
7627       current.wasdirty=current.dirty;
7628       switch(dops[i-1].itype) {
7629         case UJUMP:
7630           memcpy(&branch_regs[i-1],&current,sizeof(current));
7631           branch_regs[i-1].isconst=0;
7632           branch_regs[i-1].wasconst=0;
7633           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7634           alloc_cc(&branch_regs[i-1],i-1);
7635           dirty_reg(&branch_regs[i-1],CCREG);
7636           if(dops[i-1].rt1==31) { // JAL
7637             alloc_reg(&branch_regs[i-1],i-1,31);
7638             dirty_reg(&branch_regs[i-1],31);
7639           }
7640           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7641           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7642           break;
7643         case RJUMP:
7644           memcpy(&branch_regs[i-1],&current,sizeof(current));
7645           branch_regs[i-1].isconst=0;
7646           branch_regs[i-1].wasconst=0;
7647           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7648           alloc_cc(&branch_regs[i-1],i-1);
7649           dirty_reg(&branch_regs[i-1],CCREG);
7650           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
7651           if(dops[i-1].rt1!=0) { // JALR
7652             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
7653             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
7654           }
7655           #ifdef USE_MINI_HT
7656           if(dops[i-1].rs1==31) { // JALR
7657             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7658             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7659           }
7660           #endif
7661           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7662           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7663           break;
7664         case CJUMP:
7665           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
7666           {
7667             alloc_cc(&current,i-1);
7668             dirty_reg(&current,CCREG);
7669             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
7670                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
7671               // The delay slot overwrote one of our conditions
7672               // Delay slot goes after the test (in order)
7673               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7674               current.u|=1;
7675               delayslot_alloc(&current,i);
7676               current.isconst=0;
7677             }
7678             else
7679             {
7680               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7681               // Alloc the branch condition registers
7682               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
7683               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
7684             }
7685             memcpy(&branch_regs[i-1],&current,sizeof(current));
7686             branch_regs[i-1].isconst=0;
7687             branch_regs[i-1].wasconst=0;
7688             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7689             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7690           }
7691           else
7692           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
7693           {
7694             alloc_cc(&current,i-1);
7695             dirty_reg(&current,CCREG);
7696             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7697               // The delay slot overwrote the branch condition
7698               // Delay slot goes after the test (in order)
7699               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7700               current.u|=1;
7701               delayslot_alloc(&current,i);
7702               current.isconst=0;
7703             }
7704             else
7705             {
7706               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7707               // Alloc the branch condition register
7708               alloc_reg(&current,i-1,dops[i-1].rs1);
7709             }
7710             memcpy(&branch_regs[i-1],&current,sizeof(current));
7711             branch_regs[i-1].isconst=0;
7712             branch_regs[i-1].wasconst=0;
7713             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7714             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7715           }
7716           else
7717           // Alloc the delay slot in case the branch is taken
7718           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
7719           {
7720             memcpy(&branch_regs[i-1],&current,sizeof(current));
7721             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7722             alloc_cc(&branch_regs[i-1],i);
7723             dirty_reg(&branch_regs[i-1],CCREG);
7724             delayslot_alloc(&branch_regs[i-1],i);
7725             branch_regs[i-1].isconst=0;
7726             alloc_reg(&current,i,CCREG); // Not taken path
7727             dirty_reg(&current,CCREG);
7728             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7729           }
7730           else
7731           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
7732           {
7733             memcpy(&branch_regs[i-1],&current,sizeof(current));
7734             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7735             alloc_cc(&branch_regs[i-1],i);
7736             dirty_reg(&branch_regs[i-1],CCREG);
7737             delayslot_alloc(&branch_regs[i-1],i);
7738             branch_regs[i-1].isconst=0;
7739             alloc_reg(&current,i,CCREG); // Not taken path
7740             dirty_reg(&current,CCREG);
7741             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7742           }
7743           break;
7744         case SJUMP:
7745           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
7746           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
7747           {
7748             alloc_cc(&current,i-1);
7749             dirty_reg(&current,CCREG);
7750             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7751               // The delay slot overwrote the branch condition
7752               // Delay slot goes after the test (in order)
7753               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7754               current.u|=1;
7755               delayslot_alloc(&current,i);
7756               current.isconst=0;
7757             }
7758             else
7759             {
7760               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7761               // Alloc the branch condition register
7762               alloc_reg(&current,i-1,dops[i-1].rs1);
7763             }
7764             memcpy(&branch_regs[i-1],&current,sizeof(current));
7765             branch_regs[i-1].isconst=0;
7766             branch_regs[i-1].wasconst=0;
7767             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7768             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7769           }
7770           else
7771           // Alloc the delay slot in case the branch is taken
7772           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
7773           {
7774             memcpy(&branch_regs[i-1],&current,sizeof(current));
7775             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
7776             alloc_cc(&branch_regs[i-1],i);
7777             dirty_reg(&branch_regs[i-1],CCREG);
7778             delayslot_alloc(&branch_regs[i-1],i);
7779             branch_regs[i-1].isconst=0;
7780             alloc_reg(&current,i,CCREG); // Not taken path
7781             dirty_reg(&current,CCREG);
7782             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7783           }
7784           // FIXME: BLTZAL/BGEZAL
7785           if(dops[i-1].opcode2&0x10) { // BxxZAL
7786             alloc_reg(&branch_regs[i-1],i-1,31);
7787             dirty_reg(&branch_regs[i-1],31);
7788           }
7789           break;
7790       }
7791
7792       if (dops[i-1].is_ujump)
7793       {
7794         if(dops[i-1].rt1==31) // JAL/JALR
7795         {
7796           // Subroutine call will return here, don't alloc any registers
7797           current.dirty=0;
7798           clear_all_regs(current.regmap);
7799           alloc_reg(&current,i,CCREG);
7800           dirty_reg(&current,CCREG);
7801         }
7802         else if(i+1<slen)
7803         {
7804           // Internal branch will jump here, match registers to caller
7805           current.dirty=0;
7806           clear_all_regs(current.regmap);
7807           alloc_reg(&current,i,CCREG);
7808           dirty_reg(&current,CCREG);
7809           for(j=i-1;j>=0;j--)
7810           {
7811             if(ba[j]==start+i*4+4) {
7812               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
7813               current.dirty=branch_regs[j].dirty;
7814               break;
7815             }
7816           }
7817           while(j>=0) {
7818             if(ba[j]==start+i*4+4) {
7819               for(hr=0;hr<HOST_REGS;hr++) {
7820                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
7821                   current.regmap[hr]=-1;
7822                 }
7823                 current.dirty&=branch_regs[j].dirty;
7824               }
7825             }
7826             j--;
7827           }
7828         }
7829       }
7830     }
7831
7832     // Count cycles in between branches
7833     ccadj[i] = CLOCK_ADJUST(cc);
7834     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
7835     {
7836       cc=0;
7837     }
7838 #if !defined(DRC_DBG)
7839     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
7840     {
7841       // this should really be removed since the real stalls have been implemented,
7842       // but doing so causes sizeable perf regression against the older version
7843       u_int gtec = gte_cycletab[source[i] & 0x3f];
7844       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
7845     }
7846     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
7847     {
7848       cc+=4;
7849     }
7850     else if(dops[i].itype==C2LS)
7851     {
7852       // same as with C2OP
7853       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
7854     }
7855 #endif
7856     else
7857     {
7858       cc++;
7859     }
7860
7861     if(!dops[i].is_ds) {
7862       regs[i].dirty=current.dirty;
7863       regs[i].isconst=current.isconst;
7864       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
7865     }
7866     for(hr=0;hr<HOST_REGS;hr++) {
7867       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
7868         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
7869           regs[i].wasconst&=~(1<<hr);
7870         }
7871       }
7872     }
7873     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
7874     //regs[i].waswritten=current.waswritten;
7875   }
7876 }
7877
7878 static noinline void pass4_cull_unused_regs(void)
7879 {
7880   u_int last_needed_regs[4] = {0,0,0,0};
7881   u_int nr=0;
7882   int i;
7883
7884   for (i=slen-1;i>=0;i--)
7885   {
7886     int hr;
7887     __builtin_prefetch(regs[i-2].regmap);
7888     if(dops[i].is_jump)
7889     {
7890       if(ba[i]<start || ba[i]>=(start+slen*4))
7891       {
7892         // Branch out of this block, don't need anything
7893         nr=0;
7894       }
7895       else
7896       {
7897         // Internal branch
7898         // Need whatever matches the target
7899         nr=0;
7900         int t=(ba[i]-start)>>2;
7901         for(hr=0;hr<HOST_REGS;hr++)
7902         {
7903           if(regs[i].regmap_entry[hr]>=0) {
7904             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
7905           }
7906         }
7907       }
7908       // Conditional branch may need registers for following instructions
7909       if (!dops[i].is_ujump)
7910       {
7911         if(i<slen-2) {
7912           nr |= last_needed_regs[(i+2) & 3];
7913           for(hr=0;hr<HOST_REGS;hr++)
7914           {
7915             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
7916             //if((regmap_entry[i+2][hr])>=0) if(!((nr>>hr)&1)) printf("%x-bogus(%d=%d)\n",start+i*4,hr,regmap_entry[i+2][hr]);
7917           }
7918         }
7919       }
7920       // Don't need stuff which is overwritten
7921       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7922       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7923       // Merge in delay slot
7924       if (dops[i+1].rt1) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt1);
7925       if (dops[i+1].rt2) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt2);
7926       nr |= get_regm(regmap_pre[i], dops[i+1].rs1);
7927       nr |= get_regm(regmap_pre[i], dops[i+1].rs2);
7928       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs1);
7929       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs2);
7930       if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
7931         nr |= get_regm(regmap_pre[i], ROREG);
7932         nr |= get_regm(regs[i].regmap_entry, ROREG);
7933       }
7934       if (dops[i+1].is_store) {
7935         nr |= get_regm(regmap_pre[i], INVCP);
7936         nr |= get_regm(regs[i].regmap_entry, INVCP);
7937       }
7938     }
7939     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7940     {
7941       // SYSCALL instruction (software interrupt)
7942       nr=0;
7943     }
7944     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
7945     {
7946       // ERET instruction (return from interrupt)
7947       nr=0;
7948     }
7949     else // Non-branch
7950     {
7951       if(i<slen-1) {
7952         for(hr=0;hr<HOST_REGS;hr++) {
7953           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
7954           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
7955           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7956           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7957         }
7958       }
7959     }
7960     // Overwritten registers are not needed
7961     if (dops[i].rt1) nr &= ~get_regm(regs[i].regmap, dops[i].rt1);
7962     if (dops[i].rt2) nr &= ~get_regm(regs[i].regmap, dops[i].rt2);
7963     nr &= ~get_regm(regs[i].regmap, FTEMP);
7964     // Source registers are needed
7965     nr |= get_regm(regmap_pre[i], dops[i].rs1);
7966     nr |= get_regm(regmap_pre[i], dops[i].rs2);
7967     nr |= get_regm(regs[i].regmap_entry, dops[i].rs1);
7968     nr |= get_regm(regs[i].regmap_entry, dops[i].rs2);
7969     if (ram_offset && (dops[i].is_load || dops[i].is_store)) {
7970       nr |= get_regm(regmap_pre[i], ROREG);
7971       nr |= get_regm(regs[i].regmap_entry, ROREG);
7972     }
7973     if (dops[i].is_store) {
7974       nr |= get_regm(regmap_pre[i], INVCP);
7975       nr |= get_regm(regs[i].regmap_entry, INVCP);
7976     }
7977
7978     if (i > 0 && !dops[i].bt && regs[i].wasdirty)
7979     for(hr=0;hr<HOST_REGS;hr++)
7980     {
7981       // Don't store a register immediately after writing it,
7982       // may prevent dual-issue.
7983       // But do so if this is a branch target, otherwise we
7984       // might have to load the register before the branch.
7985       if((regs[i].wasdirty>>hr)&1) {
7986         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
7987           if(dops[i-1].rt1==regmap_pre[i][hr]) nr|=1<<hr;
7988           if(dops[i-1].rt2==regmap_pre[i][hr]) nr|=1<<hr;
7989         }
7990         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
7991           if(dops[i-1].rt1==regs[i].regmap_entry[hr]) nr|=1<<hr;
7992           if(dops[i-1].rt2==regs[i].regmap_entry[hr]) nr|=1<<hr;
7993         }
7994       }
7995     }
7996     // Cycle count is needed at branches.  Assume it is needed at the target too.
7997     if(i==0||dops[i].bt||dops[i].itype==CJUMP) {
7998       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
7999       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8000     }
8001     // Save it
8002     last_needed_regs[i & 3] = nr;
8003
8004     // Deallocate unneeded registers
8005     for(hr=0;hr<HOST_REGS;hr++)
8006     {
8007       if(!((nr>>hr)&1)) {
8008         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8009         if(dops[i].is_jump)
8010         {
8011           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
8012           if (dops[i+1].is_load || dops[i+1].is_store)
8013             map1 = ROREG;
8014           if (dops[i+1].is_store)
8015             map2 = INVCP;
8016           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
8017             temp = FTEMP;
8018           if(regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8019              regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
8020              regs[i].regmap[hr]!=dops[i+1].rt1 && regs[i].regmap[hr]!=dops[i+1].rt2 &&
8021              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8022              regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=PTEMP &&
8023              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8024              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8025              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
8026           {
8027             regs[i].regmap[hr]=-1;
8028             regs[i].isconst&=~(1<<hr);
8029             regs[i].dirty&=~(1<<hr);
8030             regs[i+1].wasdirty&=~(1<<hr);
8031             if(branch_regs[i].regmap[hr]!=dops[i].rs1 && branch_regs[i].regmap[hr]!=dops[i].rs2 &&
8032                branch_regs[i].regmap[hr]!=dops[i].rt1 && branch_regs[i].regmap[hr]!=dops[i].rt2 &&
8033                branch_regs[i].regmap[hr]!=dops[i+1].rt1 && branch_regs[i].regmap[hr]!=dops[i+1].rt2 &&
8034                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8035                branch_regs[i].regmap[hr]!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8036                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8037                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8038                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
8039             {
8040               branch_regs[i].regmap[hr]=-1;
8041               branch_regs[i].regmap_entry[hr]=-1;
8042               if (!dops[i].is_ujump)
8043               {
8044                 if (i < slen-2) {
8045                   regmap_pre[i+2][hr]=-1;
8046                   regs[i+2].wasconst&=~(1<<hr);
8047                 }
8048               }
8049             }
8050           }
8051         }
8052         else
8053         {
8054           // Non-branch
8055           if(i>0)
8056           {
8057             int map1 = -1, map2 = -1, temp=-1;
8058             if (dops[i].is_load || dops[i].is_store)
8059               map1 = ROREG;
8060             if (dops[i].is_store)
8061               map2 = INVCP;
8062             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8063               temp = FTEMP;
8064             if(regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
8065                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8066                regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8067                //(dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG)
8068                regs[i].regmap[hr] != CCREG)
8069             {
8070               if(i<slen-1&&!dops[i].is_ds) {
8071                 assert(regs[i].regmap[hr]<64);
8072                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8073                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8074                 {
8075                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8076                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8077                 }
8078                 regmap_pre[i+1][hr]=-1;
8079                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8080                 regs[i+1].wasconst&=~(1<<hr);
8081               }
8082               regs[i].regmap[hr]=-1;
8083               regs[i].isconst&=~(1<<hr);
8084               regs[i].dirty&=~(1<<hr);
8085               regs[i+1].wasdirty&=~(1<<hr);
8086             }
8087           }
8088         }
8089       } // if needed
8090     } // for hr
8091   }
8092 }
8093
8094 // If a register is allocated during a loop, try to allocate it for the
8095 // entire loop, if possible.  This avoids loading/storing registers
8096 // inside of the loop.
8097 static noinline void pass5a_preallocate1(void)
8098 {
8099   int i, j, hr;
8100   signed char f_regmap[HOST_REGS];
8101   clear_all_regs(f_regmap);
8102   for(i=0;i<slen-1;i++)
8103   {
8104     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8105     {
8106       if(ba[i]>=start && ba[i]<(start+i*4))
8107       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8108       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8109       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8110       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8111       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8112       {
8113         int t=(ba[i]-start)>>2;
8114         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8115         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8116         for(hr=0;hr<HOST_REGS;hr++)
8117         {
8118           if(regs[i].regmap[hr]>=0) {
8119             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8120               // dealloc old register
8121               int n;
8122               for(n=0;n<HOST_REGS;n++)
8123               {
8124                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8125               }
8126               // and alloc new one
8127               f_regmap[hr]=regs[i].regmap[hr];
8128             }
8129           }
8130           if(branch_regs[i].regmap[hr]>=0) {
8131             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8132               // dealloc old register
8133               int n;
8134               for(n=0;n<HOST_REGS;n++)
8135               {
8136                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8137               }
8138               // and alloc new one
8139               f_regmap[hr]=branch_regs[i].regmap[hr];
8140             }
8141           }
8142           if(dops[i].ooo) {
8143             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8144               f_regmap[hr]=branch_regs[i].regmap[hr];
8145           }else{
8146             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8147               f_regmap[hr]=branch_regs[i].regmap[hr];
8148           }
8149           // Avoid dirty->clean transition
8150           #ifdef DESTRUCTIVE_WRITEBACK
8151           if(t>0) if(get_reg(regmap_pre[t],f_regmap[hr])>=0) if((regs[t].wasdirty>>get_reg(regmap_pre[t],f_regmap[hr]))&1) f_regmap[hr]=-1;
8152           #endif
8153           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8154           // case above, however it's always a good idea.  We can't hoist the
8155           // load if the register was already allocated, so there's no point
8156           // wasting time analyzing most of these cases.  It only "succeeds"
8157           // when the mapping was different and the load can be replaced with
8158           // a mov, which is of negligible benefit.  So such cases are
8159           // skipped below.
8160           if(f_regmap[hr]>0) {
8161             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8162               int r=f_regmap[hr];
8163               for(j=t;j<=i;j++)
8164               {
8165                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8166                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8167                 assert(r < 64);
8168                 if(regs[j].regmap[hr]==f_regmap[hr]&&f_regmap[hr]<TEMPREG) {
8169                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8170                   int k;
8171                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8172                     if(get_reg(regs[i].regmap,f_regmap[hr])>=0) break;
8173                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8174                     k=i;
8175                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8176                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8177                         //printf("no free regs for store %x\n",start+(k-1)*4);
8178                         break;
8179                       }
8180                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8181                         //printf("no-match due to different register\n");
8182                         break;
8183                       }
8184                       if (dops[k-2].is_jump) {
8185                         //printf("no-match due to branch\n");
8186                         break;
8187                       }
8188                       // call/ret fast path assumes no registers allocated
8189                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8190                         break;
8191                       }
8192                       k--;
8193                     }
8194                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8195                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8196                       while(k<i) {
8197                         regs[k].regmap_entry[hr]=f_regmap[hr];
8198                         regs[k].regmap[hr]=f_regmap[hr];
8199                         regmap_pre[k+1][hr]=f_regmap[hr];
8200                         regs[k].wasdirty&=~(1<<hr);
8201                         regs[k].dirty&=~(1<<hr);
8202                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8203                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8204                         regs[k].wasconst&=~(1<<hr);
8205                         regs[k].isconst&=~(1<<hr);
8206                         k++;
8207                       }
8208                     }
8209                     else {
8210                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8211                       break;
8212                     }
8213                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8214                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8215                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8216                       regs[i].regmap_entry[hr]=f_regmap[hr];
8217                       regs[i].regmap[hr]=f_regmap[hr];
8218                       regs[i].wasdirty&=~(1<<hr);
8219                       regs[i].dirty&=~(1<<hr);
8220                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8221                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8222                       regs[i].wasconst&=~(1<<hr);
8223                       regs[i].isconst&=~(1<<hr);
8224                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8225                       branch_regs[i].wasdirty&=~(1<<hr);
8226                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8227                       branch_regs[i].regmap[hr]=f_regmap[hr];
8228                       branch_regs[i].dirty&=~(1<<hr);
8229                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8230                       branch_regs[i].wasconst&=~(1<<hr);
8231                       branch_regs[i].isconst&=~(1<<hr);
8232                       if (!dops[i].is_ujump) {
8233                         regmap_pre[i+2][hr]=f_regmap[hr];
8234                         regs[i+2].wasdirty&=~(1<<hr);
8235                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8236                       }
8237                     }
8238                   }
8239                   for(k=t;k<j;k++) {
8240                     // Alloc register clean at beginning of loop,
8241                     // but may dirty it in pass 6
8242                     regs[k].regmap_entry[hr]=f_regmap[hr];
8243                     regs[k].regmap[hr]=f_regmap[hr];
8244                     regs[k].dirty&=~(1<<hr);
8245                     regs[k].wasconst&=~(1<<hr);
8246                     regs[k].isconst&=~(1<<hr);
8247                     if (dops[k].is_jump) {
8248                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8249                       branch_regs[k].regmap[hr]=f_regmap[hr];
8250                       branch_regs[k].dirty&=~(1<<hr);
8251                       branch_regs[k].wasconst&=~(1<<hr);
8252                       branch_regs[k].isconst&=~(1<<hr);
8253                       if (!dops[k].is_ujump) {
8254                         regmap_pre[k+2][hr]=f_regmap[hr];
8255                         regs[k+2].wasdirty&=~(1<<hr);
8256                       }
8257                     }
8258                     else
8259                     {
8260                       regmap_pre[k+1][hr]=f_regmap[hr];
8261                       regs[k+1].wasdirty&=~(1<<hr);
8262                     }
8263                   }
8264                   if(regs[j].regmap[hr]==f_regmap[hr])
8265                     regs[j].regmap_entry[hr]=f_regmap[hr];
8266                   break;
8267                 }
8268                 if(j==i) break;
8269                 if(regs[j].regmap[hr]>=0)
8270                   break;
8271                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8272                   //printf("no-match due to different register\n");
8273                   break;
8274                 }
8275                 if (dops[j].is_ujump)
8276                 {
8277                   // Stop on unconditional branch
8278                   break;
8279                 }
8280                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8281                 {
8282                   if(dops[j].ooo) {
8283                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8284                       break;
8285                   }else{
8286                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8287                       break;
8288                   }
8289                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8290                     //printf("no-match due to different register (branch)\n");
8291                     break;
8292                   }
8293                 }
8294                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8295                   //printf("No free regs for store %x\n",start+j*4);
8296                   break;
8297                 }
8298                 assert(f_regmap[hr]<64);
8299               }
8300             }
8301           }
8302         }
8303       }
8304     }else{
8305       // Non branch or undetermined branch target
8306       for(hr=0;hr<HOST_REGS;hr++)
8307       {
8308         if(hr!=EXCLUDE_REG) {
8309           if(regs[i].regmap[hr]>=0) {
8310             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8311               // dealloc old register
8312               int n;
8313               for(n=0;n<HOST_REGS;n++)
8314               {
8315                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8316               }
8317               // and alloc new one
8318               f_regmap[hr]=regs[i].regmap[hr];
8319             }
8320           }
8321         }
8322       }
8323       // Try to restore cycle count at branch targets
8324       if(dops[i].bt) {
8325         for(j=i;j<slen-1;j++) {
8326           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8327           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8328             //printf("no free regs for store %x\n",start+j*4);
8329             break;
8330           }
8331         }
8332         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8333           int k=i;
8334           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8335           while(k<j) {
8336             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8337             regs[k].regmap[HOST_CCREG]=CCREG;
8338             regmap_pre[k+1][HOST_CCREG]=CCREG;
8339             regs[k+1].wasdirty|=1<<HOST_CCREG;
8340             regs[k].dirty|=1<<HOST_CCREG;
8341             regs[k].wasconst&=~(1<<HOST_CCREG);
8342             regs[k].isconst&=~(1<<HOST_CCREG);
8343             k++;
8344           }
8345           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8346         }
8347         // Work backwards from the branch target
8348         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8349         {
8350           //printf("Extend backwards\n");
8351           int k;
8352           k=i;
8353           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8354             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8355               //printf("no free regs for store %x\n",start+(k-1)*4);
8356               break;
8357             }
8358             k--;
8359           }
8360           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8361             //printf("Extend CC, %x ->\n",start+k*4);
8362             while(k<=i) {
8363               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8364               regs[k].regmap[HOST_CCREG]=CCREG;
8365               regmap_pre[k+1][HOST_CCREG]=CCREG;
8366               regs[k+1].wasdirty|=1<<HOST_CCREG;
8367               regs[k].dirty|=1<<HOST_CCREG;
8368               regs[k].wasconst&=~(1<<HOST_CCREG);
8369               regs[k].isconst&=~(1<<HOST_CCREG);
8370               k++;
8371             }
8372           }
8373           else {
8374             //printf("Fail Extend CC, %x ->\n",start+k*4);
8375           }
8376         }
8377       }
8378       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8379          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8380          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8381       {
8382         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8383       }
8384     }
8385   }
8386 }
8387
8388 // This allocates registers (if possible) one instruction prior
8389 // to use, which can avoid a load-use penalty on certain CPUs.
8390 static noinline void pass5b_preallocate2(void)
8391 {
8392   int i, hr;
8393   for(i=0;i<slen-1;i++)
8394   {
8395     if (!i || !dops[i-1].is_jump)
8396     {
8397       if(!dops[i+1].bt)
8398       {
8399         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8400            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8401         {
8402           if(dops[i+1].rs1) {
8403             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8404             {
8405               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8406               {
8407                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8408                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8409                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8410                 regs[i].isconst&=~(1<<hr);
8411                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8412                 constmap[i][hr]=constmap[i+1][hr];
8413                 regs[i+1].wasdirty&=~(1<<hr);
8414                 regs[i].dirty&=~(1<<hr);
8415               }
8416             }
8417           }
8418           if(dops[i+1].rs2) {
8419             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8420             {
8421               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8422               {
8423                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8424                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8425                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8426                 regs[i].isconst&=~(1<<hr);
8427                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8428                 constmap[i][hr]=constmap[i+1][hr];
8429                 regs[i+1].wasdirty&=~(1<<hr);
8430                 regs[i].dirty&=~(1<<hr);
8431               }
8432             }
8433           }
8434           // Preload target address for load instruction (non-constant)
8435           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8436             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8437             {
8438               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8439               {
8440                 regs[i].regmap[hr]=dops[i+1].rs1;
8441                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8442                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8443                 regs[i].isconst&=~(1<<hr);
8444                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8445                 constmap[i][hr]=constmap[i+1][hr];
8446                 regs[i+1].wasdirty&=~(1<<hr);
8447                 regs[i].dirty&=~(1<<hr);
8448               }
8449             }
8450           }
8451           // Load source into target register
8452           if(dops[i+1].use_lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8453             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8454             {
8455               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8456               {
8457                 regs[i].regmap[hr]=dops[i+1].rs1;
8458                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8459                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8460                 regs[i].isconst&=~(1<<hr);
8461                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8462                 constmap[i][hr]=constmap[i+1][hr];
8463                 regs[i+1].wasdirty&=~(1<<hr);
8464                 regs[i].dirty&=~(1<<hr);
8465               }
8466             }
8467           }
8468           // Address for store instruction (non-constant)
8469           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8470              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8471             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8472               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8473               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8474               else {
8475                 regs[i+1].regmap[hr]=AGEN1+((i+1)&1);
8476                 regs[i+1].isconst&=~(1<<hr);
8477               }
8478               assert(hr>=0);
8479               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8480               {
8481                 regs[i].regmap[hr]=dops[i+1].rs1;
8482                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8483                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8484                 regs[i].isconst&=~(1<<hr);
8485                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8486                 constmap[i][hr]=constmap[i+1][hr];
8487                 regs[i+1].wasdirty&=~(1<<hr);
8488                 regs[i].dirty&=~(1<<hr);
8489               }
8490             }
8491           }
8492           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8493             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8494               int nr;
8495               hr=get_reg(regs[i+1].regmap,FTEMP);
8496               assert(hr>=0);
8497               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8498               {
8499                 regs[i].regmap[hr]=dops[i+1].rs1;
8500                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8501                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8502                 regs[i].isconst&=~(1<<hr);
8503                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8504                 constmap[i][hr]=constmap[i+1][hr];
8505                 regs[i+1].wasdirty&=~(1<<hr);
8506                 regs[i].dirty&=~(1<<hr);
8507               }
8508               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8509               {
8510                 // move it to another register
8511                 regs[i+1].regmap[hr]=-1;
8512                 regmap_pre[i+2][hr]=-1;
8513                 regs[i+1].regmap[nr]=FTEMP;
8514                 regmap_pre[i+2][nr]=FTEMP;
8515                 regs[i].regmap[nr]=dops[i+1].rs1;
8516                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8517                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8518                 regs[i].isconst&=~(1<<nr);
8519                 regs[i+1].isconst&=~(1<<nr);
8520                 regs[i].dirty&=~(1<<nr);
8521                 regs[i+1].wasdirty&=~(1<<nr);
8522                 regs[i+1].dirty&=~(1<<nr);
8523                 regs[i+2].wasdirty&=~(1<<nr);
8524               }
8525             }
8526           }
8527           if(dops[i+1].itype==LOAD||dops[i+1].itype==LOADLR||dops[i+1].itype==STORE||dops[i+1].itype==STORELR/*||dops[i+1].itype==C1LS||||dops[i+1].itype==C2LS*/) {
8528             hr = -1;
8529             if(dops[i+1].itype==LOAD)
8530               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8531             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8532               hr=get_reg(regs[i+1].regmap,FTEMP);
8533             if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8534               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8535               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8536             }
8537             if(hr>=0&&regs[i].regmap[hr]<0) {
8538               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8539               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8540                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8541                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8542                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8543                 regs[i].isconst&=~(1<<hr);
8544                 regs[i+1].wasdirty&=~(1<<hr);
8545                 regs[i].dirty&=~(1<<hr);
8546               }
8547             }
8548           }
8549         }
8550       }
8551     }
8552   }
8553 }
8554
8555 // Write back dirty registers as soon as we will no longer modify them,
8556 // so that we don't end up with lots of writes at the branches.
8557 static noinline void pass6_clean_registers(int istart, int iend, int wr)
8558 {
8559   static u_int wont_dirty[MAXBLOCK];
8560   static u_int will_dirty[MAXBLOCK];
8561   int i;
8562   int r;
8563   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
8564   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
8565   if(iend==slen-1) {
8566     will_dirty_i=will_dirty_next=0;
8567     wont_dirty_i=wont_dirty_next=0;
8568   }else{
8569     will_dirty_i=will_dirty_next=will_dirty[iend+1];
8570     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
8571   }
8572   for (i=iend;i>=istart;i--)
8573   {
8574     signed char rregmap_i[RRMAP_SIZE];
8575     u_int hr_candirty = 0;
8576     assert(HOST_REGS < 32);
8577     make_rregs(regs[i].regmap, rregmap_i, &hr_candirty);
8578     __builtin_prefetch(regs[i-1].regmap);
8579     if(dops[i].is_jump)
8580     {
8581       signed char branch_rregmap_i[RRMAP_SIZE];
8582       u_int branch_hr_candirty = 0;
8583       make_rregs(branch_regs[i].regmap, branch_rregmap_i, &branch_hr_candirty);
8584       if(ba[i]<start || ba[i]>=(start+slen*4))
8585       {
8586         // Branch out of this block, flush all regs
8587         will_dirty_i = 0;
8588         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8589         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8590         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8591         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8592         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8593         will_dirty_i &= branch_hr_candirty;
8594         if (dops[i].is_ujump)
8595         {
8596           // Unconditional branch
8597           wont_dirty_i = 0;
8598           // Merge in delay slot (will dirty)
8599           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8600           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8601           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8602           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8603           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8604           will_dirty_i &= hr_candirty;
8605         }
8606         else
8607         {
8608           // Conditional branch
8609           wont_dirty_i = wont_dirty_next;
8610           // Merge in delay slot (will dirty)
8611           // (the original code had no explanation why these 2 are commented out)
8612           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8613           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8614           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8615           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8616           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8617           will_dirty_i &= hr_candirty;
8618         }
8619         // Merge in delay slot (wont dirty)
8620         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8621         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8622         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8623         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8624         wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8625         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8626         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8627         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8628         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8629         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8630         wont_dirty_i &= ~(1u << 31);
8631         if(wr) {
8632           #ifndef DESTRUCTIVE_WRITEBACK
8633           branch_regs[i].dirty&=wont_dirty_i;
8634           #endif
8635           branch_regs[i].dirty|=will_dirty_i;
8636         }
8637       }
8638       else
8639       {
8640         // Internal branch
8641         if(ba[i]<=start+i*4) {
8642           // Backward branch
8643           if (dops[i].is_ujump)
8644           {
8645             // Unconditional branch
8646             temp_will_dirty=0;
8647             temp_wont_dirty=0;
8648             // Merge in delay slot (will dirty)
8649             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8650             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8651             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8652             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8653             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8654             temp_will_dirty &= branch_hr_candirty;
8655             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8656             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8657             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8658             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8659             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8660             temp_will_dirty &= hr_candirty;
8661           } else {
8662             // Conditional branch (not taken case)
8663             temp_will_dirty=will_dirty_next;
8664             temp_wont_dirty=wont_dirty_next;
8665             // Merge in delay slot (will dirty)
8666             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8667             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8668             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8669             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8670             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8671             temp_will_dirty &= branch_hr_candirty;
8672             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8673             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8674             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8675             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8676             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8677             temp_will_dirty &= hr_candirty;
8678           }
8679           // Merge in delay slot (wont dirty)
8680           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8681           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8682           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8683           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8684           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8685           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8686           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8687           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8688           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8689           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8690           temp_wont_dirty &= ~(1u << 31);
8691           // Deal with changed mappings
8692           if(i<iend) {
8693             for(r=0;r<HOST_REGS;r++) {
8694               if(r!=EXCLUDE_REG) {
8695                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
8696                   temp_will_dirty&=~(1<<r);
8697                   temp_wont_dirty&=~(1<<r);
8698                   if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8699                     temp_will_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8700                     temp_wont_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8701                   } else {
8702                     temp_will_dirty|=1<<r;
8703                     temp_wont_dirty|=1<<r;
8704                   }
8705                 }
8706               }
8707             }
8708           }
8709           if(wr) {
8710             will_dirty[i]=temp_will_dirty;
8711             wont_dirty[i]=temp_wont_dirty;
8712             pass6_clean_registers((ba[i]-start)>>2,i-1,0);
8713           }else{
8714             // Limit recursion.  It can take an excessive amount
8715             // of time if there are a lot of nested loops.
8716             will_dirty[(ba[i]-start)>>2]=0;
8717             wont_dirty[(ba[i]-start)>>2]=-1;
8718           }
8719         }
8720         /*else*/ if(1)
8721         {
8722           if (dops[i].is_ujump)
8723           {
8724             // Unconditional branch
8725             will_dirty_i=0;
8726             wont_dirty_i=0;
8727           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
8728             for(r=0;r<HOST_REGS;r++) {
8729               if(r!=EXCLUDE_REG) {
8730                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8731                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
8732                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8733                 }
8734                 if(branch_regs[i].regmap[r]>=0) {
8735                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8736                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8737                 }
8738               }
8739             }
8740           //}
8741             // Merge in delay slot
8742             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8743             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8744             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8745             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8746             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8747             will_dirty_i &= branch_hr_candirty;
8748             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8749             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8750             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8751             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8752             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8753             will_dirty_i &= hr_candirty;
8754           } else {
8755             // Conditional branch
8756             will_dirty_i=will_dirty_next;
8757             wont_dirty_i=wont_dirty_next;
8758           //if(ba[i]>start+i*4) // Disable recursion (for debugging)
8759             for(r=0;r<HOST_REGS;r++) {
8760               if(r!=EXCLUDE_REG) {
8761                 signed char target_reg=branch_regs[i].regmap[r];
8762                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8763                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
8764                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8765                 }
8766                 else if(target_reg>=0) {
8767                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8768                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8769                 }
8770               }
8771             }
8772             // Merge in delay slot
8773             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8774             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8775             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8776             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8777             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8778             will_dirty_i &= branch_hr_candirty;
8779             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8780             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8781             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8782             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8783             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8784             will_dirty_i &= hr_candirty;
8785           }
8786           // Merge in delay slot (won't dirty)
8787           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8788           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8789           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8790           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8791           wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8792           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8793           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8794           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8795           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8796           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8797           wont_dirty_i &= ~(1u << 31);
8798           if(wr) {
8799             #ifndef DESTRUCTIVE_WRITEBACK
8800             branch_regs[i].dirty&=wont_dirty_i;
8801             #endif
8802             branch_regs[i].dirty|=will_dirty_i;
8803           }
8804         }
8805       }
8806     }
8807     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8808     {
8809       // SYSCALL instruction (software interrupt)
8810       will_dirty_i=0;
8811       wont_dirty_i=0;
8812     }
8813     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8814     {
8815       // ERET instruction (return from interrupt)
8816       will_dirty_i=0;
8817       wont_dirty_i=0;
8818     }
8819     will_dirty_next=will_dirty_i;
8820     wont_dirty_next=wont_dirty_i;
8821     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8822     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8823     will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8824     will_dirty_i &= hr_candirty;
8825     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8826     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8827     wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8828     wont_dirty_i &= ~(1u << 31);
8829     if (i > istart && !dops[i].is_jump) {
8830       // Don't store a register immediately after writing it,
8831       // may prevent dual-issue.
8832       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt1) & 31);
8833       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt2) & 31);
8834     }
8835     // Save it
8836     will_dirty[i]=will_dirty_i;
8837     wont_dirty[i]=wont_dirty_i;
8838     // Mark registers that won't be dirtied as not dirty
8839     if(wr) {
8840         regs[i].dirty|=will_dirty_i;
8841         #ifndef DESTRUCTIVE_WRITEBACK
8842         regs[i].dirty&=wont_dirty_i;
8843         if(dops[i].is_jump)
8844         {
8845           if (i < iend-1 && !dops[i].is_ujump) {
8846             for(r=0;r<HOST_REGS;r++) {
8847               if(r!=EXCLUDE_REG) {
8848                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
8849                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
8850                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8851               }
8852             }
8853           }
8854         }
8855         else
8856         {
8857           if(i<iend) {
8858             for(r=0;r<HOST_REGS;r++) {
8859               if(r!=EXCLUDE_REG) {
8860                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
8861                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
8862                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8863               }
8864             }
8865           }
8866         }
8867         #endif
8868     }
8869     // Deal with changed mappings
8870     temp_will_dirty=will_dirty_i;
8871     temp_wont_dirty=wont_dirty_i;
8872     for(r=0;r<HOST_REGS;r++) {
8873       if(r!=EXCLUDE_REG) {
8874         int nr;
8875         if(regs[i].regmap[r]==regmap_pre[i][r]) {
8876           if(wr) {
8877             #ifndef DESTRUCTIVE_WRITEBACK
8878             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8879             #endif
8880             regs[i].wasdirty|=will_dirty_i&(1<<r);
8881           }
8882         }
8883         else if(regmap_pre[i][r]>=0&&(nr=get_rreg(rregmap_i,regmap_pre[i][r]))>=0) {
8884           // Register moved to a different register
8885           will_dirty_i&=~(1<<r);
8886           wont_dirty_i&=~(1<<r);
8887           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
8888           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
8889           if(wr) {
8890             #ifndef DESTRUCTIVE_WRITEBACK
8891             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8892             #endif
8893             regs[i].wasdirty|=will_dirty_i&(1<<r);
8894           }
8895         }
8896         else {
8897           will_dirty_i&=~(1<<r);
8898           wont_dirty_i&=~(1<<r);
8899           if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8900             will_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8901             wont_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8902           } else {
8903             wont_dirty_i|=1<<r;
8904             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
8905           }
8906         }
8907       }
8908     }
8909   }
8910 }
8911
8912 static noinline void pass10_expire_blocks(void)
8913 {
8914   u_int step = MAX_OUTPUT_BLOCK_SIZE / PAGE_COUNT / 2;
8915   // not sizeof(ndrc->translation_cache) due to vita hack
8916   u_int step_mask = ((1u << TARGET_SIZE_2) - 1u) & ~(step - 1u);
8917   u_int end = (out - ndrc->translation_cache + EXPIRITY_OFFSET) & step_mask;
8918   u_int base_shift = __builtin_ctz(MAX_OUTPUT_BLOCK_SIZE);
8919   int hit;
8920
8921   for (; expirep != end; expirep = ((expirep + step) & step_mask))
8922   {
8923     u_int base_offs = expirep & ~(MAX_OUTPUT_BLOCK_SIZE - 1);
8924     u_int block_i = expirep / step & (PAGE_COUNT - 1);
8925     u_int phase = (expirep >> (base_shift - 1)) & 1u;
8926     if (!(expirep & (MAX_OUTPUT_BLOCK_SIZE / 2 - 1))) {
8927       inv_debug("EXP: base_offs %x/%lx phase %u\n", base_offs,
8928         (long)(out - ndrc->translation_cache), phase);
8929     }
8930
8931     if (!phase) {
8932       hit = blocks_remove_matching_addrs(&blocks[block_i], base_offs, base_shift);
8933       if (hit) {
8934         do_clear_cache();
8935         #ifdef USE_MINI_HT
8936         memset(mini_ht, -1, sizeof(mini_ht));
8937         #endif
8938       }
8939     }
8940     else
8941       unlink_jumps_tc_range(jumps[block_i], base_offs, base_shift);
8942   }
8943 }
8944
8945 static struct block_info *new_block_info(u_int start, u_int len,
8946   const void *source, const void *copy, u_char *beginning, u_short jump_in_count)
8947 {
8948   struct block_info **b_pptr;
8949   struct block_info *block;
8950   u_int page = get_page(start);
8951
8952   block = malloc(sizeof(*block) + jump_in_count * sizeof(block->jump_in[0]));
8953   assert(block);
8954   assert(jump_in_count > 0);
8955   block->source = source;
8956   block->copy = copy;
8957   block->start = start;
8958   block->len = len;
8959   block->reg_sv_flags = 0;
8960   block->tc_offs = beginning - ndrc->translation_cache;
8961   //block->tc_len = out - beginning;
8962   block->is_dirty = 0;
8963   block->inv_near_misses = 0;
8964   block->jump_in_cnt = jump_in_count;
8965
8966   // insert sorted by start mirror-unmasked vaddr
8967   for (b_pptr = &blocks[page]; ; b_pptr = &((*b_pptr)->next)) {
8968     if (*b_pptr == NULL || (*b_pptr)->start >= start) {
8969       block->next = *b_pptr;
8970       *b_pptr = block;
8971       break;
8972     }
8973   }
8974   stat_inc(stat_blocks);
8975   return block;
8976 }
8977
8978 static int new_recompile_block(u_int addr)
8979 {
8980   u_int pagelimit = 0;
8981   u_int state_rflags = 0;
8982   int i;
8983
8984   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
8985
8986   // this is just for speculation
8987   for (i = 1; i < 32; i++) {
8988     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
8989       state_rflags |= 1 << i;
8990   }
8991
8992   assert(!(addr & 3));
8993   start = addr & ~3;
8994   new_dynarec_did_compile=1;
8995   if (Config.HLE && start == 0x80001000) // hlecall
8996   {
8997     // XXX: is this enough? Maybe check hleSoftCall?
8998     void *beginning = start_block();
8999
9000     emit_movimm(start,0);
9001     emit_writeword(0,&pcaddr);
9002     emit_far_jump(new_dyna_leave);
9003     literal_pool(0);
9004     end_block(beginning);
9005     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
9006     block->jump_in[0].vaddr = start;
9007     block->jump_in[0].addr = beginning;
9008     return 0;
9009   }
9010   else if (f1_hack && hack_addr == 0) {
9011     void *beginning = start_block();
9012     emit_movimm(start, 0);
9013     emit_writeword(0, &hack_addr);
9014     emit_readword(&psxRegs.GPR.n.sp, 0);
9015     emit_readptr(&mem_rtab, 1);
9016     emit_shrimm(0, 12, 2);
9017     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
9018     emit_addimm(0, 0x18, 0);
9019     emit_adds_ptr(1, 1, 1);
9020     emit_ldr_dualindexed(1, 0, 0);
9021     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
9022     emit_far_call(ndrc_get_addr_ht);
9023     emit_jmpreg(0); // jr k0
9024     literal_pool(0);
9025     end_block(beginning);
9026
9027     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
9028     block->jump_in[0].vaddr = start;
9029     block->jump_in[0].addr = beginning;
9030     SysPrintf("F1 hack to   %08x\n", start);
9031     return 0;
9032   }
9033
9034   cycle_multiplier_active = cycle_multiplier_override && cycle_multiplier == CYCLE_MULT_DEFAULT
9035     ? cycle_multiplier_override : cycle_multiplier;
9036
9037   source = get_source_start(start, &pagelimit);
9038   if (source == NULL) {
9039     if (addr != hack_addr) {
9040       SysPrintf("Compile at bogus memory address: %08x\n", addr);
9041       hack_addr = addr;
9042     }
9043     //abort();
9044     return -1;
9045   }
9046
9047   /* Pass 1: disassemble */
9048   /* Pass 2: register dependencies, branch targets */
9049   /* Pass 3: register allocation */
9050   /* Pass 4: branch dependencies */
9051   /* Pass 5: pre-alloc */
9052   /* Pass 6: optimize clean/dirty state */
9053   /* Pass 7: flag 32-bit registers */
9054   /* Pass 8: assembly */
9055   /* Pass 9: linker */
9056   /* Pass 10: garbage collection / free memory */
9057
9058   /* Pass 1 disassembly */
9059
9060   pass1_disassemble(pagelimit);
9061
9062   int clear_hack_addr = apply_hacks();
9063
9064   /* Pass 2 - Register dependencies and branch targets */
9065
9066   pass2_unneeded_regs(0,slen-1,0);
9067
9068   /* Pass 3 - Register allocation */
9069
9070   pass3_register_alloc(addr);
9071
9072   /* Pass 4 - Cull unused host registers */
9073
9074   pass4_cull_unused_regs();
9075
9076   /* Pass 5 - Pre-allocate registers */
9077
9078   pass5a_preallocate1();
9079   pass5b_preallocate2();
9080
9081   /* Pass 6 - Optimize clean/dirty state */
9082   pass6_clean_registers(0, slen-1, 1);
9083
9084   /* Pass 7 - Identify 32-bit registers */
9085   for (i=slen-1;i>=0;i--)
9086   {
9087     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9088     {
9089       // Conditional branch
9090       if((source[i]>>16)!=0x1000&&i<slen-2) {
9091         // Mark this address as a branch target since it may be called
9092         // upon return from interrupt
9093         dops[i+2].bt=1;
9094       }
9095     }
9096   }
9097
9098   /* Pass 8 - Assembly */
9099   linkcount=0;stubcount=0;
9100   is_delayslot=0;
9101   u_int dirty_pre=0;
9102   void *beginning=start_block();
9103   void *instr_addr0_override = NULL;
9104   int ds = 0;
9105
9106   if (start == 0x80030000) {
9107     // nasty hack for the fastbios thing
9108     // override block entry to this code
9109     instr_addr0_override = out;
9110     emit_movimm(start,0);
9111     // abuse io address var as a flag that we
9112     // have already returned here once
9113     emit_readword(&address,1);
9114     emit_writeword(0,&pcaddr);
9115     emit_writeword(0,&address);
9116     emit_cmp(0,1);
9117     #ifdef __aarch64__
9118     emit_jeq(out + 4*2);
9119     emit_far_jump(new_dyna_leave);
9120     #else
9121     emit_jne(new_dyna_leave);
9122     #endif
9123   }
9124   for(i=0;i<slen;i++)
9125   {
9126     __builtin_prefetch(regs[i+1].regmap);
9127     check_regmap(regmap_pre[i]);
9128     check_regmap(regs[i].regmap_entry);
9129     check_regmap(regs[i].regmap);
9130     //if(ds) printf("ds: ");
9131     disassemble_inst(i);
9132     if(ds) {
9133       ds=0; // Skip delay slot
9134       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9135       instr_addr[i] = NULL;
9136     } else {
9137       speculate_register_values(i);
9138       #ifndef DESTRUCTIVE_WRITEBACK
9139       if (i < 2 || !dops[i-2].is_ujump)
9140       {
9141         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9142       }
9143       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9144         dirty_pre=branch_regs[i].dirty;
9145       }else{
9146         dirty_pre=regs[i].dirty;
9147       }
9148       #endif
9149       // write back
9150       if (i < 2 || !dops[i-2].is_ujump)
9151       {
9152         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9153         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9154       }
9155       // branch target entry point
9156       instr_addr[i] = out;
9157       assem_debug("<->\n");
9158       drc_dbg_emit_do_cmp(i, ccadj[i]);
9159       if (clear_hack_addr) {
9160         emit_movimm(0, 0);
9161         emit_writeword(0, &hack_addr);
9162         clear_hack_addr = 0;
9163       }
9164
9165       // load regs
9166       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9167         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9168       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9169       address_generation(i,&regs[i],regs[i].regmap_entry);
9170       load_consts(regmap_pre[i],regs[i].regmap,i);
9171       if(dops[i].is_jump)
9172       {
9173         // Load the delay slot registers if necessary
9174         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2&&(dops[i+1].rs1!=dops[i].rt1||dops[i].rt1==0))
9175           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9176         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2&&(dops[i+1].rs2!=dops[i].rt1||dops[i].rt1==0))
9177           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9178         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9179           load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9180         if (dops[i+1].is_store)
9181           load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9182       }
9183       else if(i+1<slen)
9184       {
9185         // Preload registers for following instruction
9186         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9187           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9188             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9189         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9190           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9191             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9192       }
9193       // TODO: if(is_ooo(i)) address_generation(i+1);
9194       if (!dops[i].is_jump || dops[i].itype == CJUMP)
9195         load_reg(regs[i].regmap_entry,regs[i].regmap,CCREG);
9196       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9197         load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9198       if (dops[i].is_store)
9199         load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9200
9201       ds = assemble(i, &regs[i], ccadj[i]);
9202
9203       if (dops[i].is_ujump)
9204         literal_pool(1024);
9205       else
9206         literal_pool_jumpover(256);
9207     }
9208   }
9209
9210   assert(slen > 0);
9211   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9212     // no ending needed for this block since INTCALL never returns
9213   }
9214   // If the block did not end with an unconditional branch,
9215   // add a jump to the next instruction.
9216   else if (i > 1) {
9217     if (!dops[i-2].is_ujump) {
9218       assert(!dops[i-1].is_jump);
9219       assert(i==slen);
9220       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9221         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9222         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9223           emit_loadreg(CCREG,HOST_CCREG);
9224         emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9225       }
9226       else
9227       {
9228         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9229         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9230       }
9231       add_to_linker(out,start+i*4,0);
9232       emit_jmp(0);
9233     }
9234   }
9235   else
9236   {
9237     assert(i>0);
9238     assert(!dops[i-1].is_jump);
9239     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9240     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9241       emit_loadreg(CCREG,HOST_CCREG);
9242     emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9243     add_to_linker(out,start+i*4,0);
9244     emit_jmp(0);
9245   }
9246
9247   // TODO: delay slot stubs?
9248   // Stubs
9249   for(i=0;i<stubcount;i++)
9250   {
9251     switch(stubs[i].type)
9252     {
9253       case LOADB_STUB:
9254       case LOADH_STUB:
9255       case LOADW_STUB:
9256       case LOADD_STUB:
9257       case LOADBU_STUB:
9258       case LOADHU_STUB:
9259         do_readstub(i);break;
9260       case STOREB_STUB:
9261       case STOREH_STUB:
9262       case STOREW_STUB:
9263       case STORED_STUB:
9264         do_writestub(i);break;
9265       case CC_STUB:
9266         do_ccstub(i);break;
9267       case INVCODE_STUB:
9268         do_invstub(i);break;
9269       case FP_STUB:
9270         do_cop1stub(i);break;
9271       case STORELR_STUB:
9272         do_unalignedwritestub(i);break;
9273     }
9274   }
9275
9276   if (instr_addr0_override)
9277     instr_addr[0] = instr_addr0_override;
9278
9279 #if 0
9280   /* check for improper expiration */
9281   for (i = 0; i < ARRAY_SIZE(jumps); i++) {
9282     int j;
9283     if (!jumps[i])
9284       continue;
9285     for (j = 0; j < jumps[i]->count; j++)
9286       assert(jumps[i]->e[j].stub < beginning || (u_char *)jumps[i]->e[j].stub > out);
9287   }
9288 #endif
9289
9290   /* Pass 9 - Linker */
9291   for(i=0;i<linkcount;i++)
9292   {
9293     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9294     literal_pool(64);
9295     if (!link_addr[i].internal)
9296     {
9297       void *stub = out;
9298       void *addr = check_addr(link_addr[i].target);
9299       emit_extjump(link_addr[i].addr, link_addr[i].target);
9300       if (addr) {
9301         set_jump_target(link_addr[i].addr, addr);
9302         ndrc_add_jump_out(link_addr[i].target,stub);
9303       }
9304       else
9305         set_jump_target(link_addr[i].addr, stub);
9306     }
9307     else
9308     {
9309       // Internal branch
9310       int target=(link_addr[i].target-start)>>2;
9311       assert(target>=0&&target<slen);
9312       assert(instr_addr[target]);
9313       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9314       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9315       //#else
9316       set_jump_target(link_addr[i].addr, instr_addr[target]);
9317       //#endif
9318     }
9319   }
9320
9321   u_int source_len = slen*4;
9322   if (dops[slen-1].itype == INTCALL && source_len > 4)
9323     // no need to treat the last instruction as compiled
9324     // as interpreter fully handles it
9325     source_len -= 4;
9326
9327   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9328     copy = shadow;
9329
9330   // External Branch Targets (jump_in)
9331   int jump_in_count = 1;
9332   assert(instr_addr[0]);
9333   for (i = 1; i < slen; i++)
9334   {
9335     if (dops[i].bt && instr_addr[i])
9336       jump_in_count++;
9337   }
9338
9339   struct block_info *block =
9340     new_block_info(start, slen * 4, source, copy, beginning, jump_in_count);
9341   block->reg_sv_flags = state_rflags;
9342
9343   int jump_in_i = 0;
9344   for (i = 0; i < slen; i++)
9345   {
9346     if ((i == 0 || dops[i].bt) && instr_addr[i])
9347     {
9348       assem_debug("%p (%d) <- %8x\n", instr_addr[i], i, start + i*4);
9349       u_int vaddr = start + i*4;
9350
9351       literal_pool(256);
9352       void *entry = out;
9353       load_regs_entry(i);
9354       if (entry == out)
9355         entry = instr_addr[i];
9356       else
9357         emit_jmp(instr_addr[i]);
9358
9359       block->jump_in[jump_in_i].vaddr = vaddr;
9360       block->jump_in[jump_in_i].addr = entry;
9361       jump_in_i++;
9362     }
9363   }
9364   assert(jump_in_i == jump_in_count);
9365   hash_table_add(block->jump_in[0].vaddr, block->jump_in[0].addr);
9366   // Write out the literal pool if necessary
9367   literal_pool(0);
9368   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9369   // Align code
9370   if(((u_int)out)&7) emit_addnop(13);
9371   #endif
9372   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9373   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9374   memcpy(copy, source, source_len);
9375   copy += source_len;
9376
9377   end_block(beginning);
9378
9379   // If we're within 256K of the end of the buffer,
9380   // start over from the beginning. (Is 256K enough?)
9381   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9382     out = ndrc->translation_cache;
9383
9384   // Trap writes to any of the pages we compiled
9385   mark_invalid_code(start, slen*4, 0);
9386
9387   /* Pass 10 - Free memory by expiring oldest blocks */
9388
9389   pass10_expire_blocks();
9390
9391 #ifdef ASSEM_PRINT
9392   fflush(stdout);
9393 #endif
9394   stat_inc(stat_bc_direct);
9395   return 0;
9396 }
9397
9398 // vim:shiftwidth=2:expandtab