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