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