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