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