4ec3c53ce22a123f65ab337cd02b817b7a4560b3
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32 #ifdef VITA
33 #include <psp2/kernel/sysmem.h>
34 static int sceBlock;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "emu_if.h" //emulator interface
41
42 #define noinline __attribute__((noinline,noclone))
43 #ifndef ARRAY_SIZE
44 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
45 #endif
46
47 //#define DISASM
48 //#define assem_debug printf
49 //#define inv_debug printf
50 #define assem_debug(...)
51 #define inv_debug(...)
52
53 #ifdef __i386__
54 #include "assem_x86.h"
55 #endif
56 #ifdef __x86_64__
57 #include "assem_x64.h"
58 #endif
59 #ifdef __arm__
60 #include "assem_arm.h"
61 #endif
62 #ifdef __aarch64__
63 #include "assem_arm64.h"
64 #endif
65
66 #define MAXBLOCK 4096
67 #define MAX_OUTPUT_BLOCK_SIZE 262144
68
69 struct ndrc_mem
70 {
71   u_char translation_cache[1 << TARGET_SIZE_2];
72   struct
73   {
74     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
75     const void *f[2048 / sizeof(void *)];
76   } tramp;
77 };
78
79 #ifdef BASE_ADDR_DYNAMIC
80 static struct ndrc_mem *ndrc;
81 #else
82 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
83 static struct ndrc_mem *ndrc = &ndrc_;
84 #endif
85
86 // stubs
87 enum stub_type {
88   CC_STUB = 1,
89   FP_STUB = 2,
90   LOADB_STUB = 3,
91   LOADH_STUB = 4,
92   LOADW_STUB = 5,
93   LOADD_STUB = 6,
94   LOADBU_STUB = 7,
95   LOADHU_STUB = 8,
96   STOREB_STUB = 9,
97   STOREH_STUB = 10,
98   STOREW_STUB = 11,
99   STORED_STUB = 12,
100   STORELR_STUB = 13,
101   INVCODE_STUB = 14,
102 };
103
104 struct regstat
105 {
106   signed char regmap_entry[HOST_REGS];
107   signed char regmap[HOST_REGS];
108   uint64_t wasdirty;
109   uint64_t dirty;
110   uint64_t u;
111   u_int wasconst;
112   u_int isconst;
113   u_int loadedconst;             // host regs that have constants loaded
114   u_int waswritten;              // MIPS regs that were used as store base before
115 };
116
117 // note: asm depends on this layout
118 struct ll_entry
119 {
120   u_int vaddr;
121   u_int reg_sv_flags;
122   void *addr;
123   struct ll_entry *next;
124 };
125
126 struct ht_entry
127 {
128   u_int vaddr[2];
129   void *tcaddr[2];
130 };
131
132 struct code_stub
133 {
134   enum stub_type type;
135   void *addr;
136   void *retaddr;
137   u_int a;
138   uintptr_t b;
139   uintptr_t c;
140   u_int d;
141   u_int e;
142 };
143
144 struct link_entry
145 {
146   void *addr;
147   u_int target;
148   u_int ext;
149 };
150
151   // used by asm:
152   u_char *out;
153   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
154   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
155   struct ll_entry *jump_dirty[4096];
156
157   static struct ll_entry *jump_out[4096];
158   static u_int start;
159   static u_int *source;
160   static char insn[MAXBLOCK][10];
161   static u_char itype[MAXBLOCK];
162   static u_char opcode[MAXBLOCK];
163   static u_char opcode2[MAXBLOCK];
164   static u_char bt[MAXBLOCK];
165   static u_char rs1[MAXBLOCK];
166   static u_char rs2[MAXBLOCK];
167   static u_char rt1[MAXBLOCK];
168   static u_char rt2[MAXBLOCK];
169   static u_char dep1[MAXBLOCK];
170   static u_char dep2[MAXBLOCK];
171   static u_char lt1[MAXBLOCK];
172   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
173   static uint64_t gte_rt[MAXBLOCK];
174   static uint64_t gte_unneeded[MAXBLOCK];
175   static u_int smrv[32]; // speculated MIPS register values
176   static u_int smrv_strong; // mask or regs that are likely to have correct values
177   static u_int smrv_weak; // same, but somewhat less likely
178   static u_int smrv_strong_next; // same, but after current insn executes
179   static u_int smrv_weak_next;
180   static int imm[MAXBLOCK];
181   static u_int ba[MAXBLOCK];
182   static char likely[MAXBLOCK];
183   static char is_ds[MAXBLOCK];
184   static char ooo[MAXBLOCK];
185   static uint64_t unneeded_reg[MAXBLOCK];
186   static uint64_t branch_unneeded_reg[MAXBLOCK];
187   static signed char regmap_pre[MAXBLOCK][HOST_REGS]; // pre-instruction i?
188   // contains 'real' consts at [i] insn, but may differ from what's actually
189   // loaded in host reg as 'final' value is always loaded, see get_final_value()
190   static uint32_t current_constmap[HOST_REGS];
191   static uint32_t constmap[MAXBLOCK][HOST_REGS];
192   static struct regstat regs[MAXBLOCK];
193   static struct regstat branch_regs[MAXBLOCK];
194   static signed char minimum_free_regs[MAXBLOCK];
195   static u_int needed_reg[MAXBLOCK];
196   static u_int wont_dirty[MAXBLOCK];
197   static u_int will_dirty[MAXBLOCK];
198   static int ccadj[MAXBLOCK];
199   static int slen;
200   static void *instr_addr[MAXBLOCK];
201   static struct link_entry link_addr[MAXBLOCK];
202   static int linkcount;
203   static struct code_stub stubs[MAXBLOCK*3];
204   static int stubcount;
205   static u_int literals[1024][2];
206   static int literalcount;
207   static int is_delayslot;
208   static char shadow[1048576]  __attribute__((aligned(16)));
209   static void *copy;
210   static int expirep;
211   static u_int stop_after_jal;
212 #ifndef RAM_FIXED
213   static uintptr_t ram_offset;
214 #else
215   static const uintptr_t ram_offset=0;
216 #endif
217
218   int new_dynarec_hacks;
219   int new_dynarec_did_compile;
220
221   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
222   extern int last_count;  // last absolute target, often = next_interupt
223   extern int pcaddr;
224   extern int pending_exception;
225   extern int branch_target;
226   extern uintptr_t mini_ht[32][2];
227   extern u_char restore_candidate[512];
228
229   /* registers that may be allocated */
230   /* 1-31 gpr */
231 #define LOREG 32 // lo
232 #define HIREG 33 // hi
233 //#define FSREG 34 // FPU status (FCSR)
234 #define CSREG 35 // Coprocessor status
235 #define CCREG 36 // Cycle count
236 #define INVCP 37 // Pointer to invalid_code
237 //#define MMREG 38 // Pointer to memory_map
238 //#define ROREG 39 // ram offset (if rdram!=0x80000000)
239 #define TEMPREG 40
240 #define FTEMP 40 // FPU temporary register
241 #define PTEMP 41 // Prefetch temporary register
242 //#define TLREG 42 // TLB mapping offset
243 #define RHASH 43 // Return address hash
244 #define RHTBL 44 // Return address hash table address
245 #define RTEMP 45 // JR/JALR address register
246 #define MAXREG 45
247 #define AGEN1 46 // Address generation temporary register
248 //#define AGEN2 47 // Address generation temporary register
249 //#define MGEN1 48 // Maptable address generation temporary register
250 //#define MGEN2 49 // Maptable address generation temporary register
251 #define BTREG 50 // Branch target temporary register
252
253   /* instruction types */
254 #define NOP 0     // No operation
255 #define LOAD 1    // Load
256 #define STORE 2   // Store
257 #define LOADLR 3  // Unaligned load
258 #define STORELR 4 // Unaligned store
259 #define MOV 5     // Move
260 #define ALU 6     // Arithmetic/logic
261 #define MULTDIV 7 // Multiply/divide
262 #define SHIFT 8   // Shift by register
263 #define SHIFTIMM 9// Shift by immediate
264 #define IMM16 10  // 16-bit immediate
265 #define RJUMP 11  // Unconditional jump to register
266 #define UJUMP 12  // Unconditional jump
267 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
268 #define SJUMP 14  // Conditional branch (regimm format)
269 #define COP0 15   // Coprocessor 0
270 #define COP1 16   // Coprocessor 1
271 #define C1LS 17   // Coprocessor 1 load/store
272 //#define FJUMP 18  // Conditional branch (floating point)
273 //#define FLOAT 19  // Floating point unit
274 //#define FCONV 20  // Convert integer to float
275 //#define FCOMP 21  // Floating point compare (sets FSREG)
276 #define SYSCALL 22// SYSCALL
277 #define OTHER 23  // Other
278 #define SPAN 24   // Branch/delay slot spans 2 pages
279 #define NI 25     // Not implemented
280 #define HLECALL 26// PCSX fake opcodes for HLE
281 #define COP2 27   // Coprocessor 2 move
282 #define C2LS 28   // Coprocessor 2 load/store
283 #define C2OP 29   // Coprocessor 2 operation
284 #define INTCALL 30// Call interpreter to handle rare corner cases
285
286   /* branch codes */
287 #define TAKEN 1
288 #define NOTTAKEN 2
289 #define NULLDS 3
290
291 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
292 #define DJT_2 (void *)2l
293
294 // asm linkage
295 int new_recompile_block(u_int addr);
296 void *get_addr_ht(u_int vaddr);
297 void invalidate_block(u_int block);
298 void invalidate_addr(u_int addr);
299 void remove_hash(int vaddr);
300 void dyna_linker();
301 void dyna_linker_ds();
302 void verify_code();
303 void verify_code_ds();
304 void cc_interrupt();
305 void fp_exception();
306 void fp_exception_ds();
307 void jump_to_new_pc();
308 void new_dyna_leave();
309
310 // Needed by assembler
311 static void wb_register(signed char r,signed char regmap[],uint64_t dirty);
312 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty);
313 static void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr);
314 static void load_all_regs(signed char i_regmap[]);
315 static void load_needed_regs(signed char i_regmap[],signed char next_regmap[]);
316 static void load_regs_entry(int t);
317 static void load_all_consts(signed char regmap[],u_int dirty,int i);
318
319 static int verify_dirty(const u_int *ptr);
320 static int get_final_value(int hr, int i, int *value);
321 static void add_stub(enum stub_type type, void *addr, void *retaddr,
322   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
323 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
324   int i, int addr_reg, struct regstat *i_regs, int ccadj, u_int reglist);
325 static void add_to_linker(void *addr, u_int target, int ext);
326 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override);
327 static void *get_direct_memhandler(void *table, u_int addr,
328   enum stub_type type, uintptr_t *addr_host);
329 static void pass_args(int a0, int a1);
330 static void emit_far_jump(const void *f);
331 static void emit_far_call(const void *f);
332
333 static void mprotect_w_x(void *start, void *end, int is_x)
334 {
335 #ifdef NO_WRITE_EXEC
336   #if defined(VITA)
337   // *Open* enables write on all memory that was
338   // allocated by sceKernelAllocMemBlockForVM()?
339   if (is_x)
340     sceKernelCloseVMDomain();
341   else
342     sceKernelOpenVMDomain();
343   #else
344   u_long mstart = (u_long)start & ~4095ul;
345   u_long mend = (u_long)end;
346   if (mprotect((void *)mstart, mend - mstart,
347                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
348     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
349   #endif
350 #endif
351 }
352
353 static void start_tcache_write(void *start, void *end)
354 {
355   mprotect_w_x(start, end, 0);
356 }
357
358 static void end_tcache_write(void *start, void *end)
359 {
360 #if defined(__arm__) || defined(__aarch64__)
361   size_t len = (char *)end - (char *)start;
362   #if   defined(__BLACKBERRY_QNX__)
363   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
364   #elif defined(__MACH__)
365   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
366   #elif defined(VITA)
367   sceKernelSyncVMDomain(sceBlock, start, len);
368   #elif defined(_3DS)
369   ctr_flush_invalidate_cache();
370   #elif defined(__aarch64__)
371   // as of 2021, __clear_cache() is still broken on arm64
372   // so here is a custom one :(
373   clear_cache_arm64(start, end);
374   #else
375   __clear_cache(start, end);
376   #endif
377   (void)len;
378 #endif
379
380   mprotect_w_x(start, end, 1);
381 }
382
383 static void *start_block(void)
384 {
385   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
386   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
387     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
388   start_tcache_write(out, end);
389   return out;
390 }
391
392 static void end_block(void *start)
393 {
394   end_tcache_write(start, out);
395 }
396
397 // also takes care of w^x mappings when patching code
398 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
399
400 static void mark_clear_cache(void *target)
401 {
402   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
403   u_int mask = 1u << ((offset >> 12) & 31);
404   if (!(needs_clear_cache[offset >> 17] & mask)) {
405     char *start = (char *)((uintptr_t)target & ~4095l);
406     start_tcache_write(start, start + 4095);
407     needs_clear_cache[offset >> 17] |= mask;
408   }
409 }
410
411 // Clearing the cache is rather slow on ARM Linux, so mark the areas
412 // that need to be cleared, and then only clear these areas once.
413 static void do_clear_cache(void)
414 {
415   int i, j;
416   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
417   {
418     u_int bitmap = needs_clear_cache[i];
419     if (!bitmap)
420       continue;
421     for (j = 0; j < 32; j++)
422     {
423       u_char *start, *end;
424       if (!(bitmap & (1<<j)))
425         continue;
426
427       start = ndrc->translation_cache + i*131072 + j*4096;
428       end = start + 4095;
429       for (j++; j < 32; j++) {
430         if (!(bitmap & (1<<j)))
431           break;
432         end += 4096;
433       }
434       end_tcache_write(start, end);
435     }
436     needs_clear_cache[i] = 0;
437   }
438 }
439
440 //#define DEBUG_CYCLE_COUNT 1
441
442 #define NO_CYCLE_PENALTY_THR 12
443
444 int cycle_multiplier; // 100 for 1.0
445
446 static int CLOCK_ADJUST(int x)
447 {
448   int s=(x>>31)|1;
449   return (x * cycle_multiplier + s * 50) / 100;
450 }
451
452 static u_int get_page(u_int vaddr)
453 {
454   u_int page=vaddr&~0xe0000000;
455   if (page < 0x1000000)
456     page &= ~0x0e00000; // RAM mirrors
457   page>>=12;
458   if(page>2048) page=2048+(page&2047);
459   return page;
460 }
461
462 // no virtual mem in PCSX
463 static u_int get_vpage(u_int vaddr)
464 {
465   return get_page(vaddr);
466 }
467
468 static struct ht_entry *hash_table_get(u_int vaddr)
469 {
470   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
471 }
472
473 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
474 {
475   ht_bin->vaddr[1] = ht_bin->vaddr[0];
476   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
477   ht_bin->vaddr[0] = vaddr;
478   ht_bin->tcaddr[0] = tcaddr;
479 }
480
481 // some messy ari64's code, seems to rely on unsigned 32bit overflow
482 static int doesnt_expire_soon(void *tcaddr)
483 {
484   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
485   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
486 }
487
488 // Get address from virtual address
489 // This is called from the recompiled JR/JALR instructions
490 void noinline *get_addr(u_int vaddr)
491 {
492   u_int page=get_page(vaddr);
493   u_int vpage=get_vpage(vaddr);
494   struct ll_entry *head;
495   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
496   head=jump_in[page];
497   while(head!=NULL) {
498     if(head->vaddr==vaddr) {
499   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
500       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
501       return head->addr;
502     }
503     head=head->next;
504   }
505   head=jump_dirty[vpage];
506   while(head!=NULL) {
507     if(head->vaddr==vaddr) {
508       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
509       // Don't restore blocks which are about to expire from the cache
510       if (doesnt_expire_soon(head->addr))
511       if (verify_dirty(head->addr)) {
512         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
513         invalid_code[vaddr>>12]=0;
514         inv_code_start=inv_code_end=~0;
515         if(vpage<2048) {
516           restore_candidate[vpage>>3]|=1<<(vpage&7);
517         }
518         else restore_candidate[page>>3]|=1<<(page&7);
519         struct ht_entry *ht_bin = hash_table_get(vaddr);
520         if (ht_bin->vaddr[0] == vaddr)
521           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
522         else
523           hash_table_add(ht_bin, vaddr, head->addr);
524
525         return head->addr;
526       }
527     }
528     head=head->next;
529   }
530   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
531   int r=new_recompile_block(vaddr);
532   if(r==0) return get_addr(vaddr);
533   // Execute in unmapped page, generate pagefault execption
534   Status|=2;
535   Cause=(vaddr<<31)|0x8;
536   EPC=(vaddr&1)?vaddr-5:vaddr;
537   BadVAddr=(vaddr&~1);
538   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
539   EntryHi=BadVAddr&0xFFFFE000;
540   return get_addr_ht(0x80000000);
541 }
542 // Look up address in hash table first
543 void *get_addr_ht(u_int vaddr)
544 {
545   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
546   const struct ht_entry *ht_bin = hash_table_get(vaddr);
547   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
548   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
549   return get_addr(vaddr);
550 }
551
552 void clear_all_regs(signed char regmap[])
553 {
554   int hr;
555   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
556 }
557
558 static signed char get_reg(const signed char regmap[],int r)
559 {
560   int hr;
561   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
562   return -1;
563 }
564
565 // Find a register that is available for two consecutive cycles
566 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
567 {
568   int hr;
569   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
570   return -1;
571 }
572
573 int count_free_regs(signed char regmap[])
574 {
575   int count=0;
576   int hr;
577   for(hr=0;hr<HOST_REGS;hr++)
578   {
579     if(hr!=EXCLUDE_REG) {
580       if(regmap[hr]<0) count++;
581     }
582   }
583   return count;
584 }
585
586 void dirty_reg(struct regstat *cur,signed char reg)
587 {
588   int hr;
589   if(!reg) return;
590   for (hr=0;hr<HOST_REGS;hr++) {
591     if((cur->regmap[hr]&63)==reg) {
592       cur->dirty|=1<<hr;
593     }
594   }
595 }
596
597 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
598 {
599   int hr;
600   if(!reg) return;
601   for (hr=0;hr<HOST_REGS;hr++) {
602     if(cur->regmap[hr]==reg) {
603       cur->isconst|=1<<hr;
604       current_constmap[hr]=value;
605     }
606   }
607 }
608
609 static void clear_const(struct regstat *cur, signed char reg)
610 {
611   int hr;
612   if(!reg) return;
613   for (hr=0;hr<HOST_REGS;hr++) {
614     if((cur->regmap[hr]&63)==reg) {
615       cur->isconst&=~(1<<hr);
616     }
617   }
618 }
619
620 static int is_const(struct regstat *cur, signed char reg)
621 {
622   int hr;
623   if(reg<0) return 0;
624   if(!reg) return 1;
625   for (hr=0;hr<HOST_REGS;hr++) {
626     if((cur->regmap[hr]&63)==reg) {
627       return (cur->isconst>>hr)&1;
628     }
629   }
630   return 0;
631 }
632
633 static uint32_t get_const(struct regstat *cur, signed char reg)
634 {
635   int hr;
636   if(!reg) return 0;
637   for (hr=0;hr<HOST_REGS;hr++) {
638     if(cur->regmap[hr]==reg) {
639       return current_constmap[hr];
640     }
641   }
642   SysPrintf("Unknown constant in r%d\n",reg);
643   abort();
644 }
645
646 // Least soon needed registers
647 // Look at the next ten instructions and see which registers
648 // will be used.  Try not to reallocate these.
649 void lsn(u_char hsn[], int i, int *preferred_reg)
650 {
651   int j;
652   int b=-1;
653   for(j=0;j<9;j++)
654   {
655     if(i+j>=slen) {
656       j=slen-i-1;
657       break;
658     }
659     if(itype[i+j]==UJUMP||itype[i+j]==RJUMP||(source[i+j]>>16)==0x1000)
660     {
661       // Don't go past an unconditonal jump
662       j++;
663       break;
664     }
665   }
666   for(;j>=0;j--)
667   {
668     if(rs1[i+j]) hsn[rs1[i+j]]=j;
669     if(rs2[i+j]) hsn[rs2[i+j]]=j;
670     if(rt1[i+j]) hsn[rt1[i+j]]=j;
671     if(rt2[i+j]) hsn[rt2[i+j]]=j;
672     if(itype[i+j]==STORE || itype[i+j]==STORELR) {
673       // Stores can allocate zero
674       hsn[rs1[i+j]]=j;
675       hsn[rs2[i+j]]=j;
676     }
677     // On some architectures stores need invc_ptr
678     #if defined(HOST_IMM8)
679     if(itype[i+j]==STORE || itype[i+j]==STORELR || (opcode[i+j]&0x3b)==0x39 || (opcode[i+j]&0x3b)==0x3a) {
680       hsn[INVCP]=j;
681     }
682     #endif
683     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
684     {
685       hsn[CCREG]=j;
686       b=j;
687     }
688   }
689   if(b>=0)
690   {
691     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
692     {
693       // Follow first branch
694       int t=(ba[i+b]-start)>>2;
695       j=7-b;if(t+j>=slen) j=slen-t-1;
696       for(;j>=0;j--)
697       {
698         if(rs1[t+j]) if(hsn[rs1[t+j]]>j+b+2) hsn[rs1[t+j]]=j+b+2;
699         if(rs2[t+j]) if(hsn[rs2[t+j]]>j+b+2) hsn[rs2[t+j]]=j+b+2;
700         //if(rt1[t+j]) if(hsn[rt1[t+j]]>j+b+2) hsn[rt1[t+j]]=j+b+2;
701         //if(rt2[t+j]) if(hsn[rt2[t+j]]>j+b+2) hsn[rt2[t+j]]=j+b+2;
702       }
703     }
704     // TODO: preferred register based on backward branch
705   }
706   // Delay slot should preferably not overwrite branch conditions or cycle count
707   if(i>0&&(itype[i-1]==RJUMP||itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)) {
708     if(rs1[i-1]) if(hsn[rs1[i-1]]>1) hsn[rs1[i-1]]=1;
709     if(rs2[i-1]) if(hsn[rs2[i-1]]>1) hsn[rs2[i-1]]=1;
710     hsn[CCREG]=1;
711     // ...or hash tables
712     hsn[RHASH]=1;
713     hsn[RHTBL]=1;
714   }
715   // Coprocessor load/store needs FTEMP, even if not declared
716   if(itype[i]==C1LS||itype[i]==C2LS) {
717     hsn[FTEMP]=0;
718   }
719   // Load L/R also uses FTEMP as a temporary register
720   if(itype[i]==LOADLR) {
721     hsn[FTEMP]=0;
722   }
723   // Also SWL/SWR/SDL/SDR
724   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) {
725     hsn[FTEMP]=0;
726   }
727   // Don't remove the miniht registers
728   if(itype[i]==UJUMP||itype[i]==RJUMP)
729   {
730     hsn[RHASH]=0;
731     hsn[RHTBL]=0;
732   }
733 }
734
735 // We only want to allocate registers if we're going to use them again soon
736 int needed_again(int r, int i)
737 {
738   int j;
739   int b=-1;
740   int rn=10;
741
742   if(i>0&&(itype[i-1]==UJUMP||itype[i-1]==RJUMP||(source[i-1]>>16)==0x1000))
743   {
744     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
745       return 0; // Don't need any registers if exiting the block
746   }
747   for(j=0;j<9;j++)
748   {
749     if(i+j>=slen) {
750       j=slen-i-1;
751       break;
752     }
753     if(itype[i+j]==UJUMP||itype[i+j]==RJUMP||(source[i+j]>>16)==0x1000)
754     {
755       // Don't go past an unconditonal jump
756       j++;
757       break;
758     }
759     if(itype[i+j]==SYSCALL||itype[i+j]==HLECALL||itype[i+j]==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
760     {
761       break;
762     }
763   }
764   for(;j>=1;j--)
765   {
766     if(rs1[i+j]==r) rn=j;
767     if(rs2[i+j]==r) rn=j;
768     if((unneeded_reg[i+j]>>r)&1) rn=10;
769     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
770     {
771       b=j;
772     }
773   }
774   /*
775   if(b>=0)
776   {
777     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
778     {
779       // Follow first branch
780       int o=rn;
781       int t=(ba[i+b]-start)>>2;
782       j=7-b;if(t+j>=slen) j=slen-t-1;
783       for(;j>=0;j--)
784       {
785         if(!((unneeded_reg[t+j]>>r)&1)) {
786           if(rs1[t+j]==r) if(rn>j+b+2) rn=j+b+2;
787           if(rs2[t+j]==r) if(rn>j+b+2) rn=j+b+2;
788         }
789         else rn=o;
790       }
791     }
792   }*/
793   if(rn<10) return 1;
794   (void)b;
795   return 0;
796 }
797
798 // Try to match register allocations at the end of a loop with those
799 // at the beginning
800 int loop_reg(int i, int r, int hr)
801 {
802   int j,k;
803   for(j=0;j<9;j++)
804   {
805     if(i+j>=slen) {
806       j=slen-i-1;
807       break;
808     }
809     if(itype[i+j]==UJUMP||itype[i+j]==RJUMP||(source[i+j]>>16)==0x1000)
810     {
811       // Don't go past an unconditonal jump
812       j++;
813       break;
814     }
815   }
816   k=0;
817   if(i>0){
818     if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)
819       k--;
820   }
821   for(;k<j;k++)
822   {
823     assert(r < 64);
824     if((unneeded_reg[i+k]>>r)&1) return hr;
825     if(i+k>=0&&(itype[i+k]==UJUMP||itype[i+k]==CJUMP||itype[i+k]==SJUMP))
826     {
827       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
828       {
829         int t=(ba[i+k]-start)>>2;
830         int reg=get_reg(regs[t].regmap_entry,r);
831         if(reg>=0) return reg;
832         //reg=get_reg(regs[t+1].regmap_entry,r);
833         //if(reg>=0) return reg;
834       }
835     }
836   }
837   return hr;
838 }
839
840
841 // Allocate every register, preserving source/target regs
842 void alloc_all(struct regstat *cur,int i)
843 {
844   int hr;
845
846   for(hr=0;hr<HOST_REGS;hr++) {
847     if(hr!=EXCLUDE_REG) {
848       if(((cur->regmap[hr]&63)!=rs1[i])&&((cur->regmap[hr]&63)!=rs2[i])&&
849          ((cur->regmap[hr]&63)!=rt1[i])&&((cur->regmap[hr]&63)!=rt2[i]))
850       {
851         cur->regmap[hr]=-1;
852         cur->dirty&=~(1<<hr);
853       }
854       // Don't need zeros
855       if((cur->regmap[hr]&63)==0)
856       {
857         cur->regmap[hr]=-1;
858         cur->dirty&=~(1<<hr);
859       }
860     }
861   }
862 }
863
864 #ifndef NDEBUG
865 static int host_tempreg_in_use;
866
867 static void host_tempreg_acquire(void)
868 {
869   assert(!host_tempreg_in_use);
870   host_tempreg_in_use = 1;
871 }
872
873 static void host_tempreg_release(void)
874 {
875   host_tempreg_in_use = 0;
876 }
877 #else
878 static void host_tempreg_acquire(void) {}
879 static void host_tempreg_release(void) {}
880 #endif
881
882 #ifdef DRC_DBG
883 extern void gen_interupt();
884 extern void do_insn_cmp();
885 #define FUNCNAME(f) { f, " " #f }
886 static const struct {
887   void *addr;
888   const char *name;
889 } function_names[] = {
890   FUNCNAME(cc_interrupt),
891   FUNCNAME(gen_interupt),
892   FUNCNAME(get_addr_ht),
893   FUNCNAME(get_addr),
894   FUNCNAME(jump_handler_read8),
895   FUNCNAME(jump_handler_read16),
896   FUNCNAME(jump_handler_read32),
897   FUNCNAME(jump_handler_write8),
898   FUNCNAME(jump_handler_write16),
899   FUNCNAME(jump_handler_write32),
900   FUNCNAME(invalidate_addr),
901   FUNCNAME(jump_to_new_pc),
902   FUNCNAME(new_dyna_leave),
903   FUNCNAME(pcsx_mtc0),
904   FUNCNAME(pcsx_mtc0_ds),
905   FUNCNAME(do_insn_cmp),
906 #ifdef __arm__
907   FUNCNAME(verify_code),
908 #endif
909 };
910
911 static const char *func_name(const void *a)
912 {
913   int i;
914   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
915     if (function_names[i].addr == a)
916       return function_names[i].name;
917   return "";
918 }
919 #else
920 #define func_name(x) ""
921 #endif
922
923 #ifdef __i386__
924 #include "assem_x86.c"
925 #endif
926 #ifdef __x86_64__
927 #include "assem_x64.c"
928 #endif
929 #ifdef __arm__
930 #include "assem_arm.c"
931 #endif
932 #ifdef __aarch64__
933 #include "assem_arm64.c"
934 #endif
935
936 static void *get_trampoline(const void *f)
937 {
938   size_t i;
939
940   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
941     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
942       break;
943   }
944   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
945     SysPrintf("trampoline table is full, last func %p\n", f);
946     abort();
947   }
948   if (ndrc->tramp.f[i] == NULL) {
949     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
950     ndrc->tramp.f[i] = f;
951     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
952   }
953   return &ndrc->tramp.ops[i];
954 }
955
956 static void emit_far_jump(const void *f)
957 {
958   if (can_jump_or_call(f)) {
959     emit_jmp(f);
960     return;
961   }
962
963   f = get_trampoline(f);
964   emit_jmp(f);
965 }
966
967 static void emit_far_call(const void *f)
968 {
969   if (can_jump_or_call(f)) {
970     emit_call(f);
971     return;
972   }
973
974   f = get_trampoline(f);
975   emit_call(f);
976 }
977
978 // Add virtual address mapping to linked list
979 void ll_add(struct ll_entry **head,int vaddr,void *addr)
980 {
981   struct ll_entry *new_entry;
982   new_entry=malloc(sizeof(struct ll_entry));
983   assert(new_entry!=NULL);
984   new_entry->vaddr=vaddr;
985   new_entry->reg_sv_flags=0;
986   new_entry->addr=addr;
987   new_entry->next=*head;
988   *head=new_entry;
989 }
990
991 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
992 {
993   ll_add(head,vaddr,addr);
994   (*head)->reg_sv_flags=reg_sv_flags;
995 }
996
997 // Check if an address is already compiled
998 // but don't return addresses which are about to expire from the cache
999 void *check_addr(u_int vaddr)
1000 {
1001   struct ht_entry *ht_bin = hash_table_get(vaddr);
1002   size_t i;
1003   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1004     if (ht_bin->vaddr[i] == vaddr)
1005       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1006         if (isclean(ht_bin->tcaddr[i]))
1007           return ht_bin->tcaddr[i];
1008   }
1009   u_int page=get_page(vaddr);
1010   struct ll_entry *head;
1011   head=jump_in[page];
1012   while (head != NULL) {
1013     if (head->vaddr == vaddr) {
1014       if (doesnt_expire_soon(head->addr)) {
1015         // Update existing entry with current address
1016         if (ht_bin->vaddr[0] == vaddr) {
1017           ht_bin->tcaddr[0] = head->addr;
1018           return head->addr;
1019         }
1020         if (ht_bin->vaddr[1] == vaddr) {
1021           ht_bin->tcaddr[1] = head->addr;
1022           return head->addr;
1023         }
1024         // Insert into hash table with low priority.
1025         // Don't evict existing entries, as they are probably
1026         // addresses that are being accessed frequently.
1027         if (ht_bin->vaddr[0] == -1) {
1028           ht_bin->vaddr[0] = vaddr;
1029           ht_bin->tcaddr[0] = head->addr;
1030         }
1031         else if (ht_bin->vaddr[1] == -1) {
1032           ht_bin->vaddr[1] = vaddr;
1033           ht_bin->tcaddr[1] = head->addr;
1034         }
1035         return head->addr;
1036       }
1037     }
1038     head=head->next;
1039   }
1040   return 0;
1041 }
1042
1043 void remove_hash(int vaddr)
1044 {
1045   //printf("remove hash: %x\n",vaddr);
1046   struct ht_entry *ht_bin = hash_table_get(vaddr);
1047   if (ht_bin->vaddr[1] == vaddr) {
1048     ht_bin->vaddr[1] = -1;
1049     ht_bin->tcaddr[1] = NULL;
1050   }
1051   if (ht_bin->vaddr[0] == vaddr) {
1052     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1053     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1054     ht_bin->vaddr[1] = -1;
1055     ht_bin->tcaddr[1] = NULL;
1056   }
1057 }
1058
1059 void ll_remove_matching_addrs(struct ll_entry **head,uintptr_t addr,int shift)
1060 {
1061   struct ll_entry *next;
1062   while(*head) {
1063     if(((uintptr_t)((*head)->addr)>>shift)==(addr>>shift) ||
1064        ((uintptr_t)((*head)->addr-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(addr>>shift))
1065     {
1066       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1067       remove_hash((*head)->vaddr);
1068       next=(*head)->next;
1069       free(*head);
1070       *head=next;
1071     }
1072     else
1073     {
1074       head=&((*head)->next);
1075     }
1076   }
1077 }
1078
1079 // Remove all entries from linked list
1080 void ll_clear(struct ll_entry **head)
1081 {
1082   struct ll_entry *cur;
1083   struct ll_entry *next;
1084   if((cur=*head)) {
1085     *head=0;
1086     while(cur) {
1087       next=cur->next;
1088       free(cur);
1089       cur=next;
1090     }
1091   }
1092 }
1093
1094 // Dereference the pointers and remove if it matches
1095 static void ll_kill_pointers(struct ll_entry *head,uintptr_t addr,int shift)
1096 {
1097   while(head) {
1098     uintptr_t ptr = (uintptr_t)get_pointer(head->addr);
1099     inv_debug("EXP: Lookup pointer to %lx at %p (%x)\n",(long)ptr,head->addr,head->vaddr);
1100     if(((ptr>>shift)==(addr>>shift)) ||
1101        (((ptr-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(addr>>shift)))
1102     {
1103       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1104       void *host_addr=find_extjump_insn(head->addr);
1105       mark_clear_cache(host_addr);
1106       set_jump_target(host_addr, head->addr);
1107     }
1108     head=head->next;
1109   }
1110 }
1111
1112 // This is called when we write to a compiled block (see do_invstub)
1113 static void invalidate_page(u_int page)
1114 {
1115   struct ll_entry *head;
1116   struct ll_entry *next;
1117   head=jump_in[page];
1118   jump_in[page]=0;
1119   while(head!=NULL) {
1120     inv_debug("INVALIDATE: %x\n",head->vaddr);
1121     remove_hash(head->vaddr);
1122     next=head->next;
1123     free(head);
1124     head=next;
1125   }
1126   head=jump_out[page];
1127   jump_out[page]=0;
1128   while(head!=NULL) {
1129     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1130     void *host_addr=find_extjump_insn(head->addr);
1131     mark_clear_cache(host_addr);
1132     set_jump_target(host_addr, head->addr);
1133     next=head->next;
1134     free(head);
1135     head=next;
1136   }
1137 }
1138
1139 static void invalidate_block_range(u_int block, u_int first, u_int last)
1140 {
1141   u_int page=get_page(block<<12);
1142   //printf("first=%d last=%d\n",first,last);
1143   invalidate_page(page);
1144   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1145   assert(last<page+5);
1146   // Invalidate the adjacent pages if a block crosses a 4K boundary
1147   while(first<page) {
1148     invalidate_page(first);
1149     first++;
1150   }
1151   for(first=page+1;first<last;first++) {
1152     invalidate_page(first);
1153   }
1154   do_clear_cache();
1155
1156   // Don't trap writes
1157   invalid_code[block]=1;
1158
1159   #ifdef USE_MINI_HT
1160   memset(mini_ht,-1,sizeof(mini_ht));
1161   #endif
1162 }
1163
1164 void invalidate_block(u_int block)
1165 {
1166   u_int page=get_page(block<<12);
1167   u_int vpage=get_vpage(block<<12);
1168   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1169   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1170   u_int first,last;
1171   first=last=page;
1172   struct ll_entry *head;
1173   head=jump_dirty[vpage];
1174   //printf("page=%d vpage=%d\n",page,vpage);
1175   while(head!=NULL) {
1176     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1177       u_char *start, *end;
1178       get_bounds(head->addr, &start, &end);
1179       //printf("start: %p end: %p\n", start, end);
1180       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1181         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1182           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1183           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1184         }
1185       }
1186     }
1187     head=head->next;
1188   }
1189   invalidate_block_range(block,first,last);
1190 }
1191
1192 void invalidate_addr(u_int addr)
1193 {
1194   //static int rhits;
1195   // this check is done by the caller
1196   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1197   u_int page=get_vpage(addr);
1198   if(page<2048) { // RAM
1199     struct ll_entry *head;
1200     u_int addr_min=~0, addr_max=0;
1201     u_int mask=RAM_SIZE-1;
1202     u_int addr_main=0x80000000|(addr&mask);
1203     int pg1;
1204     inv_code_start=addr_main&~0xfff;
1205     inv_code_end=addr_main|0xfff;
1206     pg1=page;
1207     if (pg1>0) {
1208       // must check previous page too because of spans..
1209       pg1--;
1210       inv_code_start-=0x1000;
1211     }
1212     for(;pg1<=page;pg1++) {
1213       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1214         u_char *start_h, *end_h;
1215         u_int start, end;
1216         get_bounds(head->addr, &start_h, &end_h);
1217         start = (uintptr_t)start_h - ram_offset;
1218         end = (uintptr_t)end_h - ram_offset;
1219         if(start<=addr_main&&addr_main<end) {
1220           if(start<addr_min) addr_min=start;
1221           if(end>addr_max) addr_max=end;
1222         }
1223         else if(addr_main<start) {
1224           if(start<inv_code_end)
1225             inv_code_end=start-1;
1226         }
1227         else {
1228           if(end>inv_code_start)
1229             inv_code_start=end;
1230         }
1231       }
1232     }
1233     if (addr_min!=~0) {
1234       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1235       inv_code_start=inv_code_end=~0;
1236       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1237       return;
1238     }
1239     else {
1240       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1241       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1242       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1243       return;
1244     }
1245   }
1246   invalidate_block(addr>>12);
1247 }
1248
1249 // This is called when loading a save state.
1250 // Anything could have changed, so invalidate everything.
1251 void invalidate_all_pages(void)
1252 {
1253   u_int page;
1254   for(page=0;page<4096;page++)
1255     invalidate_page(page);
1256   for(page=0;page<1048576;page++)
1257     if(!invalid_code[page]) {
1258       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1259       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1260     }
1261   #ifdef USE_MINI_HT
1262   memset(mini_ht,-1,sizeof(mini_ht));
1263   #endif
1264   do_clear_cache();
1265 }
1266
1267 static void do_invstub(int n)
1268 {
1269   literal_pool(20);
1270   u_int reglist=stubs[n].a;
1271   set_jump_target(stubs[n].addr, out);
1272   save_regs(reglist);
1273   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1274   emit_far_call(invalidate_addr);
1275   restore_regs(reglist);
1276   emit_jmp(stubs[n].retaddr); // return address
1277 }
1278
1279 // Add an entry to jump_out after making a link
1280 // src should point to code by emit_extjump2()
1281 void add_link(u_int vaddr,void *src)
1282 {
1283   u_int page=get_page(vaddr);
1284   inv_debug("add_link: %p -> %x (%d)\n",src,vaddr,page);
1285   check_extjump2(src);
1286   ll_add(jump_out+page,vaddr,src);
1287   //void *ptr=get_pointer(src);
1288   //inv_debug("add_link: Pointer is to %p\n",ptr);
1289 }
1290
1291 // If a code block was found to be unmodified (bit was set in
1292 // restore_candidate) and it remains unmodified (bit is clear
1293 // in invalid_code) then move the entries for that 4K page from
1294 // the dirty list to the clean list.
1295 void clean_blocks(u_int page)
1296 {
1297   struct ll_entry *head;
1298   inv_debug("INV: clean_blocks page=%d\n",page);
1299   head=jump_dirty[page];
1300   while(head!=NULL) {
1301     if(!invalid_code[head->vaddr>>12]) {
1302       // Don't restore blocks which are about to expire from the cache
1303       if (doesnt_expire_soon(head->addr)) {
1304         if(verify_dirty(head->addr)) {
1305           u_char *start, *end;
1306           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1307           u_int i;
1308           u_int inv=0;
1309           get_bounds(head->addr, &start, &end);
1310           if (start - rdram < RAM_SIZE) {
1311             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1312               inv|=invalid_code[i];
1313             }
1314           }
1315           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1316             inv=1;
1317           }
1318           if(!inv) {
1319             void *clean_addr = get_clean_addr(head->addr);
1320             if (doesnt_expire_soon(clean_addr)) {
1321               u_int ppage=page;
1322               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1323               //printf("page=%x, addr=%x\n",page,head->vaddr);
1324               //assert(head->vaddr>>12==(page|0x80000));
1325               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1326               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1327               if (ht_bin->vaddr[0] == head->vaddr)
1328                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1329               if (ht_bin->vaddr[1] == head->vaddr)
1330                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1331             }
1332           }
1333         }
1334       }
1335     }
1336     head=head->next;
1337   }
1338 }
1339
1340 /* Register allocation */
1341
1342 // Note: registers are allocated clean (unmodified state)
1343 // if you intend to modify the register, you must call dirty_reg().
1344 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1345 {
1346   int r,hr;
1347   int preferred_reg = (reg&7);
1348   if(reg==CCREG) preferred_reg=HOST_CCREG;
1349   if(reg==PTEMP||reg==FTEMP) preferred_reg=12;
1350
1351   // Don't allocate unused registers
1352   if((cur->u>>reg)&1) return;
1353
1354   // see if it's already allocated
1355   for(hr=0;hr<HOST_REGS;hr++)
1356   {
1357     if(cur->regmap[hr]==reg) return;
1358   }
1359
1360   // Keep the same mapping if the register was already allocated in a loop
1361   preferred_reg = loop_reg(i,reg,preferred_reg);
1362
1363   // Try to allocate the preferred register
1364   if(cur->regmap[preferred_reg]==-1) {
1365     cur->regmap[preferred_reg]=reg;
1366     cur->dirty&=~(1<<preferred_reg);
1367     cur->isconst&=~(1<<preferred_reg);
1368     return;
1369   }
1370   r=cur->regmap[preferred_reg];
1371   assert(r < 64);
1372   if((cur->u>>r)&1) {
1373     cur->regmap[preferred_reg]=reg;
1374     cur->dirty&=~(1<<preferred_reg);
1375     cur->isconst&=~(1<<preferred_reg);
1376     return;
1377   }
1378
1379   // Clear any unneeded registers
1380   // We try to keep the mapping consistent, if possible, because it
1381   // makes branches easier (especially loops).  So we try to allocate
1382   // first (see above) before removing old mappings.  If this is not
1383   // possible then go ahead and clear out the registers that are no
1384   // longer needed.
1385   for(hr=0;hr<HOST_REGS;hr++)
1386   {
1387     r=cur->regmap[hr];
1388     if(r>=0) {
1389       assert(r < 64);
1390       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1391     }
1392   }
1393   // Try to allocate any available register, but prefer
1394   // registers that have not been used recently.
1395   if(i>0) {
1396     for(hr=0;hr<HOST_REGS;hr++) {
1397       if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1398         if(regs[i-1].regmap[hr]!=rs1[i-1]&&regs[i-1].regmap[hr]!=rs2[i-1]&&regs[i-1].regmap[hr]!=rt1[i-1]&&regs[i-1].regmap[hr]!=rt2[i-1]) {
1399           cur->regmap[hr]=reg;
1400           cur->dirty&=~(1<<hr);
1401           cur->isconst&=~(1<<hr);
1402           return;
1403         }
1404       }
1405     }
1406   }
1407   // Try to allocate any available register
1408   for(hr=0;hr<HOST_REGS;hr++) {
1409     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1410       cur->regmap[hr]=reg;
1411       cur->dirty&=~(1<<hr);
1412       cur->isconst&=~(1<<hr);
1413       return;
1414     }
1415   }
1416
1417   // Ok, now we have to evict someone
1418   // Pick a register we hopefully won't need soon
1419   u_char hsn[MAXREG+1];
1420   memset(hsn,10,sizeof(hsn));
1421   int j;
1422   lsn(hsn,i,&preferred_reg);
1423   //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]);
1424   //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]);
1425   if(i>0) {
1426     // Don't evict the cycle count at entry points, otherwise the entry
1427     // stub will have to write it.
1428     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1429     if(i>1&&hsn[CCREG]>2&&(itype[i-2]==RJUMP||itype[i-2]==UJUMP||itype[i-2]==CJUMP||itype[i-2]==SJUMP)) hsn[CCREG]=2;
1430     for(j=10;j>=3;j--)
1431     {
1432       // Alloc preferred register if available
1433       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1434         for(hr=0;hr<HOST_REGS;hr++) {
1435           // Evict both parts of a 64-bit register
1436           if((cur->regmap[hr]&63)==r) {
1437             cur->regmap[hr]=-1;
1438             cur->dirty&=~(1<<hr);
1439             cur->isconst&=~(1<<hr);
1440           }
1441         }
1442         cur->regmap[preferred_reg]=reg;
1443         return;
1444       }
1445       for(r=1;r<=MAXREG;r++)
1446       {
1447         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1448           for(hr=0;hr<HOST_REGS;hr++) {
1449             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1450               if(cur->regmap[hr]==r) {
1451                 cur->regmap[hr]=reg;
1452                 cur->dirty&=~(1<<hr);
1453                 cur->isconst&=~(1<<hr);
1454                 return;
1455               }
1456             }
1457           }
1458         }
1459       }
1460     }
1461   }
1462   for(j=10;j>=0;j--)
1463   {
1464     for(r=1;r<=MAXREG;r++)
1465     {
1466       if(hsn[r]==j) {
1467         for(hr=0;hr<HOST_REGS;hr++) {
1468           if(cur->regmap[hr]==r) {
1469             cur->regmap[hr]=reg;
1470             cur->dirty&=~(1<<hr);
1471             cur->isconst&=~(1<<hr);
1472             return;
1473           }
1474         }
1475       }
1476     }
1477   }
1478   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1479 }
1480
1481 // Allocate a temporary register.  This is done without regard to
1482 // dirty status or whether the register we request is on the unneeded list
1483 // Note: This will only allocate one register, even if called multiple times
1484 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1485 {
1486   int r,hr;
1487   int preferred_reg = -1;
1488
1489   // see if it's already allocated
1490   for(hr=0;hr<HOST_REGS;hr++)
1491   {
1492     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1493   }
1494
1495   // Try to allocate any available register
1496   for(hr=HOST_REGS-1;hr>=0;hr--) {
1497     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1498       cur->regmap[hr]=reg;
1499       cur->dirty&=~(1<<hr);
1500       cur->isconst&=~(1<<hr);
1501       return;
1502     }
1503   }
1504
1505   // Find an unneeded register
1506   for(hr=HOST_REGS-1;hr>=0;hr--)
1507   {
1508     r=cur->regmap[hr];
1509     if(r>=0) {
1510       assert(r < 64);
1511       if((cur->u>>r)&1) {
1512         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1513           cur->regmap[hr]=reg;
1514           cur->dirty&=~(1<<hr);
1515           cur->isconst&=~(1<<hr);
1516           return;
1517         }
1518       }
1519     }
1520   }
1521
1522   // Ok, now we have to evict someone
1523   // Pick a register we hopefully won't need soon
1524   // TODO: we might want to follow unconditional jumps here
1525   // TODO: get rid of dupe code and make this into a function
1526   u_char hsn[MAXREG+1];
1527   memset(hsn,10,sizeof(hsn));
1528   int j;
1529   lsn(hsn,i,&preferred_reg);
1530   //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]);
1531   if(i>0) {
1532     // Don't evict the cycle count at entry points, otherwise the entry
1533     // stub will have to write it.
1534     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1535     if(i>1&&hsn[CCREG]>2&&(itype[i-2]==RJUMP||itype[i-2]==UJUMP||itype[i-2]==CJUMP||itype[i-2]==SJUMP)) hsn[CCREG]=2;
1536     for(j=10;j>=3;j--)
1537     {
1538       for(r=1;r<=MAXREG;r++)
1539       {
1540         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1541           for(hr=0;hr<HOST_REGS;hr++) {
1542             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1543               if(cur->regmap[hr]==r) {
1544                 cur->regmap[hr]=reg;
1545                 cur->dirty&=~(1<<hr);
1546                 cur->isconst&=~(1<<hr);
1547                 return;
1548               }
1549             }
1550           }
1551         }
1552       }
1553     }
1554   }
1555   for(j=10;j>=0;j--)
1556   {
1557     for(r=1;r<=MAXREG;r++)
1558     {
1559       if(hsn[r]==j) {
1560         for(hr=0;hr<HOST_REGS;hr++) {
1561           if(cur->regmap[hr]==r) {
1562             cur->regmap[hr]=reg;
1563             cur->dirty&=~(1<<hr);
1564             cur->isconst&=~(1<<hr);
1565             return;
1566           }
1567         }
1568       }
1569     }
1570   }
1571   SysPrintf("This shouldn't happen");abort();
1572 }
1573
1574 static void mov_alloc(struct regstat *current,int i)
1575 {
1576   // Note: Don't need to actually alloc the source registers
1577   //alloc_reg(current,i,rs1[i]);
1578   alloc_reg(current,i,rt1[i]);
1579
1580   clear_const(current,rs1[i]);
1581   clear_const(current,rt1[i]);
1582   dirty_reg(current,rt1[i]);
1583 }
1584
1585 static void shiftimm_alloc(struct regstat *current,int i)
1586 {
1587   if(opcode2[i]<=0x3) // SLL/SRL/SRA
1588   {
1589     if(rt1[i]) {
1590       if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1591       else lt1[i]=rs1[i];
1592       alloc_reg(current,i,rt1[i]);
1593       dirty_reg(current,rt1[i]);
1594       if(is_const(current,rs1[i])) {
1595         int v=get_const(current,rs1[i]);
1596         if(opcode2[i]==0x00) set_const(current,rt1[i],v<<imm[i]);
1597         if(opcode2[i]==0x02) set_const(current,rt1[i],(u_int)v>>imm[i]);
1598         if(opcode2[i]==0x03) set_const(current,rt1[i],v>>imm[i]);
1599       }
1600       else clear_const(current,rt1[i]);
1601     }
1602   }
1603   else
1604   {
1605     clear_const(current,rs1[i]);
1606     clear_const(current,rt1[i]);
1607   }
1608
1609   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
1610   {
1611     assert(0);
1612   }
1613   if(opcode2[i]==0x3c) // DSLL32
1614   {
1615     assert(0);
1616   }
1617   if(opcode2[i]==0x3e) // DSRL32
1618   {
1619     assert(0);
1620   }
1621   if(opcode2[i]==0x3f) // DSRA32
1622   {
1623     assert(0);
1624   }
1625 }
1626
1627 static void shift_alloc(struct regstat *current,int i)
1628 {
1629   if(rt1[i]) {
1630     if(opcode2[i]<=0x07) // SLLV/SRLV/SRAV
1631     {
1632       if(rs1[i]) alloc_reg(current,i,rs1[i]);
1633       if(rs2[i]) alloc_reg(current,i,rs2[i]);
1634       alloc_reg(current,i,rt1[i]);
1635       if(rt1[i]==rs2[i]) {
1636         alloc_reg_temp(current,i,-1);
1637         minimum_free_regs[i]=1;
1638       }
1639     } else { // DSLLV/DSRLV/DSRAV
1640       assert(0);
1641     }
1642     clear_const(current,rs1[i]);
1643     clear_const(current,rs2[i]);
1644     clear_const(current,rt1[i]);
1645     dirty_reg(current,rt1[i]);
1646   }
1647 }
1648
1649 static void alu_alloc(struct regstat *current,int i)
1650 {
1651   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
1652     if(rt1[i]) {
1653       if(rs1[i]&&rs2[i]) {
1654         alloc_reg(current,i,rs1[i]);
1655         alloc_reg(current,i,rs2[i]);
1656       }
1657       else {
1658         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1659         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1660       }
1661       alloc_reg(current,i,rt1[i]);
1662     }
1663   }
1664   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
1665     if(rt1[i]) {
1666       alloc_reg(current,i,rs1[i]);
1667       alloc_reg(current,i,rs2[i]);
1668       alloc_reg(current,i,rt1[i]);
1669     }
1670   }
1671   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
1672     if(rt1[i]) {
1673       if(rs1[i]&&rs2[i]) {
1674         alloc_reg(current,i,rs1[i]);
1675         alloc_reg(current,i,rs2[i]);
1676       }
1677       else
1678       {
1679         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1680         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1681       }
1682       alloc_reg(current,i,rt1[i]);
1683     }
1684   }
1685   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1686     assert(0);
1687   }
1688   clear_const(current,rs1[i]);
1689   clear_const(current,rs2[i]);
1690   clear_const(current,rt1[i]);
1691   dirty_reg(current,rt1[i]);
1692 }
1693
1694 static void imm16_alloc(struct regstat *current,int i)
1695 {
1696   if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1697   else lt1[i]=rs1[i];
1698   if(rt1[i]) alloc_reg(current,i,rt1[i]);
1699   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
1700     assert(0);
1701   }
1702   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
1703     clear_const(current,rs1[i]);
1704     clear_const(current,rt1[i]);
1705   }
1706   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
1707     if(is_const(current,rs1[i])) {
1708       int v=get_const(current,rs1[i]);
1709       if(opcode[i]==0x0c) set_const(current,rt1[i],v&imm[i]);
1710       if(opcode[i]==0x0d) set_const(current,rt1[i],v|imm[i]);
1711       if(opcode[i]==0x0e) set_const(current,rt1[i],v^imm[i]);
1712     }
1713     else clear_const(current,rt1[i]);
1714   }
1715   else if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
1716     if(is_const(current,rs1[i])) {
1717       int v=get_const(current,rs1[i]);
1718       set_const(current,rt1[i],v+imm[i]);
1719     }
1720     else clear_const(current,rt1[i]);
1721   }
1722   else {
1723     set_const(current,rt1[i],imm[i]<<16); // LUI
1724   }
1725   dirty_reg(current,rt1[i]);
1726 }
1727
1728 static void load_alloc(struct regstat *current,int i)
1729 {
1730   clear_const(current,rt1[i]);
1731   //if(rs1[i]!=rt1[i]&&needed_again(rs1[i],i)) clear_const(current,rs1[i]); // Does this help or hurt?
1732   if(!rs1[i]) current->u&=~1LL; // Allow allocating r0 if it's the source register
1733   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1734   if(rt1[i]&&!((current->u>>rt1[i])&1)) {
1735     alloc_reg(current,i,rt1[i]);
1736     assert(get_reg(current->regmap,rt1[i])>=0);
1737     if(opcode[i]==0x27||opcode[i]==0x37) // LWU/LD
1738     {
1739       assert(0);
1740     }
1741     else if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1742     {
1743       assert(0);
1744     }
1745     dirty_reg(current,rt1[i]);
1746     // LWL/LWR need a temporary register for the old value
1747     if(opcode[i]==0x22||opcode[i]==0x26)
1748     {
1749       alloc_reg(current,i,FTEMP);
1750       alloc_reg_temp(current,i,-1);
1751       minimum_free_regs[i]=1;
1752     }
1753   }
1754   else
1755   {
1756     // Load to r0 or unneeded register (dummy load)
1757     // but we still need a register to calculate the address
1758     if(opcode[i]==0x22||opcode[i]==0x26)
1759     {
1760       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1761     }
1762     alloc_reg_temp(current,i,-1);
1763     minimum_free_regs[i]=1;
1764     if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1765     {
1766       assert(0);
1767     }
1768   }
1769 }
1770
1771 void store_alloc(struct regstat *current,int i)
1772 {
1773   clear_const(current,rs2[i]);
1774   if(!(rs2[i])) current->u&=~1LL; // Allow allocating r0 if necessary
1775   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1776   alloc_reg(current,i,rs2[i]);
1777   if(opcode[i]==0x2c||opcode[i]==0x2d||opcode[i]==0x3f) { // 64-bit SDL/SDR/SD
1778     assert(0);
1779   }
1780   #if defined(HOST_IMM8)
1781   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1782   else alloc_reg(current,i,INVCP);
1783   #endif
1784   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) { // SWL/SWL/SDL/SDR
1785     alloc_reg(current,i,FTEMP);
1786   }
1787   // We need a temporary register for address generation
1788   alloc_reg_temp(current,i,-1);
1789   minimum_free_regs[i]=1;
1790 }
1791
1792 void c1ls_alloc(struct regstat *current,int i)
1793 {
1794   //clear_const(current,rs1[i]); // FIXME
1795   clear_const(current,rt1[i]);
1796   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1797   alloc_reg(current,i,CSREG); // Status
1798   alloc_reg(current,i,FTEMP);
1799   if(opcode[i]==0x35||opcode[i]==0x3d) { // 64-bit LDC1/SDC1
1800     assert(0);
1801   }
1802   #if defined(HOST_IMM8)
1803   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1804   else if((opcode[i]&0x3b)==0x39) // SWC1/SDC1
1805     alloc_reg(current,i,INVCP);
1806   #endif
1807   // We need a temporary register for address generation
1808   alloc_reg_temp(current,i,-1);
1809 }
1810
1811 void c2ls_alloc(struct regstat *current,int i)
1812 {
1813   clear_const(current,rt1[i]);
1814   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1815   alloc_reg(current,i,FTEMP);
1816   #if defined(HOST_IMM8)
1817   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1818   if((opcode[i]&0x3b)==0x3a) // SWC2/SDC2
1819     alloc_reg(current,i,INVCP);
1820   #endif
1821   // We need a temporary register for address generation
1822   alloc_reg_temp(current,i,-1);
1823   minimum_free_regs[i]=1;
1824 }
1825
1826 #ifndef multdiv_alloc
1827 void multdiv_alloc(struct regstat *current,int i)
1828 {
1829   //  case 0x18: MULT
1830   //  case 0x19: MULTU
1831   //  case 0x1A: DIV
1832   //  case 0x1B: DIVU
1833   //  case 0x1C: DMULT
1834   //  case 0x1D: DMULTU
1835   //  case 0x1E: DDIV
1836   //  case 0x1F: DDIVU
1837   clear_const(current,rs1[i]);
1838   clear_const(current,rs2[i]);
1839   if(rs1[i]&&rs2[i])
1840   {
1841     if((opcode2[i]&4)==0) // 32-bit
1842     {
1843       current->u&=~(1LL<<HIREG);
1844       current->u&=~(1LL<<LOREG);
1845       alloc_reg(current,i,HIREG);
1846       alloc_reg(current,i,LOREG);
1847       alloc_reg(current,i,rs1[i]);
1848       alloc_reg(current,i,rs2[i]);
1849       dirty_reg(current,HIREG);
1850       dirty_reg(current,LOREG);
1851     }
1852     else // 64-bit
1853     {
1854       assert(0);
1855     }
1856   }
1857   else
1858   {
1859     // Multiply by zero is zero.
1860     // MIPS does not have a divide by zero exception.
1861     // The result is undefined, we return zero.
1862     alloc_reg(current,i,HIREG);
1863     alloc_reg(current,i,LOREG);
1864     dirty_reg(current,HIREG);
1865     dirty_reg(current,LOREG);
1866   }
1867 }
1868 #endif
1869
1870 void cop0_alloc(struct regstat *current,int i)
1871 {
1872   if(opcode2[i]==0) // MFC0
1873   {
1874     if(rt1[i]) {
1875       clear_const(current,rt1[i]);
1876       alloc_all(current,i);
1877       alloc_reg(current,i,rt1[i]);
1878       dirty_reg(current,rt1[i]);
1879     }
1880   }
1881   else if(opcode2[i]==4) // MTC0
1882   {
1883     if(rs1[i]){
1884       clear_const(current,rs1[i]);
1885       alloc_reg(current,i,rs1[i]);
1886       alloc_all(current,i);
1887     }
1888     else {
1889       alloc_all(current,i); // FIXME: Keep r0
1890       current->u&=~1LL;
1891       alloc_reg(current,i,0);
1892     }
1893   }
1894   else
1895   {
1896     // TLBR/TLBWI/TLBWR/TLBP/ERET
1897     assert(opcode2[i]==0x10);
1898     alloc_all(current,i);
1899   }
1900   minimum_free_regs[i]=HOST_REGS;
1901 }
1902
1903 static void cop12_alloc(struct regstat *current,int i)
1904 {
1905   alloc_reg(current,i,CSREG); // Load status
1906   if(opcode2[i]<3) // MFC1/CFC1
1907   {
1908     if(rt1[i]){
1909       clear_const(current,rt1[i]);
1910       alloc_reg(current,i,rt1[i]);
1911       dirty_reg(current,rt1[i]);
1912     }
1913     alloc_reg_temp(current,i,-1);
1914   }
1915   else if(opcode2[i]>3) // MTC1/CTC1
1916   {
1917     if(rs1[i]){
1918       clear_const(current,rs1[i]);
1919       alloc_reg(current,i,rs1[i]);
1920     }
1921     else {
1922       current->u&=~1LL;
1923       alloc_reg(current,i,0);
1924     }
1925     alloc_reg_temp(current,i,-1);
1926   }
1927   minimum_free_regs[i]=1;
1928 }
1929
1930 void c2op_alloc(struct regstat *current,int i)
1931 {
1932   alloc_reg_temp(current,i,-1);
1933 }
1934
1935 void syscall_alloc(struct regstat *current,int i)
1936 {
1937   alloc_cc(current,i);
1938   dirty_reg(current,CCREG);
1939   alloc_all(current,i);
1940   minimum_free_regs[i]=HOST_REGS;
1941   current->isconst=0;
1942 }
1943
1944 void delayslot_alloc(struct regstat *current,int i)
1945 {
1946   switch(itype[i]) {
1947     case UJUMP:
1948     case CJUMP:
1949     case SJUMP:
1950     case RJUMP:
1951     case SYSCALL:
1952     case HLECALL:
1953     case SPAN:
1954       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
1955       SysPrintf("Disabled speculative precompilation\n");
1956       stop_after_jal=1;
1957       break;
1958     case IMM16:
1959       imm16_alloc(current,i);
1960       break;
1961     case LOAD:
1962     case LOADLR:
1963       load_alloc(current,i);
1964       break;
1965     case STORE:
1966     case STORELR:
1967       store_alloc(current,i);
1968       break;
1969     case ALU:
1970       alu_alloc(current,i);
1971       break;
1972     case SHIFT:
1973       shift_alloc(current,i);
1974       break;
1975     case MULTDIV:
1976       multdiv_alloc(current,i);
1977       break;
1978     case SHIFTIMM:
1979       shiftimm_alloc(current,i);
1980       break;
1981     case MOV:
1982       mov_alloc(current,i);
1983       break;
1984     case COP0:
1985       cop0_alloc(current,i);
1986       break;
1987     case COP1:
1988     case COP2:
1989       cop12_alloc(current,i);
1990       break;
1991     case C1LS:
1992       c1ls_alloc(current,i);
1993       break;
1994     case C2LS:
1995       c2ls_alloc(current,i);
1996       break;
1997     case C2OP:
1998       c2op_alloc(current,i);
1999       break;
2000   }
2001 }
2002
2003 // Special case where a branch and delay slot span two pages in virtual memory
2004 static void pagespan_alloc(struct regstat *current,int i)
2005 {
2006   current->isconst=0;
2007   current->wasconst=0;
2008   regs[i].wasconst=0;
2009   minimum_free_regs[i]=HOST_REGS;
2010   alloc_all(current,i);
2011   alloc_cc(current,i);
2012   dirty_reg(current,CCREG);
2013   if(opcode[i]==3) // JAL
2014   {
2015     alloc_reg(current,i,31);
2016     dirty_reg(current,31);
2017   }
2018   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
2019   {
2020     alloc_reg(current,i,rs1[i]);
2021     if (rt1[i]!=0) {
2022       alloc_reg(current,i,rt1[i]);
2023       dirty_reg(current,rt1[i]);
2024     }
2025   }
2026   if((opcode[i]&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2027   {
2028     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2029     if(rs2[i]) alloc_reg(current,i,rs2[i]);
2030   }
2031   else
2032   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2033   {
2034     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2035   }
2036   //else ...
2037 }
2038
2039 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2040   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2041 {
2042   assert(stubcount < ARRAY_SIZE(stubs));
2043   stubs[stubcount].type = type;
2044   stubs[stubcount].addr = addr;
2045   stubs[stubcount].retaddr = retaddr;
2046   stubs[stubcount].a = a;
2047   stubs[stubcount].b = b;
2048   stubs[stubcount].c = c;
2049   stubs[stubcount].d = d;
2050   stubs[stubcount].e = e;
2051   stubcount++;
2052 }
2053
2054 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2055   int i, int addr_reg, struct regstat *i_regs, int ccadj, u_int reglist)
2056 {
2057   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2058 }
2059
2060 // Write out a single register
2061 static void wb_register(signed char r,signed char regmap[],uint64_t dirty)
2062 {
2063   int hr;
2064   for(hr=0;hr<HOST_REGS;hr++) {
2065     if(hr!=EXCLUDE_REG) {
2066       if((regmap[hr]&63)==r) {
2067         if((dirty>>hr)&1) {
2068           assert(regmap[hr]<64);
2069           emit_storereg(r,hr);
2070         }
2071       }
2072     }
2073   }
2074 }
2075
2076 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2077 {
2078   //if(dirty_pre==dirty) return;
2079   int hr,reg;
2080   for(hr=0;hr<HOST_REGS;hr++) {
2081     if(hr!=EXCLUDE_REG) {
2082       reg=pre[hr];
2083       if(((~u)>>(reg&63))&1) {
2084         if(reg>0) {
2085           if(((dirty_pre&~dirty)>>hr)&1) {
2086             if(reg>0&&reg<34) {
2087               emit_storereg(reg,hr);
2088             }
2089             else if(reg>=64) {
2090               assert(0);
2091             }
2092           }
2093         }
2094       }
2095     }
2096   }
2097 }
2098
2099 // trashes r2
2100 static void pass_args(int a0, int a1)
2101 {
2102   if(a0==1&&a1==0) {
2103     // must swap
2104     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2105   }
2106   else if(a0!=0&&a1==0) {
2107     emit_mov(a1,1);
2108     if (a0>=0) emit_mov(a0,0);
2109   }
2110   else {
2111     if(a0>=0&&a0!=0) emit_mov(a0,0);
2112     if(a1>=0&&a1!=1) emit_mov(a1,1);
2113   }
2114 }
2115
2116 static void alu_assemble(int i,struct regstat *i_regs)
2117 {
2118   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
2119     if(rt1[i]) {
2120       signed char s1,s2,t;
2121       t=get_reg(i_regs->regmap,rt1[i]);
2122       if(t>=0) {
2123         s1=get_reg(i_regs->regmap,rs1[i]);
2124         s2=get_reg(i_regs->regmap,rs2[i]);
2125         if(rs1[i]&&rs2[i]) {
2126           assert(s1>=0);
2127           assert(s2>=0);
2128           if(opcode2[i]&2) emit_sub(s1,s2,t);
2129           else emit_add(s1,s2,t);
2130         }
2131         else if(rs1[i]) {
2132           if(s1>=0) emit_mov(s1,t);
2133           else emit_loadreg(rs1[i],t);
2134         }
2135         else if(rs2[i]) {
2136           if(s2>=0) {
2137             if(opcode2[i]&2) emit_neg(s2,t);
2138             else emit_mov(s2,t);
2139           }
2140           else {
2141             emit_loadreg(rs2[i],t);
2142             if(opcode2[i]&2) emit_neg(t,t);
2143           }
2144         }
2145         else emit_zeroreg(t);
2146       }
2147     }
2148   }
2149   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2150     assert(0);
2151   }
2152   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
2153     if(rt1[i]) {
2154       signed char s1l,s2l,t;
2155       {
2156         t=get_reg(i_regs->regmap,rt1[i]);
2157         //assert(t>=0);
2158         if(t>=0) {
2159           s1l=get_reg(i_regs->regmap,rs1[i]);
2160           s2l=get_reg(i_regs->regmap,rs2[i]);
2161           if(rs2[i]==0) // rx<r0
2162           {
2163             if(opcode2[i]==0x2a&&rs1[i]!=0) { // SLT
2164               assert(s1l>=0);
2165               emit_shrimm(s1l,31,t);
2166             }
2167             else // SLTU (unsigned can not be less than zero, 0<0)
2168               emit_zeroreg(t);
2169           }
2170           else if(rs1[i]==0) // r0<rx
2171           {
2172             assert(s2l>=0);
2173             if(opcode2[i]==0x2a) // SLT
2174               emit_set_gz32(s2l,t);
2175             else // SLTU (set if not zero)
2176               emit_set_nz32(s2l,t);
2177           }
2178           else{
2179             assert(s1l>=0);assert(s2l>=0);
2180             if(opcode2[i]==0x2a) // SLT
2181               emit_set_if_less32(s1l,s2l,t);
2182             else // SLTU
2183               emit_set_if_carry32(s1l,s2l,t);
2184           }
2185         }
2186       }
2187     }
2188   }
2189   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
2190     if(rt1[i]) {
2191       signed char s1l,s2l,tl;
2192       tl=get_reg(i_regs->regmap,rt1[i]);
2193       {
2194         if(tl>=0) {
2195           s1l=get_reg(i_regs->regmap,rs1[i]);
2196           s2l=get_reg(i_regs->regmap,rs2[i]);
2197           if(rs1[i]&&rs2[i]) {
2198             assert(s1l>=0);
2199             assert(s2l>=0);
2200             if(opcode2[i]==0x24) { // AND
2201               emit_and(s1l,s2l,tl);
2202             } else
2203             if(opcode2[i]==0x25) { // OR
2204               emit_or(s1l,s2l,tl);
2205             } else
2206             if(opcode2[i]==0x26) { // XOR
2207               emit_xor(s1l,s2l,tl);
2208             } else
2209             if(opcode2[i]==0x27) { // NOR
2210               emit_or(s1l,s2l,tl);
2211               emit_not(tl,tl);
2212             }
2213           }
2214           else
2215           {
2216             if(opcode2[i]==0x24) { // AND
2217               emit_zeroreg(tl);
2218             } else
2219             if(opcode2[i]==0x25||opcode2[i]==0x26) { // OR/XOR
2220               if(rs1[i]){
2221                 if(s1l>=0) emit_mov(s1l,tl);
2222                 else emit_loadreg(rs1[i],tl); // CHECK: regmap_entry?
2223               }
2224               else
2225               if(rs2[i]){
2226                 if(s2l>=0) emit_mov(s2l,tl);
2227                 else emit_loadreg(rs2[i],tl); // CHECK: regmap_entry?
2228               }
2229               else emit_zeroreg(tl);
2230             } else
2231             if(opcode2[i]==0x27) { // NOR
2232               if(rs1[i]){
2233                 if(s1l>=0) emit_not(s1l,tl);
2234                 else {
2235                   emit_loadreg(rs1[i],tl);
2236                   emit_not(tl,tl);
2237                 }
2238               }
2239               else
2240               if(rs2[i]){
2241                 if(s2l>=0) emit_not(s2l,tl);
2242                 else {
2243                   emit_loadreg(rs2[i],tl);
2244                   emit_not(tl,tl);
2245                 }
2246               }
2247               else emit_movimm(-1,tl);
2248             }
2249           }
2250         }
2251       }
2252     }
2253   }
2254 }
2255
2256 void imm16_assemble(int i,struct regstat *i_regs)
2257 {
2258   if (opcode[i]==0x0f) { // LUI
2259     if(rt1[i]) {
2260       signed char t;
2261       t=get_reg(i_regs->regmap,rt1[i]);
2262       //assert(t>=0);
2263       if(t>=0) {
2264         if(!((i_regs->isconst>>t)&1))
2265           emit_movimm(imm[i]<<16,t);
2266       }
2267     }
2268   }
2269   if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
2270     if(rt1[i]) {
2271       signed char s,t;
2272       t=get_reg(i_regs->regmap,rt1[i]);
2273       s=get_reg(i_regs->regmap,rs1[i]);
2274       if(rs1[i]) {
2275         //assert(t>=0);
2276         //assert(s>=0);
2277         if(t>=0) {
2278           if(!((i_regs->isconst>>t)&1)) {
2279             if(s<0) {
2280               if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2281               emit_addimm(t,imm[i],t);
2282             }else{
2283               if(!((i_regs->wasconst>>s)&1))
2284                 emit_addimm(s,imm[i],t);
2285               else
2286                 emit_movimm(constmap[i][s]+imm[i],t);
2287             }
2288           }
2289         }
2290       } else {
2291         if(t>=0) {
2292           if(!((i_regs->isconst>>t)&1))
2293             emit_movimm(imm[i],t);
2294         }
2295       }
2296     }
2297   }
2298   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
2299     if(rt1[i]) {
2300       signed char sl,tl;
2301       tl=get_reg(i_regs->regmap,rt1[i]);
2302       sl=get_reg(i_regs->regmap,rs1[i]);
2303       if(tl>=0) {
2304         if(rs1[i]) {
2305           assert(sl>=0);
2306           emit_addimm(sl,imm[i],tl);
2307         } else {
2308           emit_movimm(imm[i],tl);
2309         }
2310       }
2311     }
2312   }
2313   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
2314     if(rt1[i]) {
2315       //assert(rs1[i]!=0); // r0 might be valid, but it's probably a bug
2316       signed char sl,t;
2317       t=get_reg(i_regs->regmap,rt1[i]);
2318       sl=get_reg(i_regs->regmap,rs1[i]);
2319       //assert(t>=0);
2320       if(t>=0) {
2321         if(rs1[i]>0) {
2322             if(opcode[i]==0x0a) { // SLTI
2323               if(sl<0) {
2324                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2325                 emit_slti32(t,imm[i],t);
2326               }else{
2327                 emit_slti32(sl,imm[i],t);
2328               }
2329             }
2330             else { // SLTIU
2331               if(sl<0) {
2332                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2333                 emit_sltiu32(t,imm[i],t);
2334               }else{
2335                 emit_sltiu32(sl,imm[i],t);
2336               }
2337             }
2338         }else{
2339           // SLTI(U) with r0 is just stupid,
2340           // nonetheless examples can be found
2341           if(opcode[i]==0x0a) // SLTI
2342             if(0<imm[i]) emit_movimm(1,t);
2343             else emit_zeroreg(t);
2344           else // SLTIU
2345           {
2346             if(imm[i]) emit_movimm(1,t);
2347             else emit_zeroreg(t);
2348           }
2349         }
2350       }
2351     }
2352   }
2353   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
2354     if(rt1[i]) {
2355       signed char sl,tl;
2356       tl=get_reg(i_regs->regmap,rt1[i]);
2357       sl=get_reg(i_regs->regmap,rs1[i]);
2358       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2359         if(opcode[i]==0x0c) //ANDI
2360         {
2361           if(rs1[i]) {
2362             if(sl<0) {
2363               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2364               emit_andimm(tl,imm[i],tl);
2365             }else{
2366               if(!((i_regs->wasconst>>sl)&1))
2367                 emit_andimm(sl,imm[i],tl);
2368               else
2369                 emit_movimm(constmap[i][sl]&imm[i],tl);
2370             }
2371           }
2372           else
2373             emit_zeroreg(tl);
2374         }
2375         else
2376         {
2377           if(rs1[i]) {
2378             if(sl<0) {
2379               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2380             }
2381             if(opcode[i]==0x0d) { // ORI
2382               if(sl<0) {
2383                 emit_orimm(tl,imm[i],tl);
2384               }else{
2385                 if(!((i_regs->wasconst>>sl)&1))
2386                   emit_orimm(sl,imm[i],tl);
2387                 else
2388                   emit_movimm(constmap[i][sl]|imm[i],tl);
2389               }
2390             }
2391             if(opcode[i]==0x0e) { // XORI
2392               if(sl<0) {
2393                 emit_xorimm(tl,imm[i],tl);
2394               }else{
2395                 if(!((i_regs->wasconst>>sl)&1))
2396                   emit_xorimm(sl,imm[i],tl);
2397                 else
2398                   emit_movimm(constmap[i][sl]^imm[i],tl);
2399               }
2400             }
2401           }
2402           else {
2403             emit_movimm(imm[i],tl);
2404           }
2405         }
2406       }
2407     }
2408   }
2409 }
2410
2411 void shiftimm_assemble(int i,struct regstat *i_regs)
2412 {
2413   if(opcode2[i]<=0x3) // SLL/SRL/SRA
2414   {
2415     if(rt1[i]) {
2416       signed char s,t;
2417       t=get_reg(i_regs->regmap,rt1[i]);
2418       s=get_reg(i_regs->regmap,rs1[i]);
2419       //assert(t>=0);
2420       if(t>=0&&!((i_regs->isconst>>t)&1)){
2421         if(rs1[i]==0)
2422         {
2423           emit_zeroreg(t);
2424         }
2425         else
2426         {
2427           if(s<0&&i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2428           if(imm[i]) {
2429             if(opcode2[i]==0) // SLL
2430             {
2431               emit_shlimm(s<0?t:s,imm[i],t);
2432             }
2433             if(opcode2[i]==2) // SRL
2434             {
2435               emit_shrimm(s<0?t:s,imm[i],t);
2436             }
2437             if(opcode2[i]==3) // SRA
2438             {
2439               emit_sarimm(s<0?t:s,imm[i],t);
2440             }
2441           }else{
2442             // Shift by zero
2443             if(s>=0 && s!=t) emit_mov(s,t);
2444           }
2445         }
2446       }
2447       //emit_storereg(rt1[i],t); //DEBUG
2448     }
2449   }
2450   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
2451   {
2452     assert(0);
2453   }
2454   if(opcode2[i]==0x3c) // DSLL32
2455   {
2456     assert(0);
2457   }
2458   if(opcode2[i]==0x3e) // DSRL32
2459   {
2460     assert(0);
2461   }
2462   if(opcode2[i]==0x3f) // DSRA32
2463   {
2464     assert(0);
2465   }
2466 }
2467
2468 #ifndef shift_assemble
2469 static void shift_assemble(int i,struct regstat *i_regs)
2470 {
2471   signed char s,t,shift;
2472   if (rt1[i] == 0)
2473     return;
2474   assert(opcode2[i]<=0x07); // SLLV/SRLV/SRAV
2475   t = get_reg(i_regs->regmap, rt1[i]);
2476   s = get_reg(i_regs->regmap, rs1[i]);
2477   shift = get_reg(i_regs->regmap, rs2[i]);
2478   if (t < 0)
2479     return;
2480
2481   if(rs1[i]==0)
2482     emit_zeroreg(t);
2483   else if(rs2[i]==0) {
2484     assert(s>=0);
2485     if(s!=t) emit_mov(s,t);
2486   }
2487   else {
2488     host_tempreg_acquire();
2489     emit_andimm(shift,31,HOST_TEMPREG);
2490     switch(opcode2[i]) {
2491     case 4: // SLLV
2492       emit_shl(s,HOST_TEMPREG,t);
2493       break;
2494     case 6: // SRLV
2495       emit_shr(s,HOST_TEMPREG,t);
2496       break;
2497     case 7: // SRAV
2498       emit_sar(s,HOST_TEMPREG,t);
2499       break;
2500     default:
2501       assert(0);
2502     }
2503     host_tempreg_release();
2504   }
2505 }
2506
2507 #endif
2508
2509 enum {
2510   MTYPE_8000 = 0,
2511   MTYPE_8020,
2512   MTYPE_0000,
2513   MTYPE_A000,
2514   MTYPE_1F80,
2515 };
2516
2517 static int get_ptr_mem_type(u_int a)
2518 {
2519   if(a < 0x00200000) {
2520     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2521       // return wrong, must use memhandler for BIOS self-test to pass
2522       // 007 does similar stuff from a00 mirror, weird stuff
2523       return MTYPE_8000;
2524     return MTYPE_0000;
2525   }
2526   if(0x1f800000 <= a && a < 0x1f801000)
2527     return MTYPE_1F80;
2528   if(0x80200000 <= a && a < 0x80800000)
2529     return MTYPE_8020;
2530   if(0xa0000000 <= a && a < 0xa0200000)
2531     return MTYPE_A000;
2532   return MTYPE_8000;
2533 }
2534
2535 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override)
2536 {
2537   void *jaddr = NULL;
2538   int type=0;
2539   int mr=rs1[i];
2540   if(((smrv_strong|smrv_weak)>>mr)&1) {
2541     type=get_ptr_mem_type(smrv[mr]);
2542     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2543   }
2544   else {
2545     // use the mirror we are running on
2546     type=get_ptr_mem_type(start);
2547     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2548   }
2549
2550   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2551     host_tempreg_acquire();
2552     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2553     addr=*addr_reg_override=HOST_TEMPREG;
2554     type=0;
2555   }
2556   else if(type==MTYPE_0000) { // RAM 0 mirror
2557     host_tempreg_acquire();
2558     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2559     addr=*addr_reg_override=HOST_TEMPREG;
2560     type=0;
2561   }
2562   else if(type==MTYPE_A000) { // RAM A mirror
2563     host_tempreg_acquire();
2564     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2565     addr=*addr_reg_override=HOST_TEMPREG;
2566     type=0;
2567   }
2568   else if(type==MTYPE_1F80) { // scratchpad
2569     if (psxH == (void *)0x1f800000) {
2570       host_tempreg_acquire();
2571       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2572       emit_cmpimm(HOST_TEMPREG,0x1000);
2573       host_tempreg_release();
2574       jaddr=out;
2575       emit_jc(0);
2576     }
2577     else {
2578       // do the usual RAM check, jump will go to the right handler
2579       type=0;
2580     }
2581   }
2582
2583   if(type==0)
2584   {
2585     emit_cmpimm(addr,RAM_SIZE);
2586     jaddr=out;
2587     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2588     // Hint to branch predictor that the branch is unlikely to be taken
2589     if(rs1[i]>=28)
2590       emit_jno_unlikely(0);
2591     else
2592     #endif
2593       emit_jno(0);
2594     if(ram_offset!=0) {
2595       host_tempreg_acquire();
2596       emit_addimm(addr,ram_offset,HOST_TEMPREG);
2597       addr=*addr_reg_override=HOST_TEMPREG;
2598     }
2599   }
2600
2601   return jaddr;
2602 }
2603
2604 // return memhandler, or get directly accessable address and return 0
2605 static void *get_direct_memhandler(void *table, u_int addr,
2606   enum stub_type type, uintptr_t *addr_host)
2607 {
2608   uintptr_t l1, l2 = 0;
2609   l1 = ((uintptr_t *)table)[addr>>12];
2610   if ((l1 & (1ul << (sizeof(l1)*8-1))) == 0) {
2611     uintptr_t v = l1 << 1;
2612     *addr_host = v + addr;
2613     return NULL;
2614   }
2615   else {
2616     l1 <<= 1;
2617     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2618       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2619     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2620       l2=((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2621     else
2622       l2=((uintptr_t *)l1)[(addr&0xfff)/4];
2623     if ((l2 & (1<<31)) == 0) {
2624       uintptr_t v = l2 << 1;
2625       *addr_host = v + (addr&0xfff);
2626       return NULL;
2627     }
2628     return (void *)(l2 << 1);
2629   }
2630 }
2631
2632 static void load_assemble(int i,struct regstat *i_regs)
2633 {
2634   int s,tl,addr;
2635   int offset;
2636   void *jaddr=0;
2637   int memtarget=0,c=0;
2638   int fastio_reg_override=-1;
2639   u_int hr,reglist=0;
2640   tl=get_reg(i_regs->regmap,rt1[i]);
2641   s=get_reg(i_regs->regmap,rs1[i]);
2642   offset=imm[i];
2643   for(hr=0;hr<HOST_REGS;hr++) {
2644     if(i_regs->regmap[hr]>=0) reglist|=1<<hr;
2645   }
2646   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2647   if(s>=0) {
2648     c=(i_regs->wasconst>>s)&1;
2649     if (c) {
2650       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2651     }
2652   }
2653   //printf("load_assemble: c=%d\n",c);
2654   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2655   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2656   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2657     ||rt1[i]==0) {
2658       // could be FIFO, must perform the read
2659       // ||dummy read
2660       assem_debug("(forced read)\n");
2661       tl=get_reg(i_regs->regmap,-1);
2662       assert(tl>=0);
2663   }
2664   if(offset||s<0||c) addr=tl;
2665   else addr=s;
2666   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2667  if(tl>=0) {
2668   //printf("load_assemble: c=%d\n",c);
2669   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2670   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2671   reglist&=~(1<<tl);
2672   if(!c) {
2673     #ifdef R29_HACK
2674     // Strmnnrmn's speed hack
2675     if(rs1[i]!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2676     #endif
2677     {
2678       jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2679     }
2680   }
2681   else if(ram_offset&&memtarget) {
2682     host_tempreg_acquire();
2683     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2684     fastio_reg_override=HOST_TEMPREG;
2685   }
2686   int dummy=(rt1[i]==0)||(tl!=get_reg(i_regs->regmap,rt1[i])); // ignore loads to r0 and unneeded reg
2687   if (opcode[i]==0x20) { // LB
2688     if(!c||memtarget) {
2689       if(!dummy) {
2690         {
2691           int x=0,a=tl;
2692           if(!c) a=addr;
2693           if(fastio_reg_override>=0) a=fastio_reg_override;
2694
2695           emit_movsbl_indexed(x,a,tl);
2696         }
2697       }
2698       if(jaddr)
2699         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2700     }
2701     else
2702       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2703   }
2704   if (opcode[i]==0x21) { // LH
2705     if(!c||memtarget) {
2706       if(!dummy) {
2707         int x=0,a=tl;
2708         if(!c) a=addr;
2709         if(fastio_reg_override>=0) a=fastio_reg_override;
2710         emit_movswl_indexed(x,a,tl);
2711       }
2712       if(jaddr)
2713         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2714     }
2715     else
2716       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2717   }
2718   if (opcode[i]==0x23) { // LW
2719     if(!c||memtarget) {
2720       if(!dummy) {
2721         int a=addr;
2722         if(fastio_reg_override>=0) a=fastio_reg_override;
2723         emit_readword_indexed(0,a,tl);
2724       }
2725       if(jaddr)
2726         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2727     }
2728     else
2729       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2730   }
2731   if (opcode[i]==0x24) { // LBU
2732     if(!c||memtarget) {
2733       if(!dummy) {
2734         int x=0,a=tl;
2735         if(!c) a=addr;
2736         if(fastio_reg_override>=0) a=fastio_reg_override;
2737
2738         emit_movzbl_indexed(x,a,tl);
2739       }
2740       if(jaddr)
2741         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2742     }
2743     else
2744       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2745   }
2746   if (opcode[i]==0x25) { // LHU
2747     if(!c||memtarget) {
2748       if(!dummy) {
2749         int x=0,a=tl;
2750         if(!c) a=addr;
2751         if(fastio_reg_override>=0) a=fastio_reg_override;
2752         emit_movzwl_indexed(x,a,tl);
2753       }
2754       if(jaddr)
2755         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2756     }
2757     else
2758       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2759   }
2760   if (opcode[i]==0x27) { // LWU
2761     assert(0);
2762   }
2763   if (opcode[i]==0x37) { // LD
2764     assert(0);
2765   }
2766  }
2767  if (fastio_reg_override == HOST_TEMPREG)
2768    host_tempreg_release();
2769 }
2770
2771 #ifndef loadlr_assemble
2772 static void loadlr_assemble(int i,struct regstat *i_regs)
2773 {
2774   int s,tl,temp,temp2,addr;
2775   int offset;
2776   void *jaddr=0;
2777   int memtarget=0,c=0;
2778   int fastio_reg_override=-1;
2779   u_int hr,reglist=0;
2780   tl=get_reg(i_regs->regmap,rt1[i]);
2781   s=get_reg(i_regs->regmap,rs1[i]);
2782   temp=get_reg(i_regs->regmap,-1);
2783   temp2=get_reg(i_regs->regmap,FTEMP);
2784   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2785   assert(addr<0);
2786   offset=imm[i];
2787   for(hr=0;hr<HOST_REGS;hr++) {
2788     if(i_regs->regmap[hr]>=0) reglist|=1<<hr;
2789   }
2790   reglist|=1<<temp;
2791   if(offset||s<0||c) addr=temp2;
2792   else addr=s;
2793   if(s>=0) {
2794     c=(i_regs->wasconst>>s)&1;
2795     if(c) {
2796       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2797     }
2798   }
2799   if(!c) {
2800     emit_shlimm(addr,3,temp);
2801     if (opcode[i]==0x22||opcode[i]==0x26) {
2802       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2803     }else{
2804       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2805     }
2806     jaddr=emit_fastpath_cmp_jump(i,temp2,&fastio_reg_override);
2807   }
2808   else {
2809     if(ram_offset&&memtarget) {
2810       host_tempreg_acquire();
2811       emit_addimm(temp2,ram_offset,HOST_TEMPREG);
2812       fastio_reg_override=HOST_TEMPREG;
2813     }
2814     if (opcode[i]==0x22||opcode[i]==0x26) {
2815       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2816     }else{
2817       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2818     }
2819   }
2820   if (opcode[i]==0x22||opcode[i]==0x26) { // LWL/LWR
2821     if(!c||memtarget) {
2822       int a=temp2;
2823       if(fastio_reg_override>=0) a=fastio_reg_override;
2824       emit_readword_indexed(0,a,temp2);
2825       if(fastio_reg_override==HOST_TEMPREG) host_tempreg_release();
2826       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj[i],reglist);
2827     }
2828     else
2829       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj[i],reglist);
2830     if(rt1[i]) {
2831       assert(tl>=0);
2832       emit_andimm(temp,24,temp);
2833       if (opcode[i]==0x22) // LWL
2834         emit_xorimm(temp,24,temp);
2835       host_tempreg_acquire();
2836       emit_movimm(-1,HOST_TEMPREG);
2837       if (opcode[i]==0x26) {
2838         emit_shr(temp2,temp,temp2);
2839         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2840       }else{
2841         emit_shl(temp2,temp,temp2);
2842         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2843       }
2844       host_tempreg_release();
2845       emit_or(temp2,tl,tl);
2846     }
2847     //emit_storereg(rt1[i],tl); // DEBUG
2848   }
2849   if (opcode[i]==0x1A||opcode[i]==0x1B) { // LDL/LDR
2850     assert(0);
2851   }
2852 }
2853 #endif
2854
2855 void store_assemble(int i,struct regstat *i_regs)
2856 {
2857   int s,tl;
2858   int addr,temp;
2859   int offset;
2860   void *jaddr=0;
2861   enum stub_type type;
2862   int memtarget=0,c=0;
2863   int agr=AGEN1+(i&1);
2864   int fastio_reg_override=-1;
2865   u_int hr,reglist=0;
2866   tl=get_reg(i_regs->regmap,rs2[i]);
2867   s=get_reg(i_regs->regmap,rs1[i]);
2868   temp=get_reg(i_regs->regmap,agr);
2869   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2870   offset=imm[i];
2871   if(s>=0) {
2872     c=(i_regs->wasconst>>s)&1;
2873     if(c) {
2874       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2875     }
2876   }
2877   assert(tl>=0);
2878   assert(temp>=0);
2879   for(hr=0;hr<HOST_REGS;hr++) {
2880     if(i_regs->regmap[hr]>=0) reglist|=1<<hr;
2881   }
2882   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2883   if(offset||s<0||c) addr=temp;
2884   else addr=s;
2885   if(!c) {
2886     jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2887   }
2888   else if(ram_offset&&memtarget) {
2889     host_tempreg_acquire();
2890     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2891     fastio_reg_override=HOST_TEMPREG;
2892   }
2893
2894   if (opcode[i]==0x28) { // SB
2895     if(!c||memtarget) {
2896       int x=0,a=temp;
2897       if(!c) a=addr;
2898       if(fastio_reg_override>=0) a=fastio_reg_override;
2899       emit_writebyte_indexed(tl,x,a);
2900     }
2901     type=STOREB_STUB;
2902   }
2903   if (opcode[i]==0x29) { // SH
2904     if(!c||memtarget) {
2905       int x=0,a=temp;
2906       if(!c) a=addr;
2907       if(fastio_reg_override>=0) a=fastio_reg_override;
2908       emit_writehword_indexed(tl,x,a);
2909     }
2910     type=STOREH_STUB;
2911   }
2912   if (opcode[i]==0x2B) { // SW
2913     if(!c||memtarget) {
2914       int a=addr;
2915       if(fastio_reg_override>=0) a=fastio_reg_override;
2916       emit_writeword_indexed(tl,0,a);
2917     }
2918     type=STOREW_STUB;
2919   }
2920   if (opcode[i]==0x3F) { // SD
2921     assert(0);
2922     type=STORED_STUB;
2923   }
2924   if(fastio_reg_override==HOST_TEMPREG)
2925     host_tempreg_release();
2926   if(jaddr) {
2927     // PCSX store handlers don't check invcode again
2928     reglist|=1<<addr;
2929     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2930     jaddr=0;
2931   }
2932   if(!(i_regs->waswritten&(1<<rs1[i]))&&!(new_dynarec_hacks&NDHACK_NO_SMC_CHECK)) {
2933     if(!c||memtarget) {
2934       #ifdef DESTRUCTIVE_SHIFT
2935       // The x86 shift operation is 'destructive'; it overwrites the
2936       // source register, so we need to make a copy first and use that.
2937       addr=temp;
2938       #endif
2939       #if defined(HOST_IMM8)
2940       int ir=get_reg(i_regs->regmap,INVCP);
2941       assert(ir>=0);
2942       emit_cmpmem_indexedsr12_reg(ir,addr,1);
2943       #else
2944       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
2945       #endif
2946       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
2947       emit_callne(invalidate_addr_reg[addr]);
2948       #else
2949       void *jaddr2 = out;
2950       emit_jne(0);
2951       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
2952       #endif
2953     }
2954   }
2955   u_int addr_val=constmap[i][s]+offset;
2956   if(jaddr) {
2957     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2958   } else if(c&&!memtarget) {
2959     inline_writestub(type,i,addr_val,i_regs->regmap,rs2[i],ccadj[i],reglist);
2960   }
2961   // basic current block modification detection..
2962   // not looking back as that should be in mips cache already
2963   // (see Spyro2 title->attract mode)
2964   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
2965     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
2966     assert(i_regs->regmap==regs[i].regmap); // not delay slot
2967     if(i_regs->regmap==regs[i].regmap) {
2968       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
2969       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
2970       emit_movimm(start+i*4+4,0);
2971       emit_writeword(0,&pcaddr);
2972       emit_addimm(HOST_CCREG,2,HOST_CCREG);
2973       emit_far_call(get_addr_ht);
2974       emit_jmpreg(0);
2975     }
2976   }
2977 }
2978
2979 static void storelr_assemble(int i,struct regstat *i_regs)
2980 {
2981   int s,tl;
2982   int temp;
2983   int offset;
2984   void *jaddr=0;
2985   void *case1, *case2, *case3;
2986   void *done0, *done1, *done2;
2987   int memtarget=0,c=0;
2988   int agr=AGEN1+(i&1);
2989   u_int hr,reglist=0;
2990   tl=get_reg(i_regs->regmap,rs2[i]);
2991   s=get_reg(i_regs->regmap,rs1[i]);
2992   temp=get_reg(i_regs->regmap,agr);
2993   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2994   offset=imm[i];
2995   if(s>=0) {
2996     c=(i_regs->isconst>>s)&1;
2997     if(c) {
2998       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2999     }
3000   }
3001   assert(tl>=0);
3002   for(hr=0;hr<HOST_REGS;hr++) {
3003     if(i_regs->regmap[hr]>=0) reglist|=1<<hr;
3004   }
3005   assert(temp>=0);
3006   if(!c) {
3007     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3008     if(!offset&&s!=temp) emit_mov(s,temp);
3009     jaddr=out;
3010     emit_jno(0);
3011   }
3012   else
3013   {
3014     if(!memtarget||!rs1[i]) {
3015       jaddr=out;
3016       emit_jmp(0);
3017     }
3018   }
3019   if(ram_offset)
3020     emit_addimm_no_flags(ram_offset,temp);
3021
3022   if (opcode[i]==0x2C||opcode[i]==0x2D) { // SDL/SDR
3023     assert(0);
3024   }
3025
3026   emit_xorimm(temp,3,temp);
3027   emit_testimm(temp,2);
3028   case2=out;
3029   emit_jne(0);
3030   emit_testimm(temp,1);
3031   case1=out;
3032   emit_jne(0);
3033   // 0
3034   if (opcode[i]==0x2A) { // SWL
3035     emit_writeword_indexed(tl,0,temp);
3036   }
3037   else if (opcode[i]==0x2E) { // SWR
3038     emit_writebyte_indexed(tl,3,temp);
3039   }
3040   else
3041     assert(0);
3042   done0=out;
3043   emit_jmp(0);
3044   // 1
3045   set_jump_target(case1, out);
3046   if (opcode[i]==0x2A) { // SWL
3047     // Write 3 msb into three least significant bytes
3048     if(rs2[i]) emit_rorimm(tl,8,tl);
3049     emit_writehword_indexed(tl,-1,temp);
3050     if(rs2[i]) emit_rorimm(tl,16,tl);
3051     emit_writebyte_indexed(tl,1,temp);
3052     if(rs2[i]) emit_rorimm(tl,8,tl);
3053   }
3054   else if (opcode[i]==0x2E) { // SWR
3055     // Write two lsb into two most significant bytes
3056     emit_writehword_indexed(tl,1,temp);
3057   }
3058   done1=out;
3059   emit_jmp(0);
3060   // 2
3061   set_jump_target(case2, out);
3062   emit_testimm(temp,1);
3063   case3=out;
3064   emit_jne(0);
3065   if (opcode[i]==0x2A) { // SWL
3066     // Write two msb into two least significant bytes
3067     if(rs2[i]) emit_rorimm(tl,16,tl);
3068     emit_writehword_indexed(tl,-2,temp);
3069     if(rs2[i]) emit_rorimm(tl,16,tl);
3070   }
3071   else if (opcode[i]==0x2E) { // SWR
3072     // Write 3 lsb into three most significant bytes
3073     emit_writebyte_indexed(tl,-1,temp);
3074     if(rs2[i]) emit_rorimm(tl,8,tl);
3075     emit_writehword_indexed(tl,0,temp);
3076     if(rs2[i]) emit_rorimm(tl,24,tl);
3077   }
3078   done2=out;
3079   emit_jmp(0);
3080   // 3
3081   set_jump_target(case3, out);
3082   if (opcode[i]==0x2A) { // SWL
3083     // Write msb into least significant byte
3084     if(rs2[i]) emit_rorimm(tl,24,tl);
3085     emit_writebyte_indexed(tl,-3,temp);
3086     if(rs2[i]) emit_rorimm(tl,8,tl);
3087   }
3088   else if (opcode[i]==0x2E) { // SWR
3089     // Write entire word
3090     emit_writeword_indexed(tl,-3,temp);
3091   }
3092   set_jump_target(done0, out);
3093   set_jump_target(done1, out);
3094   set_jump_target(done2, out);
3095   if(!c||!memtarget)
3096     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj[i],reglist);
3097   if(!(i_regs->waswritten&(1<<rs1[i]))&&!(new_dynarec_hacks&NDHACK_NO_SMC_CHECK)) {
3098     emit_addimm_no_flags(-ram_offset,temp);
3099     #if defined(HOST_IMM8)
3100     int ir=get_reg(i_regs->regmap,INVCP);
3101     assert(ir>=0);
3102     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3103     #else
3104     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3105     #endif
3106     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3107     emit_callne(invalidate_addr_reg[temp]);
3108     #else
3109     void *jaddr2 = out;
3110     emit_jne(0);
3111     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3112     #endif
3113   }
3114 }
3115
3116 static void cop0_assemble(int i,struct regstat *i_regs)
3117 {
3118   if(opcode2[i]==0) // MFC0
3119   {
3120     signed char t=get_reg(i_regs->regmap,rt1[i]);
3121     u_int copr=(source[i]>>11)&0x1f;
3122     //assert(t>=0); // Why does this happen?  OOT is weird
3123     if(t>=0&&rt1[i]!=0) {
3124       emit_readword(&reg_cop0[copr],t);
3125     }
3126   }
3127   else if(opcode2[i]==4) // MTC0
3128   {
3129     signed char s=get_reg(i_regs->regmap,rs1[i]);
3130     char copr=(source[i]>>11)&0x1f;
3131     assert(s>=0);
3132     wb_register(rs1[i],i_regs->regmap,i_regs->dirty);
3133     if(copr==9||copr==11||copr==12||copr==13) {
3134       emit_readword(&last_count,HOST_TEMPREG);
3135       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3136       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3137       emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3138       emit_writeword(HOST_CCREG,&Count);
3139     }
3140     // What a mess.  The status register (12) can enable interrupts,
3141     // so needs a special case to handle a pending interrupt.
3142     // The interrupt must be taken immediately, because a subsequent
3143     // instruction might disable interrupts again.
3144     if(copr==12||copr==13) {
3145       if (is_delayslot) {
3146         // burn cycles to cause cc_interrupt, which will
3147         // reschedule next_interupt. Relies on CCREG from above.
3148         assem_debug("MTC0 DS %d\n", copr);
3149         emit_writeword(HOST_CCREG,&last_count);
3150         emit_movimm(0,HOST_CCREG);
3151         emit_storereg(CCREG,HOST_CCREG);
3152         emit_loadreg(rs1[i],1);
3153         emit_movimm(copr,0);
3154         emit_far_call(pcsx_mtc0_ds);
3155         emit_loadreg(rs1[i],s);
3156         return;
3157       }
3158       emit_movimm(start+i*4+4,HOST_TEMPREG);
3159       emit_writeword(HOST_TEMPREG,&pcaddr);
3160       emit_movimm(0,HOST_TEMPREG);
3161       emit_writeword(HOST_TEMPREG,&pending_exception);
3162     }
3163     if(s==HOST_CCREG)
3164       emit_loadreg(rs1[i],1);
3165     else if(s!=1)
3166       emit_mov(s,1);
3167     emit_movimm(copr,0);
3168     emit_far_call(pcsx_mtc0);
3169     if(copr==9||copr==11||copr==12||copr==13) {
3170       emit_readword(&Count,HOST_CCREG);
3171       emit_readword(&next_interupt,HOST_TEMPREG);
3172       emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3173       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3174       emit_writeword(HOST_TEMPREG,&last_count);
3175       emit_storereg(CCREG,HOST_CCREG);
3176     }
3177     if(copr==12||copr==13) {
3178       assert(!is_delayslot);
3179       emit_readword(&pending_exception,14);
3180       emit_test(14,14);
3181       void *jaddr = out;
3182       emit_jeq(0);
3183       emit_readword(&pcaddr, 0);
3184       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3185       emit_far_call(get_addr_ht);
3186       emit_jmpreg(0);
3187       set_jump_target(jaddr, out);
3188     }
3189     emit_loadreg(rs1[i],s);
3190   }
3191   else
3192   {
3193     assert(opcode2[i]==0x10);
3194     //if((source[i]&0x3f)==0x10) // RFE
3195     {
3196       emit_readword(&Status,0);
3197       emit_andimm(0,0x3c,1);
3198       emit_andimm(0,~0xf,0);
3199       emit_orrshr_imm(1,2,0);
3200       emit_writeword(0,&Status);
3201     }
3202   }
3203 }
3204
3205 static void cop1_unusable(int i,struct regstat *i_regs)
3206 {
3207   // XXX: should just just do the exception instead
3208   //if(!cop1_usable)
3209   {
3210     void *jaddr=out;
3211     emit_jmp(0);
3212     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3213   }
3214 }
3215
3216 static void cop1_assemble(int i,struct regstat *i_regs)
3217 {
3218   cop1_unusable(i, i_regs);
3219 }
3220
3221 static void c1ls_assemble(int i,struct regstat *i_regs)
3222 {
3223   cop1_unusable(i, i_regs);
3224 }
3225
3226 // FP_STUB
3227 static void do_cop1stub(int n)
3228 {
3229   literal_pool(256);
3230   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3231   set_jump_target(stubs[n].addr, out);
3232   int i=stubs[n].a;
3233 //  int rs=stubs[n].b;
3234   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3235   int ds=stubs[n].d;
3236   if(!ds) {
3237     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3238     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3239   }
3240   //else {printf("fp exception in delay slot\n");}
3241   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3242   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3243   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3244   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3245   emit_far_jump(ds?fp_exception_ds:fp_exception);
3246 }
3247
3248 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3249 {
3250   switch (copr) {
3251     case 1:
3252     case 3:
3253     case 5:
3254     case 8:
3255     case 9:
3256     case 10:
3257     case 11:
3258       emit_readword(&reg_cop2d[copr],tl);
3259       emit_signextend16(tl,tl);
3260       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3261       break;
3262     case 7:
3263     case 16:
3264     case 17:
3265     case 18:
3266     case 19:
3267       emit_readword(&reg_cop2d[copr],tl);
3268       emit_andimm(tl,0xffff,tl);
3269       emit_writeword(tl,&reg_cop2d[copr]);
3270       break;
3271     case 15:
3272       emit_readword(&reg_cop2d[14],tl); // SXY2
3273       emit_writeword(tl,&reg_cop2d[copr]);
3274       break;
3275     case 28:
3276     case 29:
3277       c2op_mfc2_29_assemble(tl,temp);
3278       break;
3279     default:
3280       emit_readword(&reg_cop2d[copr],tl);
3281       break;
3282   }
3283 }
3284
3285 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3286 {
3287   switch (copr) {
3288     case 15:
3289       emit_readword(&reg_cop2d[13],temp);  // SXY1
3290       emit_writeword(sl,&reg_cop2d[copr]);
3291       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3292       emit_readword(&reg_cop2d[14],temp);  // SXY2
3293       emit_writeword(sl,&reg_cop2d[14]);
3294       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3295       break;
3296     case 28:
3297       emit_andimm(sl,0x001f,temp);
3298       emit_shlimm(temp,7,temp);
3299       emit_writeword(temp,&reg_cop2d[9]);
3300       emit_andimm(sl,0x03e0,temp);
3301       emit_shlimm(temp,2,temp);
3302       emit_writeword(temp,&reg_cop2d[10]);
3303       emit_andimm(sl,0x7c00,temp);
3304       emit_shrimm(temp,3,temp);
3305       emit_writeword(temp,&reg_cop2d[11]);
3306       emit_writeword(sl,&reg_cop2d[28]);
3307       break;
3308     case 30:
3309       emit_xorsar_imm(sl,sl,31,temp);
3310 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3311       emit_clz(temp,temp);
3312 #else
3313       emit_movs(temp,HOST_TEMPREG);
3314       emit_movimm(0,temp);
3315       emit_jeq((int)out+4*4);
3316       emit_addpl_imm(temp,1,temp);
3317       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3318       emit_jns((int)out-2*4);
3319 #endif
3320       emit_writeword(sl,&reg_cop2d[30]);
3321       emit_writeword(temp,&reg_cop2d[31]);
3322       break;
3323     case 31:
3324       break;
3325     default:
3326       emit_writeword(sl,&reg_cop2d[copr]);
3327       break;
3328   }
3329 }
3330
3331 static void c2ls_assemble(int i,struct regstat *i_regs)
3332 {
3333   int s,tl;
3334   int ar;
3335   int offset;
3336   int memtarget=0,c=0;
3337   void *jaddr2=NULL;
3338   enum stub_type type;
3339   int agr=AGEN1+(i&1);
3340   int fastio_reg_override=-1;
3341   u_int hr,reglist=0;
3342   u_int copr=(source[i]>>16)&0x1f;
3343   s=get_reg(i_regs->regmap,rs1[i]);
3344   tl=get_reg(i_regs->regmap,FTEMP);
3345   offset=imm[i];
3346   assert(rs1[i]>0);
3347   assert(tl>=0);
3348
3349   for(hr=0;hr<HOST_REGS;hr++) {
3350     if(i_regs->regmap[hr]>=0) reglist|=1<<hr;
3351   }
3352   if(i_regs->regmap[HOST_CCREG]==CCREG)
3353     reglist&=~(1<<HOST_CCREG);
3354
3355   // get the address
3356   if (opcode[i]==0x3a) { // SWC2
3357     ar=get_reg(i_regs->regmap,agr);
3358     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3359     reglist|=1<<ar;
3360   } else { // LWC2
3361     ar=tl;
3362   }
3363   if(s>=0) c=(i_regs->wasconst>>s)&1;
3364   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3365   if (!offset&&!c&&s>=0) ar=s;
3366   assert(ar>=0);
3367
3368   if (opcode[i]==0x3a) { // SWC2
3369     cop2_get_dreg(copr,tl,-1);
3370     type=STOREW_STUB;
3371   }
3372   else
3373     type=LOADW_STUB;
3374
3375   if(c&&!memtarget) {
3376     jaddr2=out;
3377     emit_jmp(0); // inline_readstub/inline_writestub?
3378   }
3379   else {
3380     if(!c) {
3381       jaddr2=emit_fastpath_cmp_jump(i,ar,&fastio_reg_override);
3382     }
3383     else if(ram_offset&&memtarget) {
3384       host_tempreg_acquire();
3385       emit_addimm(ar,ram_offset,HOST_TEMPREG);
3386       fastio_reg_override=HOST_TEMPREG;
3387     }
3388     if (opcode[i]==0x32) { // LWC2
3389       int a=ar;
3390       if(fastio_reg_override>=0) a=fastio_reg_override;
3391       emit_readword_indexed(0,a,tl);
3392     }
3393     if (opcode[i]==0x3a) { // SWC2
3394       #ifdef DESTRUCTIVE_SHIFT
3395       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3396       #endif
3397       int a=ar;
3398       if(fastio_reg_override>=0) a=fastio_reg_override;
3399       emit_writeword_indexed(tl,0,a);
3400     }
3401   }
3402   if(fastio_reg_override==HOST_TEMPREG)
3403     host_tempreg_release();
3404   if(jaddr2)
3405     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj[i],reglist);
3406   if(opcode[i]==0x3a) // SWC2
3407   if(!(i_regs->waswritten&(1<<rs1[i]))&&!(new_dynarec_hacks&NDHACK_NO_SMC_CHECK)) {
3408 #if defined(HOST_IMM8)
3409     int ir=get_reg(i_regs->regmap,INVCP);
3410     assert(ir>=0);
3411     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3412 #else
3413     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3414 #endif
3415     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3416     emit_callne(invalidate_addr_reg[ar]);
3417     #else
3418     void *jaddr3 = out;
3419     emit_jne(0);
3420     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3421     #endif
3422   }
3423   if (opcode[i]==0x32) { // LWC2
3424     host_tempreg_acquire();
3425     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3426     host_tempreg_release();
3427   }
3428 }
3429
3430 static void cop2_assemble(int i,struct regstat *i_regs)
3431 {
3432   u_int copr=(source[i]>>11)&0x1f;
3433   signed char temp=get_reg(i_regs->regmap,-1);
3434   if (opcode2[i]==0) { // MFC2
3435     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3436     if(tl>=0&&rt1[i]!=0)
3437       cop2_get_dreg(copr,tl,temp);
3438   }
3439   else if (opcode2[i]==4) { // MTC2
3440     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3441     cop2_put_dreg(copr,sl,temp);
3442   }
3443   else if (opcode2[i]==2) // CFC2
3444   {
3445     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3446     if(tl>=0&&rt1[i]!=0)
3447       emit_readword(&reg_cop2c[copr],tl);
3448   }
3449   else if (opcode2[i]==6) // CTC2
3450   {
3451     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3452     switch(copr) {
3453       case 4:
3454       case 12:
3455       case 20:
3456       case 26:
3457       case 27:
3458       case 29:
3459       case 30:
3460         emit_signextend16(sl,temp);
3461         break;
3462       case 31:
3463         c2op_ctc2_31_assemble(sl,temp);
3464         break;
3465       default:
3466         temp=sl;
3467         break;
3468     }
3469     emit_writeword(temp,&reg_cop2c[copr]);
3470     assert(sl>=0);
3471   }
3472 }
3473
3474 static void do_unalignedwritestub(int n)
3475 {
3476   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3477   literal_pool(256);
3478   set_jump_target(stubs[n].addr, out);
3479
3480   int i=stubs[n].a;
3481   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3482   int addr=stubs[n].b;
3483   u_int reglist=stubs[n].e;
3484   signed char *i_regmap=i_regs->regmap;
3485   int temp2=get_reg(i_regmap,FTEMP);
3486   int rt;
3487   rt=get_reg(i_regmap,rs2[i]);
3488   assert(rt>=0);
3489   assert(addr>=0);
3490   assert(opcode[i]==0x2a||opcode[i]==0x2e); // SWL/SWR only implemented
3491   reglist|=(1<<addr);
3492   reglist&=~(1<<temp2);
3493
3494 #if 1
3495   // don't bother with it and call write handler
3496   save_regs(reglist);
3497   pass_args(addr,rt);
3498   int cc=get_reg(i_regmap,CCREG);
3499   if(cc<0)
3500     emit_loadreg(CCREG,2);
3501   emit_addimm(cc<0?2:cc,CLOCK_ADJUST((int)stubs[n].d+1),2);
3502   emit_far_call((opcode[i]==0x2a?jump_handle_swl:jump_handle_swr));
3503   emit_addimm(0,-CLOCK_ADJUST((int)stubs[n].d+1),cc<0?2:cc);
3504   if(cc<0)
3505     emit_storereg(CCREG,2);
3506   restore_regs(reglist);
3507   emit_jmp(stubs[n].retaddr); // return address
3508 #else
3509   emit_andimm(addr,0xfffffffc,temp2);
3510   emit_writeword(temp2,&address);
3511
3512   save_regs(reglist);
3513   emit_shrimm(addr,16,1);
3514   int cc=get_reg(i_regmap,CCREG);
3515   if(cc<0) {
3516     emit_loadreg(CCREG,2);
3517   }
3518   emit_movimm((u_int)readmem,0);
3519   emit_addimm(cc<0?2:cc,2*stubs[n].d+2,2);
3520   emit_call((int)&indirect_jump_indexed);
3521   restore_regs(reglist);
3522
3523   emit_readword(&readmem_dword,temp2);
3524   int temp=addr; //hmh
3525   emit_shlimm(addr,3,temp);
3526   emit_andimm(temp,24,temp);
3527   if (opcode[i]==0x2a) // SWL
3528     emit_xorimm(temp,24,temp);
3529   emit_movimm(-1,HOST_TEMPREG);
3530   if (opcode[i]==0x2a) { // SWL
3531     emit_bic_lsr(temp2,HOST_TEMPREG,temp,temp2);
3532     emit_orrshr(rt,temp,temp2);
3533   }else{
3534     emit_bic_lsl(temp2,HOST_TEMPREG,temp,temp2);
3535     emit_orrshl(rt,temp,temp2);
3536   }
3537   emit_readword(&address,addr);
3538   emit_writeword(temp2,&word);
3539   //save_regs(reglist); // don't need to, no state changes
3540   emit_shrimm(addr,16,1);
3541   emit_movimm((u_int)writemem,0);
3542   //emit_call((int)&indirect_jump_indexed);
3543   emit_mov(15,14);
3544   emit_readword_dualindexedx4(0,1,15);
3545   emit_readword(&Count,HOST_TEMPREG);
3546   emit_readword(&next_interupt,2);
3547   emit_addimm(HOST_TEMPREG,-2*stubs[n].d-2,HOST_TEMPREG);
3548   emit_writeword(2,&last_count);
3549   emit_sub(HOST_TEMPREG,2,cc<0?HOST_TEMPREG:cc);
3550   if(cc<0) {
3551     emit_storereg(CCREG,HOST_TEMPREG);
3552   }
3553   restore_regs(reglist);
3554   emit_jmp(stubs[n].retaddr); // return address
3555 #endif
3556 }
3557
3558 #ifndef multdiv_assemble
3559 void multdiv_assemble(int i,struct regstat *i_regs)
3560 {
3561   printf("Need multdiv_assemble for this architecture.\n");
3562   abort();
3563 }
3564 #endif
3565
3566 static void mov_assemble(int i,struct regstat *i_regs)
3567 {
3568   //if(opcode2[i]==0x10||opcode2[i]==0x12) { // MFHI/MFLO
3569   //if(opcode2[i]==0x11||opcode2[i]==0x13) { // MTHI/MTLO
3570   if(rt1[i]) {
3571     signed char sl,tl;
3572     tl=get_reg(i_regs->regmap,rt1[i]);
3573     //assert(tl>=0);
3574     if(tl>=0) {
3575       sl=get_reg(i_regs->regmap,rs1[i]);
3576       if(sl>=0) emit_mov(sl,tl);
3577       else emit_loadreg(rs1[i],tl);
3578     }
3579   }
3580 }
3581
3582 // call interpreter, exception handler, things that change pc/regs/cycles ...
3583 static void call_c_cpu_handler(int i, const struct regstat *i_regs, u_int pc, void *func)
3584 {
3585   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3586   assert(ccreg==HOST_CCREG);
3587   assert(!is_delayslot);
3588   (void)ccreg;
3589
3590   emit_movimm(pc,3); // Get PC
3591   emit_readword(&last_count,2);
3592   emit_writeword(3,&psxRegs.pc);
3593   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // XXX
3594   emit_add(2,HOST_CCREG,2);
3595   emit_writeword(2,&psxRegs.cycle);
3596   emit_far_call(func);
3597   emit_far_jump(jump_to_new_pc);
3598 }
3599
3600 static void syscall_assemble(int i,struct regstat *i_regs)
3601 {
3602   emit_movimm(0x20,0); // cause code
3603   emit_movimm(0,1);    // not in delay slot
3604   call_c_cpu_handler(i,i_regs,start+i*4,psxException);
3605 }
3606
3607 static void hlecall_assemble(int i,struct regstat *i_regs)
3608 {
3609   void *hlefunc = psxNULL;
3610   uint32_t hleCode = source[i] & 0x03ffffff;
3611   if (hleCode < ARRAY_SIZE(psxHLEt))
3612     hlefunc = psxHLEt[hleCode];
3613
3614   call_c_cpu_handler(i,i_regs,start+i*4+4,hlefunc);
3615 }
3616
3617 static void intcall_assemble(int i,struct regstat *i_regs)
3618 {
3619   call_c_cpu_handler(i,i_regs,start+i*4,execI);
3620 }
3621
3622 static void speculate_mov(int rs,int rt)
3623 {
3624   if(rt!=0) {
3625     smrv_strong_next|=1<<rt;
3626     smrv[rt]=smrv[rs];
3627   }
3628 }
3629
3630 static void speculate_mov_weak(int rs,int rt)
3631 {
3632   if(rt!=0) {
3633     smrv_weak_next|=1<<rt;
3634     smrv[rt]=smrv[rs];
3635   }
3636 }
3637
3638 static void speculate_register_values(int i)
3639 {
3640   if(i==0) {
3641     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3642     // gp,sp are likely to stay the same throughout the block
3643     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3644     smrv_weak_next=~smrv_strong_next;
3645     //printf(" llr %08x\n", smrv[4]);
3646   }
3647   smrv_strong=smrv_strong_next;
3648   smrv_weak=smrv_weak_next;
3649   switch(itype[i]) {
3650     case ALU:
3651       if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3652       else if((smrv_strong>>rs2[i])&1) speculate_mov(rs2[i],rt1[i]);
3653       else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3654       else if((smrv_weak>>rs2[i])&1) speculate_mov_weak(rs2[i],rt1[i]);
3655       else {
3656         smrv_strong_next&=~(1<<rt1[i]);
3657         smrv_weak_next&=~(1<<rt1[i]);
3658       }
3659       break;
3660     case SHIFTIMM:
3661       smrv_strong_next&=~(1<<rt1[i]);
3662       smrv_weak_next&=~(1<<rt1[i]);
3663       // fallthrough
3664     case IMM16:
3665       if(rt1[i]&&is_const(&regs[i],rt1[i])) {
3666         int value,hr=get_reg(regs[i].regmap,rt1[i]);
3667         if(hr>=0) {
3668           if(get_final_value(hr,i,&value))
3669                smrv[rt1[i]]=value;
3670           else smrv[rt1[i]]=constmap[i][hr];
3671           smrv_strong_next|=1<<rt1[i];
3672         }
3673       }
3674       else {
3675         if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3676         else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3677       }
3678       break;
3679     case LOAD:
3680       if(start<0x2000&&(rt1[i]==26||(smrv[rt1[i]]>>24)==0xa0)) {
3681         // special case for BIOS
3682         smrv[rt1[i]]=0xa0000000;
3683         smrv_strong_next|=1<<rt1[i];
3684         break;
3685       }
3686       // fallthrough
3687     case SHIFT:
3688     case LOADLR:
3689     case MOV:
3690       smrv_strong_next&=~(1<<rt1[i]);
3691       smrv_weak_next&=~(1<<rt1[i]);
3692       break;
3693     case COP0:
3694     case COP2:
3695       if(opcode2[i]==0||opcode2[i]==2) { // MFC/CFC
3696         smrv_strong_next&=~(1<<rt1[i]);
3697         smrv_weak_next&=~(1<<rt1[i]);
3698       }
3699       break;
3700     case C2LS:
3701       if (opcode[i]==0x32) { // LWC2
3702         smrv_strong_next&=~(1<<rt1[i]);
3703         smrv_weak_next&=~(1<<rt1[i]);
3704       }
3705       break;
3706   }
3707 #if 0
3708   int r=4;
3709   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
3710     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
3711 #endif
3712 }
3713
3714 static void ds_assemble(int i,struct regstat *i_regs)
3715 {
3716   speculate_register_values(i);
3717   is_delayslot=1;
3718   switch(itype[i]) {
3719     case ALU:
3720       alu_assemble(i,i_regs);break;
3721     case IMM16:
3722       imm16_assemble(i,i_regs);break;
3723     case SHIFT:
3724       shift_assemble(i,i_regs);break;
3725     case SHIFTIMM:
3726       shiftimm_assemble(i,i_regs);break;
3727     case LOAD:
3728       load_assemble(i,i_regs);break;
3729     case LOADLR:
3730       loadlr_assemble(i,i_regs);break;
3731     case STORE:
3732       store_assemble(i,i_regs);break;
3733     case STORELR:
3734       storelr_assemble(i,i_regs);break;
3735     case COP0:
3736       cop0_assemble(i,i_regs);break;
3737     case COP1:
3738       cop1_assemble(i,i_regs);break;
3739     case C1LS:
3740       c1ls_assemble(i,i_regs);break;
3741     case COP2:
3742       cop2_assemble(i,i_regs);break;
3743     case C2LS:
3744       c2ls_assemble(i,i_regs);break;
3745     case C2OP:
3746       c2op_assemble(i,i_regs);break;
3747     case MULTDIV:
3748       multdiv_assemble(i,i_regs);break;
3749     case MOV:
3750       mov_assemble(i,i_regs);break;
3751     case SYSCALL:
3752     case HLECALL:
3753     case INTCALL:
3754     case SPAN:
3755     case UJUMP:
3756     case RJUMP:
3757     case CJUMP:
3758     case SJUMP:
3759       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
3760   }
3761   is_delayslot=0;
3762 }
3763
3764 // Is the branch target a valid internal jump?
3765 static int internal_branch(int addr)
3766 {
3767   if(addr&1) return 0; // Indirect (register) jump
3768   if(addr>=start && addr<start+slen*4-4)
3769   {
3770     return 1;
3771   }
3772   return 0;
3773 }
3774
3775 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
3776 {
3777   int hr;
3778   for(hr=0;hr<HOST_REGS;hr++) {
3779     if(hr!=EXCLUDE_REG) {
3780       if(pre[hr]!=entry[hr]) {
3781         if(pre[hr]>=0) {
3782           if((dirty>>hr)&1) {
3783             if(get_reg(entry,pre[hr])<0) {
3784               assert(pre[hr]<64);
3785               if(!((u>>pre[hr])&1))
3786                 emit_storereg(pre[hr],hr);
3787             }
3788           }
3789         }
3790       }
3791     }
3792   }
3793   // Move from one register to another (no writeback)
3794   for(hr=0;hr<HOST_REGS;hr++) {
3795     if(hr!=EXCLUDE_REG) {
3796       if(pre[hr]!=entry[hr]) {
3797         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
3798           int nr;
3799           if((nr=get_reg(entry,pre[hr]))>=0) {
3800             emit_mov(hr,nr);
3801           }
3802         }
3803       }
3804     }
3805   }
3806 }
3807
3808 // Load the specified registers
3809 // This only loads the registers given as arguments because
3810 // we don't want to load things that will be overwritten
3811 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
3812 {
3813   int hr;
3814   // Load 32-bit regs
3815   for(hr=0;hr<HOST_REGS;hr++) {
3816     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
3817       if(entry[hr]!=regmap[hr]) {
3818         if(regmap[hr]==rs1||regmap[hr]==rs2)
3819         {
3820           if(regmap[hr]==0) {
3821             emit_zeroreg(hr);
3822           }
3823           else
3824           {
3825             emit_loadreg(regmap[hr],hr);
3826           }
3827         }
3828       }
3829     }
3830   }
3831 }
3832
3833 // Load registers prior to the start of a loop
3834 // so that they are not loaded within the loop
3835 static void loop_preload(signed char pre[],signed char entry[])
3836 {
3837   int hr;
3838   for(hr=0;hr<HOST_REGS;hr++) {
3839     if(hr!=EXCLUDE_REG) {
3840       if(pre[hr]!=entry[hr]) {
3841         if(entry[hr]>=0) {
3842           if(get_reg(pre,entry[hr])<0) {
3843             assem_debug("loop preload:\n");
3844             //printf("loop preload: %d\n",hr);
3845             if(entry[hr]==0) {
3846               emit_zeroreg(hr);
3847             }
3848             else if(entry[hr]<TEMPREG)
3849             {
3850               emit_loadreg(entry[hr],hr);
3851             }
3852             else if(entry[hr]-64<TEMPREG)
3853             {
3854               emit_loadreg(entry[hr],hr);
3855             }
3856           }
3857         }
3858       }
3859     }
3860   }
3861 }
3862
3863 // Generate address for load/store instruction
3864 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
3865 void address_generation(int i,struct regstat *i_regs,signed char entry[])
3866 {
3867   if(itype[i]==LOAD||itype[i]==LOADLR||itype[i]==STORE||itype[i]==STORELR||itype[i]==C1LS||itype[i]==C2LS) {
3868     int ra=-1;
3869     int agr=AGEN1+(i&1);
3870     if(itype[i]==LOAD) {
3871       ra=get_reg(i_regs->regmap,rt1[i]);
3872       if(ra<0) ra=get_reg(i_regs->regmap,-1);
3873       assert(ra>=0);
3874     }
3875     if(itype[i]==LOADLR) {
3876       ra=get_reg(i_regs->regmap,FTEMP);
3877     }
3878     if(itype[i]==STORE||itype[i]==STORELR) {
3879       ra=get_reg(i_regs->regmap,agr);
3880       if(ra<0) ra=get_reg(i_regs->regmap,-1);
3881     }
3882     if(itype[i]==C1LS||itype[i]==C2LS) {
3883       if ((opcode[i]&0x3b)==0x31||(opcode[i]&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
3884         ra=get_reg(i_regs->regmap,FTEMP);
3885       else { // SWC1/SDC1/SWC2/SDC2
3886         ra=get_reg(i_regs->regmap,agr);
3887         if(ra<0) ra=get_reg(i_regs->regmap,-1);
3888       }
3889     }
3890     int rs=get_reg(i_regs->regmap,rs1[i]);
3891     if(ra>=0) {
3892       int offset=imm[i];
3893       int c=(i_regs->wasconst>>rs)&1;
3894       if(rs1[i]==0) {
3895         // Using r0 as a base address
3896         if(!entry||entry[ra]!=agr) {
3897           if (opcode[i]==0x22||opcode[i]==0x26) {
3898             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
3899           }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
3900             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
3901           }else{
3902             emit_movimm(offset,ra);
3903           }
3904         } // else did it in the previous cycle
3905       }
3906       else if(rs<0) {
3907         if(!entry||entry[ra]!=rs1[i])
3908           emit_loadreg(rs1[i],ra);
3909         //if(!entry||entry[ra]!=rs1[i])
3910         //  printf("poor load scheduling!\n");
3911       }
3912       else if(c) {
3913         if(rs1[i]!=rt1[i]||itype[i]!=LOAD) {
3914           if(!entry||entry[ra]!=agr) {
3915             if (opcode[i]==0x22||opcode[i]==0x26) {
3916               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
3917             }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
3918               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
3919             }else{
3920               emit_movimm(constmap[i][rs]+offset,ra);
3921               regs[i].loadedconst|=1<<ra;
3922             }
3923           } // else did it in the previous cycle
3924         } // else load_consts already did it
3925       }
3926       if(offset&&!c&&rs1[i]) {
3927         if(rs>=0) {
3928           emit_addimm(rs,offset,ra);
3929         }else{
3930           emit_addimm(ra,offset,ra);
3931         }
3932       }
3933     }
3934   }
3935   // Preload constants for next instruction
3936   if(itype[i+1]==LOAD||itype[i+1]==LOADLR||itype[i+1]==STORE||itype[i+1]==STORELR||itype[i+1]==C1LS||itype[i+1]==C2LS) {
3937     int agr,ra;
3938     // Actual address
3939     agr=AGEN1+((i+1)&1);
3940     ra=get_reg(i_regs->regmap,agr);
3941     if(ra>=0) {
3942       int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
3943       int offset=imm[i+1];
3944       int c=(regs[i+1].wasconst>>rs)&1;
3945       if(c&&(rs1[i+1]!=rt1[i+1]||itype[i+1]!=LOAD)) {
3946         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
3947           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
3948         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
3949           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
3950         }else{
3951           emit_movimm(constmap[i+1][rs]+offset,ra);
3952           regs[i+1].loadedconst|=1<<ra;
3953         }
3954       }
3955       else if(rs1[i+1]==0) {
3956         // Using r0 as a base address
3957         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
3958           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
3959         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
3960           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
3961         }else{
3962           emit_movimm(offset,ra);
3963         }
3964       }
3965     }
3966   }
3967 }
3968
3969 static int get_final_value(int hr, int i, int *value)
3970 {
3971   int reg=regs[i].regmap[hr];
3972   while(i<slen-1) {
3973     if(regs[i+1].regmap[hr]!=reg) break;
3974     if(!((regs[i+1].isconst>>hr)&1)) break;
3975     if(bt[i+1]) break;
3976     i++;
3977   }
3978   if(i<slen-1) {
3979     if(itype[i]==UJUMP||itype[i]==RJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
3980       *value=constmap[i][hr];
3981       return 1;
3982     }
3983     if(!bt[i+1]) {
3984       if(itype[i+1]==UJUMP||itype[i+1]==RJUMP||itype[i+1]==CJUMP||itype[i+1]==SJUMP) {
3985         // Load in delay slot, out-of-order execution
3986         if(itype[i+2]==LOAD&&rs1[i+2]==reg&&rt1[i+2]==reg&&((regs[i+1].wasconst>>hr)&1))
3987         {
3988           // Precompute load address
3989           *value=constmap[i][hr]+imm[i+2];
3990           return 1;
3991         }
3992       }
3993       if(itype[i+1]==LOAD&&rs1[i+1]==reg&&rt1[i+1]==reg)
3994       {
3995         // Precompute load address
3996         *value=constmap[i][hr]+imm[i+1];
3997         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
3998         return 1;
3999       }
4000     }
4001   }
4002   *value=constmap[i][hr];
4003   //printf("c=%lx\n",(long)constmap[i][hr]);
4004   if(i==slen-1) return 1;
4005   assert(reg < 64);
4006   return !((unneeded_reg[i+1]>>reg)&1);
4007 }
4008
4009 // Load registers with known constants
4010 static void load_consts(signed char pre[],signed char regmap[],int i)
4011 {
4012   int hr,hr2;
4013   // propagate loaded constant flags
4014   if(i==0||bt[i])
4015     regs[i].loadedconst=0;
4016   else {
4017     for(hr=0;hr<HOST_REGS;hr++) {
4018       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4019          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4020       {
4021         regs[i].loadedconst|=1<<hr;
4022       }
4023     }
4024   }
4025   // Load 32-bit regs
4026   for(hr=0;hr<HOST_REGS;hr++) {
4027     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4028       //if(entry[hr]!=regmap[hr]) {
4029       if(!((regs[i].loadedconst>>hr)&1)) {
4030         assert(regmap[hr]<64);
4031         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4032           int value,similar=0;
4033           if(get_final_value(hr,i,&value)) {
4034             // see if some other register has similar value
4035             for(hr2=0;hr2<HOST_REGS;hr2++) {
4036               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4037                 if(is_similar_value(value,constmap[i][hr2])) {
4038                   similar=1;
4039                   break;
4040                 }
4041               }
4042             }
4043             if(similar) {
4044               int value2;
4045               if(get_final_value(hr2,i,&value2)) // is this needed?
4046                 emit_movimm_from(value2,hr2,value,hr);
4047               else
4048                 emit_movimm(value,hr);
4049             }
4050             else if(value==0) {
4051               emit_zeroreg(hr);
4052             }
4053             else {
4054               emit_movimm(value,hr);
4055             }
4056           }
4057           regs[i].loadedconst|=1<<hr;
4058         }
4059       }
4060     }
4061   }
4062 }
4063
4064 void load_all_consts(signed char regmap[], u_int dirty, int i)
4065 {
4066   int hr;
4067   // Load 32-bit regs
4068   for(hr=0;hr<HOST_REGS;hr++) {
4069     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4070       assert(regmap[hr] < 64);
4071       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4072         int value=constmap[i][hr];
4073         if(value==0) {
4074           emit_zeroreg(hr);
4075         }
4076         else {
4077           emit_movimm(value,hr);
4078         }
4079       }
4080     }
4081   }
4082 }
4083
4084 // Write out all dirty registers (except cycle count)
4085 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty)
4086 {
4087   int hr;
4088   for(hr=0;hr<HOST_REGS;hr++) {
4089     if(hr!=EXCLUDE_REG) {
4090       if(i_regmap[hr]>0) {
4091         if(i_regmap[hr]!=CCREG) {
4092           if((i_dirty>>hr)&1) {
4093             assert(i_regmap[hr]<64);
4094             emit_storereg(i_regmap[hr],hr);
4095           }
4096         }
4097       }
4098     }
4099   }
4100 }
4101
4102 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4103 // This writes the registers not written by store_regs_bt
4104 void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr)
4105 {
4106   int hr;
4107   int t=(addr-start)>>2;
4108   for(hr=0;hr<HOST_REGS;hr++) {
4109     if(hr!=EXCLUDE_REG) {
4110       if(i_regmap[hr]>0) {
4111         if(i_regmap[hr]!=CCREG) {
4112           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4113             if((i_dirty>>hr)&1) {
4114               assert(i_regmap[hr]<64);
4115               emit_storereg(i_regmap[hr],hr);
4116             }
4117           }
4118         }
4119       }
4120     }
4121   }
4122 }
4123
4124 // Load all registers (except cycle count)
4125 void load_all_regs(signed char i_regmap[])
4126 {
4127   int hr;
4128   for(hr=0;hr<HOST_REGS;hr++) {
4129     if(hr!=EXCLUDE_REG) {
4130       if(i_regmap[hr]==0) {
4131         emit_zeroreg(hr);
4132       }
4133       else
4134       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4135       {
4136         emit_loadreg(i_regmap[hr],hr);
4137       }
4138     }
4139   }
4140 }
4141
4142 // Load all current registers also needed by next instruction
4143 void load_needed_regs(signed char i_regmap[],signed char next_regmap[])
4144 {
4145   int hr;
4146   for(hr=0;hr<HOST_REGS;hr++) {
4147     if(hr!=EXCLUDE_REG) {
4148       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4149         if(i_regmap[hr]==0) {
4150           emit_zeroreg(hr);
4151         }
4152         else
4153         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4154         {
4155           emit_loadreg(i_regmap[hr],hr);
4156         }
4157       }
4158     }
4159   }
4160 }
4161
4162 // Load all regs, storing cycle count if necessary
4163 void load_regs_entry(int t)
4164 {
4165   int hr;
4166   if(is_ds[t]) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4167   else if(ccadj[t]) emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[t]),HOST_CCREG);
4168   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4169     emit_storereg(CCREG,HOST_CCREG);
4170   }
4171   // Load 32-bit regs
4172   for(hr=0;hr<HOST_REGS;hr++) {
4173     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4174       if(regs[t].regmap_entry[hr]==0) {
4175         emit_zeroreg(hr);
4176       }
4177       else if(regs[t].regmap_entry[hr]!=CCREG)
4178       {
4179         emit_loadreg(regs[t].regmap_entry[hr],hr);
4180       }
4181     }
4182   }
4183 }
4184
4185 // Store dirty registers prior to branch
4186 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4187 {
4188   if(internal_branch(addr))
4189   {
4190     int t=(addr-start)>>2;
4191     int hr;
4192     for(hr=0;hr<HOST_REGS;hr++) {
4193       if(hr!=EXCLUDE_REG) {
4194         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4195           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4196             if((i_dirty>>hr)&1) {
4197               assert(i_regmap[hr]<64);
4198               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4199                 emit_storereg(i_regmap[hr],hr);
4200             }
4201           }
4202         }
4203       }
4204     }
4205   }
4206   else
4207   {
4208     // Branch out of this block, write out all dirty regs
4209     wb_dirtys(i_regmap,i_dirty);
4210   }
4211 }
4212
4213 // Load all needed registers for branch target
4214 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4215 {
4216   //if(addr>=start && addr<(start+slen*4))
4217   if(internal_branch(addr))
4218   {
4219     int t=(addr-start)>>2;
4220     int hr;
4221     // Store the cycle count before loading something else
4222     if(i_regmap[HOST_CCREG]!=CCREG) {
4223       assert(i_regmap[HOST_CCREG]==-1);
4224     }
4225     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4226       emit_storereg(CCREG,HOST_CCREG);
4227     }
4228     // Load 32-bit regs
4229     for(hr=0;hr<HOST_REGS;hr++) {
4230       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4231         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4232           if(regs[t].regmap_entry[hr]==0) {
4233             emit_zeroreg(hr);
4234           }
4235           else if(regs[t].regmap_entry[hr]!=CCREG)
4236           {
4237             emit_loadreg(regs[t].regmap_entry[hr],hr);
4238           }
4239         }
4240       }
4241     }
4242   }
4243 }
4244
4245 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4246 {
4247   if(addr>=start && addr<start+slen*4-4)
4248   {
4249     int t=(addr-start)>>2;
4250     int hr;
4251     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4252     for(hr=0;hr<HOST_REGS;hr++)
4253     {
4254       if(hr!=EXCLUDE_REG)
4255       {
4256         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4257         {
4258           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4259           {
4260             return 0;
4261           }
4262           else
4263           if((i_dirty>>hr)&1)
4264           {
4265             if(i_regmap[hr]<TEMPREG)
4266             {
4267               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4268                 return 0;
4269             }
4270             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4271             {
4272               assert(0);
4273             }
4274           }
4275         }
4276         else // Same register but is it 32-bit or dirty?
4277         if(i_regmap[hr]>=0)
4278         {
4279           if(!((regs[t].dirty>>hr)&1))
4280           {
4281             if((i_dirty>>hr)&1)
4282             {
4283               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4284               {
4285                 //printf("%x: dirty no match\n",addr);
4286                 return 0;
4287               }
4288             }
4289           }
4290         }
4291       }
4292     }
4293     // Delay slots are not valid branch targets
4294     //if(t>0&&(itype[t-1]==RJUMP||itype[t-1]==UJUMP||itype[t-1]==CJUMP||itype[t-1]==SJUMP)) return 0;
4295     // Delay slots require additional processing, so do not match
4296     if(is_ds[t]) return 0;
4297   }
4298   else
4299   {
4300     int hr;
4301     for(hr=0;hr<HOST_REGS;hr++)
4302     {
4303       if(hr!=EXCLUDE_REG)
4304       {
4305         if(i_regmap[hr]>=0)
4306         {
4307           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4308           {
4309             if((i_dirty>>hr)&1)
4310             {
4311               return 0;
4312             }
4313           }
4314         }
4315       }
4316     }
4317   }
4318   return 1;
4319 }
4320
4321 #ifdef DRC_DBG
4322 static void drc_dbg_emit_do_cmp(int i)
4323 {
4324   extern void do_insn_cmp();
4325   //extern int cycle;
4326   u_int hr,reglist=0;
4327
4328   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4329   for (hr = 0; hr < HOST_REGS; hr++)
4330     if(regs[i].regmap[hr]>=0) reglist|=1<<hr;
4331   save_regs(reglist);
4332   // write out changed consts to match the interpreter
4333   if (i > 0 && !bt[i]) {
4334     for (hr = 0; hr < HOST_REGS; hr++) {
4335       int reg = regs[i-1].regmap[hr];
4336       if (hr == EXCLUDE_REG || reg < 0)
4337         continue;
4338       if (!((regs[i-1].isconst >> hr) & 1))
4339         continue;
4340       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4341         continue;
4342       emit_movimm(constmap[i-1][hr],0);
4343       emit_storereg(reg, 0);
4344     }
4345   }
4346   emit_movimm(start+i*4,0);
4347   emit_writeword(0,&pcaddr);
4348   emit_far_call(do_insn_cmp);
4349   //emit_readword(&cycle,0);
4350   //emit_addimm(0,2,0);
4351   //emit_writeword(0,&cycle);
4352   (void)get_reg2;
4353   restore_regs(reglist);
4354   assem_debug("\\\\do_insn_cmp\n");
4355 }
4356 #else
4357 #define drc_dbg_emit_do_cmp(x)
4358 #endif
4359
4360 // Used when a branch jumps into the delay slot of another branch
4361 static void ds_assemble_entry(int i)
4362 {
4363   int t=(ba[i]-start)>>2;
4364   if (!instr_addr[t])
4365     instr_addr[t] = out;
4366   assem_debug("Assemble delay slot at %x\n",ba[i]);
4367   assem_debug("<->\n");
4368   drc_dbg_emit_do_cmp(t);
4369   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4370     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4371   load_regs(regs[t].regmap_entry,regs[t].regmap,rs1[t],rs2[t]);
4372   address_generation(t,&regs[t],regs[t].regmap_entry);
4373   if(itype[t]==STORE||itype[t]==STORELR||(opcode[t]&0x3b)==0x39||(opcode[t]&0x3b)==0x3a)
4374     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4375   is_delayslot=0;
4376   switch(itype[t]) {
4377     case ALU:
4378       alu_assemble(t,&regs[t]);break;
4379     case IMM16:
4380       imm16_assemble(t,&regs[t]);break;
4381     case SHIFT:
4382       shift_assemble(t,&regs[t]);break;
4383     case SHIFTIMM:
4384       shiftimm_assemble(t,&regs[t]);break;
4385     case LOAD:
4386       load_assemble(t,&regs[t]);break;
4387     case LOADLR:
4388       loadlr_assemble(t,&regs[t]);break;
4389     case STORE:
4390       store_assemble(t,&regs[t]);break;
4391     case STORELR:
4392       storelr_assemble(t,&regs[t]);break;
4393     case COP0:
4394       cop0_assemble(t,&regs[t]);break;
4395     case COP1:
4396       cop1_assemble(t,&regs[t]);break;
4397     case C1LS:
4398       c1ls_assemble(t,&regs[t]);break;
4399     case COP2:
4400       cop2_assemble(t,&regs[t]);break;
4401     case C2LS:
4402       c2ls_assemble(t,&regs[t]);break;
4403     case C2OP:
4404       c2op_assemble(t,&regs[t]);break;
4405     case MULTDIV:
4406       multdiv_assemble(t,&regs[t]);break;
4407     case MOV:
4408       mov_assemble(t,&regs[t]);break;
4409     case SYSCALL:
4410     case HLECALL:
4411     case INTCALL:
4412     case SPAN:
4413     case UJUMP:
4414     case RJUMP:
4415     case CJUMP:
4416     case SJUMP:
4417       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4418   }
4419   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4420   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4421   if(internal_branch(ba[i]+4))
4422     assem_debug("branch: internal\n");
4423   else
4424     assem_debug("branch: external\n");
4425   assert(internal_branch(ba[i]+4));
4426   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4427   emit_jmp(0);
4428 }
4429
4430 static void emit_extjump(void *addr, u_int target)
4431 {
4432   emit_extjump2(addr, target, dyna_linker);
4433 }
4434
4435 static void emit_extjump_ds(void *addr, u_int target)
4436 {
4437   emit_extjump2(addr, target, dyna_linker_ds);
4438 }
4439
4440 // Load 2 immediates optimizing for small code size
4441 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4442 {
4443   emit_movimm(imm1,rt1);
4444   emit_movimm_from(imm1,rt1,imm2,rt2);
4445 }
4446
4447 void do_cc(int i,signed char i_regmap[],int *adj,int addr,int taken,int invert)
4448 {
4449   int count;
4450   void *jaddr;
4451   void *idle=NULL;
4452   int t=0;
4453   if(itype[i]==RJUMP)
4454   {
4455     *adj=0;
4456   }
4457   //if(ba[i]>=start && ba[i]<(start+slen*4))
4458   if(internal_branch(ba[i]))
4459   {
4460     t=(ba[i]-start)>>2;
4461     if(is_ds[t]) *adj=-1; // Branch into delay slot adds an extra cycle
4462     else *adj=ccadj[t];
4463   }
4464   else
4465   {
4466     *adj=0;
4467   }
4468   count=ccadj[i];
4469   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4470     // Idle loop
4471     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4472     idle=out;
4473     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4474     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4475     jaddr=out;
4476     emit_jmp(0);
4477   }
4478   else if(*adj==0||invert) {
4479     int cycles=CLOCK_ADJUST(count+2);
4480     // faster loop HACK
4481 #if 0
4482     if (t&&*adj) {
4483       int rel=t-i;
4484       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4485         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4486     }
4487 #endif
4488     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4489     jaddr=out;
4490     emit_jns(0);
4491   }
4492   else
4493   {
4494     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4495     jaddr=out;
4496     emit_jns(0);
4497   }
4498   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4499 }
4500
4501 static void do_ccstub(int n)
4502 {
4503   literal_pool(256);
4504   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4505   set_jump_target(stubs[n].addr, out);
4506   int i=stubs[n].b;
4507   if(stubs[n].d==NULLDS) {
4508     // Delay slot instruction is nullified ("likely" branch)
4509     wb_dirtys(regs[i].regmap,regs[i].dirty);
4510   }
4511   else if(stubs[n].d!=TAKEN) {
4512     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4513   }
4514   else {
4515     if(internal_branch(ba[i]))
4516       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4517   }
4518   if(stubs[n].c!=-1)
4519   {
4520     // Save PC as return address
4521     emit_movimm(stubs[n].c,EAX);
4522     emit_writeword(EAX,&pcaddr);
4523   }
4524   else
4525   {
4526     // Return address depends on which way the branch goes
4527     if(itype[i]==CJUMP||itype[i]==SJUMP)
4528     {
4529       int s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4530       int s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4531       if(rs1[i]==0)
4532       {
4533         s1l=s2l;
4534         s2l=-1;
4535       }
4536       else if(rs2[i]==0)
4537       {
4538         s2l=-1;
4539       }
4540       assert(s1l>=0);
4541       #ifdef DESTRUCTIVE_WRITEBACK
4542       if(rs1[i]) {
4543         if((branch_regs[i].dirty>>s1l)&&1)
4544           emit_loadreg(rs1[i],s1l);
4545       }
4546       else {
4547         if((branch_regs[i].dirty>>s1l)&1)
4548           emit_loadreg(rs2[i],s1l);
4549       }
4550       if(s2l>=0)
4551         if((branch_regs[i].dirty>>s2l)&1)
4552           emit_loadreg(rs2[i],s2l);
4553       #endif
4554       int hr=0;
4555       int addr=-1,alt=-1,ntaddr=-1;
4556       while(hr<HOST_REGS)
4557       {
4558         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4559            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4560            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4561         {
4562           addr=hr++;break;
4563         }
4564         hr++;
4565       }
4566       while(hr<HOST_REGS)
4567       {
4568         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4569            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4570            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4571         {
4572           alt=hr++;break;
4573         }
4574         hr++;
4575       }
4576       if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
4577       {
4578         while(hr<HOST_REGS)
4579         {
4580           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4581              (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4582              (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4583           {
4584             ntaddr=hr;break;
4585           }
4586           hr++;
4587         }
4588         assert(hr<HOST_REGS);
4589       }
4590       if((opcode[i]&0x2f)==4) // BEQ
4591       {
4592         #ifdef HAVE_CMOV_IMM
4593         if(s2l>=0) emit_cmp(s1l,s2l);
4594         else emit_test(s1l,s1l);
4595         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4596         #else
4597         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4598         if(s2l>=0) emit_cmp(s1l,s2l);
4599         else emit_test(s1l,s1l);
4600         emit_cmovne_reg(alt,addr);
4601         #endif
4602       }
4603       if((opcode[i]&0x2f)==5) // BNE
4604       {
4605         #ifdef HAVE_CMOV_IMM
4606         if(s2l>=0) emit_cmp(s1l,s2l);
4607         else emit_test(s1l,s1l);
4608         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4609         #else
4610         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4611         if(s2l>=0) emit_cmp(s1l,s2l);
4612         else emit_test(s1l,s1l);
4613         emit_cmovne_reg(alt,addr);
4614         #endif
4615       }
4616       if((opcode[i]&0x2f)==6) // BLEZ
4617       {
4618         //emit_movimm(ba[i],alt);
4619         //emit_movimm(start+i*4+8,addr);
4620         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4621         emit_cmpimm(s1l,1);
4622         emit_cmovl_reg(alt,addr);
4623       }
4624       if((opcode[i]&0x2f)==7) // BGTZ
4625       {
4626         //emit_movimm(ba[i],addr);
4627         //emit_movimm(start+i*4+8,ntaddr);
4628         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4629         emit_cmpimm(s1l,1);
4630         emit_cmovl_reg(ntaddr,addr);
4631       }
4632       if((opcode[i]==1)&&(opcode2[i]&0x2D)==0) // BLTZ
4633       {
4634         //emit_movimm(ba[i],alt);
4635         //emit_movimm(start+i*4+8,addr);
4636         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4637         emit_test(s1l,s1l);
4638         emit_cmovs_reg(alt,addr);
4639       }
4640       if((opcode[i]==1)&&(opcode2[i]&0x2D)==1) // BGEZ
4641       {
4642         //emit_movimm(ba[i],addr);
4643         //emit_movimm(start+i*4+8,alt);
4644         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4645         emit_test(s1l,s1l);
4646         emit_cmovs_reg(alt,addr);
4647       }
4648       if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
4649         if(source[i]&0x10000) // BC1T
4650         {
4651           //emit_movimm(ba[i],alt);
4652           //emit_movimm(start+i*4+8,addr);
4653           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4654           emit_testimm(s1l,0x800000);
4655           emit_cmovne_reg(alt,addr);
4656         }
4657         else // BC1F
4658         {
4659           //emit_movimm(ba[i],addr);
4660           //emit_movimm(start+i*4+8,alt);
4661           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4662           emit_testimm(s1l,0x800000);
4663           emit_cmovne_reg(alt,addr);
4664         }
4665       }
4666       emit_writeword(addr,&pcaddr);
4667     }
4668     else
4669     if(itype[i]==RJUMP)
4670     {
4671       int r=get_reg(branch_regs[i].regmap,rs1[i]);
4672       if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4673         r=get_reg(branch_regs[i].regmap,RTEMP);
4674       }
4675       emit_writeword(r,&pcaddr);
4676     }
4677     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4678   }
4679   // Update cycle count
4680   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4681   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4682   emit_far_call(cc_interrupt);
4683   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4684   if(stubs[n].d==TAKEN) {
4685     if(internal_branch(ba[i]))
4686       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4687     else if(itype[i]==RJUMP) {
4688       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4689         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4690       else
4691         emit_loadreg(rs1[i],get_reg(branch_regs[i].regmap,rs1[i]));
4692     }
4693   }else if(stubs[n].d==NOTTAKEN) {
4694     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4695     else load_all_regs(branch_regs[i].regmap);
4696   }else if(stubs[n].d==NULLDS) {
4697     // Delay slot instruction is nullified ("likely" branch)
4698     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
4699     else load_all_regs(regs[i].regmap);
4700   }else{
4701     load_all_regs(branch_regs[i].regmap);
4702   }
4703   if (stubs[n].retaddr)
4704     emit_jmp(stubs[n].retaddr);
4705   else
4706     do_jump_vaddr(stubs[n].e);
4707 }
4708
4709 static void add_to_linker(void *addr, u_int target, int ext)
4710 {
4711   assert(linkcount < ARRAY_SIZE(link_addr));
4712   link_addr[linkcount].addr = addr;
4713   link_addr[linkcount].target = target;
4714   link_addr[linkcount].ext = ext;
4715   linkcount++;
4716 }
4717
4718 static void ujump_assemble_write_ra(int i)
4719 {
4720   int rt;
4721   unsigned int return_address;
4722   rt=get_reg(branch_regs[i].regmap,31);
4723   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]);
4724   //assert(rt>=0);
4725   return_address=start+i*4+8;
4726   if(rt>=0) {
4727     #ifdef USE_MINI_HT
4728     if(internal_branch(return_address)&&rt1[i+1]!=31) {
4729       int temp=-1; // note: must be ds-safe
4730       #ifdef HOST_TEMPREG
4731       temp=HOST_TEMPREG;
4732       #endif
4733       if(temp>=0) do_miniht_insert(return_address,rt,temp);
4734       else emit_movimm(return_address,rt);
4735     }
4736     else
4737     #endif
4738     {
4739       #ifdef REG_PREFETCH
4740       if(temp>=0)
4741       {
4742         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4743       }
4744       #endif
4745       emit_movimm(return_address,rt); // PC into link register
4746       #ifdef IMM_PREFETCH
4747       emit_prefetch(hash_table_get(return_address));
4748       #endif
4749     }
4750   }
4751 }
4752
4753 static void ujump_assemble(int i,struct regstat *i_regs)
4754 {
4755   int ra_done=0;
4756   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
4757   address_generation(i+1,i_regs,regs[i].regmap_entry);
4758   #ifdef REG_PREFETCH
4759   int temp=get_reg(branch_regs[i].regmap,PTEMP);
4760   if(rt1[i]==31&&temp>=0)
4761   {
4762     signed char *i_regmap=i_regs->regmap;
4763     int return_address=start+i*4+8;
4764     if(get_reg(branch_regs[i].regmap,31)>0)
4765     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4766   }
4767   #endif
4768   if(rt1[i]==31&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
4769     ujump_assemble_write_ra(i); // writeback ra for DS
4770     ra_done=1;
4771   }
4772   ds_assemble(i+1,i_regs);
4773   uint64_t bc_unneeded=branch_regs[i].u;
4774   bc_unneeded|=1|(1LL<<rt1[i]);
4775   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4776   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
4777   if(!ra_done&&rt1[i]==31)
4778     ujump_assemble_write_ra(i);
4779   int cc,adj;
4780   cc=get_reg(branch_regs[i].regmap,CCREG);
4781   assert(cc==HOST_CCREG);
4782   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4783   #ifdef REG_PREFETCH
4784   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
4785   #endif
4786   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
4787   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
4788   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4789   if(internal_branch(ba[i]))
4790     assem_debug("branch: internal\n");
4791   else
4792     assem_debug("branch: external\n");
4793   if(internal_branch(ba[i])&&is_ds[(ba[i]-start)>>2]) {
4794     ds_assemble_entry(i);
4795   }
4796   else {
4797     add_to_linker(out,ba[i],internal_branch(ba[i]));
4798     emit_jmp(0);
4799   }
4800 }
4801
4802 static void rjump_assemble_write_ra(int i)
4803 {
4804   int rt,return_address;
4805   assert(rt1[i+1]!=rt1[i]);
4806   assert(rt2[i+1]!=rt1[i]);
4807   rt=get_reg(branch_regs[i].regmap,rt1[i]);
4808   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]);
4809   assert(rt>=0);
4810   return_address=start+i*4+8;
4811   #ifdef REG_PREFETCH
4812   if(temp>=0)
4813   {
4814     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4815   }
4816   #endif
4817   emit_movimm(return_address,rt); // PC into link register
4818   #ifdef IMM_PREFETCH
4819   emit_prefetch(hash_table_get(return_address));
4820   #endif
4821 }
4822
4823 static void rjump_assemble(int i,struct regstat *i_regs)
4824 {
4825   int temp;
4826   int rs,cc;
4827   int ra_done=0;
4828   rs=get_reg(branch_regs[i].regmap,rs1[i]);
4829   assert(rs>=0);
4830   if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4831     // Delay slot abuse, make a copy of the branch address register
4832     temp=get_reg(branch_regs[i].regmap,RTEMP);
4833     assert(temp>=0);
4834     assert(regs[i].regmap[temp]==RTEMP);
4835     emit_mov(rs,temp);
4836     rs=temp;
4837   }
4838   address_generation(i+1,i_regs,regs[i].regmap_entry);
4839   #ifdef REG_PREFETCH
4840   if(rt1[i]==31)
4841   {
4842     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
4843       signed char *i_regmap=i_regs->regmap;
4844       int return_address=start+i*4+8;
4845       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4846     }
4847   }
4848   #endif
4849   #ifdef USE_MINI_HT
4850   if(rs1[i]==31) {
4851     int rh=get_reg(regs[i].regmap,RHASH);
4852     if(rh>=0) do_preload_rhash(rh);
4853   }
4854   #endif
4855   if(rt1[i]!=0&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
4856     rjump_assemble_write_ra(i);
4857     ra_done=1;
4858   }
4859   ds_assemble(i+1,i_regs);
4860   uint64_t bc_unneeded=branch_regs[i].u;
4861   bc_unneeded|=1|(1LL<<rt1[i]);
4862   bc_unneeded&=~(1LL<<rs1[i]);
4863   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4864   load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],CCREG);
4865   if(!ra_done&&rt1[i]!=0)
4866     rjump_assemble_write_ra(i);
4867   cc=get_reg(branch_regs[i].regmap,CCREG);
4868   assert(cc==HOST_CCREG);
4869   (void)cc;
4870   #ifdef USE_MINI_HT
4871   int rh=get_reg(branch_regs[i].regmap,RHASH);
4872   int ht=get_reg(branch_regs[i].regmap,RHTBL);
4873   if(rs1[i]==31) {
4874     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
4875     do_preload_rhtbl(ht);
4876     do_rhash(rs,rh);
4877   }
4878   #endif
4879   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
4880   #ifdef DESTRUCTIVE_WRITEBACK
4881   if((branch_regs[i].dirty>>rs)&1) {
4882     if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
4883       emit_loadreg(rs1[i],rs);
4884     }
4885   }
4886   #endif
4887   #ifdef REG_PREFETCH
4888   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
4889   #endif
4890   #ifdef USE_MINI_HT
4891   if(rs1[i]==31) {
4892     do_miniht_load(ht,rh);
4893   }
4894   #endif
4895   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
4896   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
4897   //assert(adj==0);
4898   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
4899   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
4900   if(itype[i+1]==COP0&&(source[i+1]&0x3f)==0x10)
4901     // special case for RFE
4902     emit_jmp(0);
4903   else
4904     emit_jns(0);
4905   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
4906   #ifdef USE_MINI_HT
4907   if(rs1[i]==31) {
4908     do_miniht_jump(rs,rh,ht);
4909   }
4910   else
4911   #endif
4912   {
4913     do_jump_vaddr(rs);
4914   }
4915   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
4916   if(rt1[i]!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
4917   #endif
4918 }
4919
4920 static void cjump_assemble(int i,struct regstat *i_regs)
4921 {
4922   signed char *i_regmap=i_regs->regmap;
4923   int cc;
4924   int match;
4925   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4926   assem_debug("match=%d\n",match);
4927   int s1l,s2l;
4928   int unconditional=0,nop=0;
4929   int invert=0;
4930   int internal=internal_branch(ba[i]);
4931   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
4932   if(!match) invert=1;
4933   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
4934   if(i>(ba[i]-start)>>2) invert=1;
4935   #endif
4936   #ifdef __aarch64__
4937   invert=1; // because of near cond. branches
4938   #endif
4939
4940   if(ooo[i]) {
4941     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4942     s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4943   }
4944   else {
4945     s1l=get_reg(i_regmap,rs1[i]);
4946     s2l=get_reg(i_regmap,rs2[i]);
4947   }
4948   if(rs1[i]==0&&rs2[i]==0)
4949   {
4950     if(opcode[i]&1) nop=1;
4951     else unconditional=1;
4952     //assert(opcode[i]!=5);
4953     //assert(opcode[i]!=7);
4954     //assert(opcode[i]!=0x15);
4955     //assert(opcode[i]!=0x17);
4956   }
4957   else if(rs1[i]==0)
4958   {
4959     s1l=s2l;
4960     s2l=-1;
4961   }
4962   else if(rs2[i]==0)
4963   {
4964     s2l=-1;
4965   }
4966
4967   if(ooo[i]) {
4968     // Out of order execution (delay slot first)
4969     //printf("OOOE\n");
4970     address_generation(i+1,i_regs,regs[i].regmap_entry);
4971     ds_assemble(i+1,i_regs);
4972     int adj;
4973     uint64_t bc_unneeded=branch_regs[i].u;
4974     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
4975     bc_unneeded|=1;
4976     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4977     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs2[i]);
4978     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
4979     cc=get_reg(branch_regs[i].regmap,CCREG);
4980     assert(cc==HOST_CCREG);
4981     if(unconditional)
4982       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4983     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
4984     //assem_debug("cycle count (adj)\n");
4985     if(unconditional) {
4986       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
4987       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
4988         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
4989         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4990         if(internal)
4991           assem_debug("branch: internal\n");
4992         else
4993           assem_debug("branch: external\n");
4994         if(internal&&is_ds[(ba[i]-start)>>2]) {
4995           ds_assemble_entry(i);
4996         }
4997         else {
4998           add_to_linker(out,ba[i],internal);
4999           emit_jmp(0);
5000         }
5001         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5002         if(((u_int)out)&7) emit_addnop(0);
5003         #endif
5004       }
5005     }
5006     else if(nop) {
5007       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5008       void *jaddr=out;
5009       emit_jns(0);
5010       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5011     }
5012     else {
5013       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5014       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5015       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5016
5017       //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]);
5018       assert(s1l>=0);
5019       if(opcode[i]==4) // BEQ
5020       {
5021         if(s2l>=0) emit_cmp(s1l,s2l);
5022         else emit_test(s1l,s1l);
5023         if(invert){
5024           nottaken=out;
5025           emit_jne(DJT_1);
5026         }else{
5027           add_to_linker(out,ba[i],internal);
5028           emit_jeq(0);
5029         }
5030       }
5031       if(opcode[i]==5) // BNE
5032       {
5033         if(s2l>=0) emit_cmp(s1l,s2l);
5034         else emit_test(s1l,s1l);
5035         if(invert){
5036           nottaken=out;
5037           emit_jeq(DJT_1);
5038         }else{
5039           add_to_linker(out,ba[i],internal);
5040           emit_jne(0);
5041         }
5042       }
5043       if(opcode[i]==6) // BLEZ
5044       {
5045         emit_cmpimm(s1l,1);
5046         if(invert){
5047           nottaken=out;
5048           emit_jge(DJT_1);
5049         }else{
5050           add_to_linker(out,ba[i],internal);
5051           emit_jl(0);
5052         }
5053       }
5054       if(opcode[i]==7) // BGTZ
5055       {
5056         emit_cmpimm(s1l,1);
5057         if(invert){
5058           nottaken=out;
5059           emit_jl(DJT_1);
5060         }else{
5061           add_to_linker(out,ba[i],internal);
5062           emit_jge(0);
5063         }
5064       }
5065       if(invert) {
5066         if(taken) set_jump_target(taken, out);
5067         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5068         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5069           if(adj) {
5070             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5071             add_to_linker(out,ba[i],internal);
5072           }else{
5073             emit_addnop(13);
5074             add_to_linker(out,ba[i],internal*2);
5075           }
5076           emit_jmp(0);
5077         }else
5078         #endif
5079         {
5080           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5081           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5082           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5083           if(internal)
5084             assem_debug("branch: internal\n");
5085           else
5086             assem_debug("branch: external\n");
5087           if(internal&&is_ds[(ba[i]-start)>>2]) {
5088             ds_assemble_entry(i);
5089           }
5090           else {
5091             add_to_linker(out,ba[i],internal);
5092             emit_jmp(0);
5093           }
5094         }
5095         set_jump_target(nottaken, out);
5096       }
5097
5098       if(nottaken1) set_jump_target(nottaken1, out);
5099       if(adj) {
5100         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5101       }
5102     } // (!unconditional)
5103   } // if(ooo)
5104   else
5105   {
5106     // In-order execution (branch first)
5107     //if(likely[i]) printf("IOL\n");
5108     //else
5109     //printf("IOE\n");
5110     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5111     if(!unconditional&&!nop) {
5112       //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]);
5113       assert(s1l>=0);
5114       if((opcode[i]&0x2f)==4) // BEQ
5115       {
5116         if(s2l>=0) emit_cmp(s1l,s2l);
5117         else emit_test(s1l,s1l);
5118         nottaken=out;
5119         emit_jne(DJT_2);
5120       }
5121       if((opcode[i]&0x2f)==5) // BNE
5122       {
5123         if(s2l>=0) emit_cmp(s1l,s2l);
5124         else emit_test(s1l,s1l);
5125         nottaken=out;
5126         emit_jeq(DJT_2);
5127       }
5128       if((opcode[i]&0x2f)==6) // BLEZ
5129       {
5130         emit_cmpimm(s1l,1);
5131         nottaken=out;
5132         emit_jge(DJT_2);
5133       }
5134       if((opcode[i]&0x2f)==7) // BGTZ
5135       {
5136         emit_cmpimm(s1l,1);
5137         nottaken=out;
5138         emit_jl(DJT_2);
5139       }
5140     } // if(!unconditional)
5141     int adj;
5142     uint64_t ds_unneeded=branch_regs[i].u;
5143     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5144     ds_unneeded|=1;
5145     // branch taken
5146     if(!nop) {
5147       if(taken) set_jump_target(taken, out);
5148       assem_debug("1:\n");
5149       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5150       // load regs
5151       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5152       address_generation(i+1,&branch_regs[i],0);
5153       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5154       ds_assemble(i+1,&branch_regs[i]);
5155       cc=get_reg(branch_regs[i].regmap,CCREG);
5156       if(cc==-1) {
5157         emit_loadreg(CCREG,cc=HOST_CCREG);
5158         // CHECK: Is the following instruction (fall thru) allocated ok?
5159       }
5160       assert(cc==HOST_CCREG);
5161       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5162       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5163       assem_debug("cycle count (adj)\n");
5164       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5165       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5166       if(internal)
5167         assem_debug("branch: internal\n");
5168       else
5169         assem_debug("branch: external\n");
5170       if(internal&&is_ds[(ba[i]-start)>>2]) {
5171         ds_assemble_entry(i);
5172       }
5173       else {
5174         add_to_linker(out,ba[i],internal);
5175         emit_jmp(0);
5176       }
5177     }
5178     // branch not taken
5179     if(!unconditional) {
5180       if(nottaken1) set_jump_target(nottaken1, out);
5181       set_jump_target(nottaken, out);
5182       assem_debug("2:\n");
5183       if(!likely[i]) {
5184         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5185         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5186         address_generation(i+1,&branch_regs[i],0);
5187         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5188         ds_assemble(i+1,&branch_regs[i]);
5189       }
5190       cc=get_reg(branch_regs[i].regmap,CCREG);
5191       if(cc==-1&&!likely[i]) {
5192         // Cycle count isn't in a register, temporarily load it then write it out
5193         emit_loadreg(CCREG,HOST_CCREG);
5194         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5195         void *jaddr=out;
5196         emit_jns(0);
5197         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5198         emit_storereg(CCREG,HOST_CCREG);
5199       }
5200       else{
5201         cc=get_reg(i_regmap,CCREG);
5202         assert(cc==HOST_CCREG);
5203         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5204         void *jaddr=out;
5205         emit_jns(0);
5206         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5207       }
5208     }
5209   }
5210 }
5211
5212 static void sjump_assemble(int i,struct regstat *i_regs)
5213 {
5214   signed char *i_regmap=i_regs->regmap;
5215   int cc;
5216   int match;
5217   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5218   assem_debug("smatch=%d\n",match);
5219   int s1l;
5220   int unconditional=0,nevertaken=0;
5221   int invert=0;
5222   int internal=internal_branch(ba[i]);
5223   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5224   if(!match) invert=1;
5225   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5226   if(i>(ba[i]-start)>>2) invert=1;
5227   #endif
5228   #ifdef __aarch64__
5229   invert=1; // because of near cond. branches
5230   #endif
5231
5232   //if(opcode2[i]>=0x10) return; // FIXME (BxxZAL)
5233   //assert(opcode2[i]<0x10||rs1[i]==0); // FIXME (BxxZAL)
5234
5235   if(ooo[i]) {
5236     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5237   }
5238   else {
5239     s1l=get_reg(i_regmap,rs1[i]);
5240   }
5241   if(rs1[i]==0)
5242   {
5243     if(opcode2[i]&1) unconditional=1;
5244     else nevertaken=1;
5245     // These are never taken (r0 is never less than zero)
5246     //assert(opcode2[i]!=0);
5247     //assert(opcode2[i]!=2);
5248     //assert(opcode2[i]!=0x10);
5249     //assert(opcode2[i]!=0x12);
5250   }
5251
5252   if(ooo[i]) {
5253     // Out of order execution (delay slot first)
5254     //printf("OOOE\n");
5255     address_generation(i+1,i_regs,regs[i].regmap_entry);
5256     ds_assemble(i+1,i_regs);
5257     int adj;
5258     uint64_t bc_unneeded=branch_regs[i].u;
5259     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5260     bc_unneeded|=1;
5261     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5262     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs1[i]);
5263     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5264     if(rt1[i]==31) {
5265       int rt,return_address;
5266       rt=get_reg(branch_regs[i].regmap,31);
5267       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]);
5268       if(rt>=0) {
5269         // Save the PC even if the branch is not taken
5270         return_address=start+i*4+8;
5271         emit_movimm(return_address,rt); // PC into link register
5272         #ifdef IMM_PREFETCH
5273         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5274         #endif
5275       }
5276     }
5277     cc=get_reg(branch_regs[i].regmap,CCREG);
5278     assert(cc==HOST_CCREG);
5279     if(unconditional)
5280       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5281     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5282     assem_debug("cycle count (adj)\n");
5283     if(unconditional) {
5284       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5285       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5286         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5287         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5288         if(internal)
5289           assem_debug("branch: internal\n");
5290         else
5291           assem_debug("branch: external\n");
5292         if(internal&&is_ds[(ba[i]-start)>>2]) {
5293           ds_assemble_entry(i);
5294         }
5295         else {
5296           add_to_linker(out,ba[i],internal);
5297           emit_jmp(0);
5298         }
5299         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5300         if(((u_int)out)&7) emit_addnop(0);
5301         #endif
5302       }
5303     }
5304     else if(nevertaken) {
5305       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5306       void *jaddr=out;
5307       emit_jns(0);
5308       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5309     }
5310     else {
5311       void *nottaken = NULL;
5312       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5313       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5314       {
5315         assert(s1l>=0);
5316         if((opcode2[i]&0xf)==0) // BLTZ/BLTZAL
5317         {
5318           emit_test(s1l,s1l);
5319           if(invert){
5320             nottaken=out;
5321             emit_jns(DJT_1);
5322           }else{
5323             add_to_linker(out,ba[i],internal);
5324             emit_js(0);
5325           }
5326         }
5327         if((opcode2[i]&0xf)==1) // BGEZ/BLTZAL
5328         {
5329           emit_test(s1l,s1l);
5330           if(invert){
5331             nottaken=out;
5332             emit_js(DJT_1);
5333           }else{
5334             add_to_linker(out,ba[i],internal);
5335             emit_jns(0);
5336           }
5337         }
5338       }
5339
5340       if(invert) {
5341         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5342         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5343           if(adj) {
5344             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5345             add_to_linker(out,ba[i],internal);
5346           }else{
5347             emit_addnop(13);
5348             add_to_linker(out,ba[i],internal*2);
5349           }
5350           emit_jmp(0);
5351         }else
5352         #endif
5353         {
5354           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5355           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5356           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5357           if(internal)
5358             assem_debug("branch: internal\n");
5359           else
5360             assem_debug("branch: external\n");
5361           if(internal&&is_ds[(ba[i]-start)>>2]) {
5362             ds_assemble_entry(i);
5363           }
5364           else {
5365             add_to_linker(out,ba[i],internal);
5366             emit_jmp(0);
5367           }
5368         }
5369         set_jump_target(nottaken, out);
5370       }
5371
5372       if(adj) {
5373         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5374       }
5375     } // (!unconditional)
5376   } // if(ooo)
5377   else
5378   {
5379     // In-order execution (branch first)
5380     //printf("IOE\n");
5381     void *nottaken = NULL;
5382     if(rt1[i]==31) {
5383       int rt,return_address;
5384       rt=get_reg(branch_regs[i].regmap,31);
5385       if(rt>=0) {
5386         // Save the PC even if the branch is not taken
5387         return_address=start+i*4+8;
5388         emit_movimm(return_address,rt); // PC into link register
5389         #ifdef IMM_PREFETCH
5390         emit_prefetch(hash_table_get(return_address));
5391         #endif
5392       }
5393     }
5394     if(!unconditional) {
5395       //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]);
5396         assert(s1l>=0);
5397         if((opcode2[i]&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5398         {
5399           emit_test(s1l,s1l);
5400           nottaken=out;
5401           emit_jns(DJT_1);
5402         }
5403         if((opcode2[i]&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5404         {
5405           emit_test(s1l,s1l);
5406           nottaken=out;
5407           emit_js(DJT_1);
5408         }
5409     } // if(!unconditional)
5410     int adj;
5411     uint64_t ds_unneeded=branch_regs[i].u;
5412     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5413     ds_unneeded|=1;
5414     // branch taken
5415     if(!nevertaken) {
5416       //assem_debug("1:\n");
5417       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5418       // load regs
5419       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5420       address_generation(i+1,&branch_regs[i],0);
5421       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5422       ds_assemble(i+1,&branch_regs[i]);
5423       cc=get_reg(branch_regs[i].regmap,CCREG);
5424       if(cc==-1) {
5425         emit_loadreg(CCREG,cc=HOST_CCREG);
5426         // CHECK: Is the following instruction (fall thru) allocated ok?
5427       }
5428       assert(cc==HOST_CCREG);
5429       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5430       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5431       assem_debug("cycle count (adj)\n");
5432       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5433       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5434       if(internal)
5435         assem_debug("branch: internal\n");
5436       else
5437         assem_debug("branch: external\n");
5438       if(internal&&is_ds[(ba[i]-start)>>2]) {
5439         ds_assemble_entry(i);
5440       }
5441       else {
5442         add_to_linker(out,ba[i],internal);
5443         emit_jmp(0);
5444       }
5445     }
5446     // branch not taken
5447     if(!unconditional) {
5448       set_jump_target(nottaken, out);
5449       assem_debug("1:\n");
5450       if(!likely[i]) {
5451         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5452         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5453         address_generation(i+1,&branch_regs[i],0);
5454         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5455         ds_assemble(i+1,&branch_regs[i]);
5456       }
5457       cc=get_reg(branch_regs[i].regmap,CCREG);
5458       if(cc==-1&&!likely[i]) {
5459         // Cycle count isn't in a register, temporarily load it then write it out
5460         emit_loadreg(CCREG,HOST_CCREG);
5461         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5462         void *jaddr=out;
5463         emit_jns(0);
5464         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5465         emit_storereg(CCREG,HOST_CCREG);
5466       }
5467       else{
5468         cc=get_reg(i_regmap,CCREG);
5469         assert(cc==HOST_CCREG);
5470         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5471         void *jaddr=out;
5472         emit_jns(0);
5473         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5474       }
5475     }
5476   }
5477 }
5478
5479 static void pagespan_assemble(int i,struct regstat *i_regs)
5480 {
5481   int s1l=get_reg(i_regs->regmap,rs1[i]);
5482   int s2l=get_reg(i_regs->regmap,rs2[i]);
5483   void *taken = NULL;
5484   void *nottaken = NULL;
5485   int unconditional=0;
5486   if(rs1[i]==0)
5487   {
5488     s1l=s2l;
5489     s2l=-1;
5490   }
5491   else if(rs2[i]==0)
5492   {
5493     s2l=-1;
5494   }
5495   int hr=0;
5496   int addr=-1,alt=-1,ntaddr=-1;
5497   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5498   else {
5499     while(hr<HOST_REGS)
5500     {
5501       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5502          (i_regs->regmap[hr]&63)!=rs1[i] &&
5503          (i_regs->regmap[hr]&63)!=rs2[i] )
5504       {
5505         addr=hr++;break;
5506       }
5507       hr++;
5508     }
5509   }
5510   while(hr<HOST_REGS)
5511   {
5512     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5513        (i_regs->regmap[hr]&63)!=rs1[i] &&
5514        (i_regs->regmap[hr]&63)!=rs2[i] )
5515     {
5516       alt=hr++;break;
5517     }
5518     hr++;
5519   }
5520   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
5521   {
5522     while(hr<HOST_REGS)
5523     {
5524       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5525          (i_regs->regmap[hr]&63)!=rs1[i] &&
5526          (i_regs->regmap[hr]&63)!=rs2[i] )
5527       {
5528         ntaddr=hr;break;
5529       }
5530       hr++;
5531     }
5532   }
5533   assert(hr<HOST_REGS);
5534   if((opcode[i]&0x2e)==4||opcode[i]==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5535     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5536   }
5537   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5538   if(opcode[i]==2) // J
5539   {
5540     unconditional=1;
5541   }
5542   if(opcode[i]==3) // JAL
5543   {
5544     // TODO: mini_ht
5545     int rt=get_reg(i_regs->regmap,31);
5546     emit_movimm(start+i*4+8,rt);
5547     unconditional=1;
5548   }
5549   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
5550   {
5551     emit_mov(s1l,addr);
5552     if(opcode2[i]==9) // JALR
5553     {
5554       int rt=get_reg(i_regs->regmap,rt1[i]);
5555       emit_movimm(start+i*4+8,rt);
5556     }
5557   }
5558   if((opcode[i]&0x3f)==4) // BEQ
5559   {
5560     if(rs1[i]==rs2[i])
5561     {
5562       unconditional=1;
5563     }
5564     else
5565     #ifdef HAVE_CMOV_IMM
5566     if(1) {
5567       if(s2l>=0) emit_cmp(s1l,s2l);
5568       else emit_test(s1l,s1l);
5569       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5570     }
5571     else
5572     #endif
5573     {
5574       assert(s1l>=0);
5575       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5576       if(s2l>=0) emit_cmp(s1l,s2l);
5577       else emit_test(s1l,s1l);
5578       emit_cmovne_reg(alt,addr);
5579     }
5580   }
5581   if((opcode[i]&0x3f)==5) // BNE
5582   {
5583     #ifdef HAVE_CMOV_IMM
5584     if(s2l>=0) emit_cmp(s1l,s2l);
5585     else emit_test(s1l,s1l);
5586     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5587     #else
5588     assert(s1l>=0);
5589     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5590     if(s2l>=0) emit_cmp(s1l,s2l);
5591     else emit_test(s1l,s1l);
5592     emit_cmovne_reg(alt,addr);
5593     #endif
5594   }
5595   if((opcode[i]&0x3f)==0x14) // BEQL
5596   {
5597     if(s2l>=0) emit_cmp(s1l,s2l);
5598     else emit_test(s1l,s1l);
5599     if(nottaken) set_jump_target(nottaken, out);
5600     nottaken=out;
5601     emit_jne(0);
5602   }
5603   if((opcode[i]&0x3f)==0x15) // BNEL
5604   {
5605     if(s2l>=0) emit_cmp(s1l,s2l);
5606     else emit_test(s1l,s1l);
5607     nottaken=out;
5608     emit_jeq(0);
5609     if(taken) set_jump_target(taken, out);
5610   }
5611   if((opcode[i]&0x3f)==6) // BLEZ
5612   {
5613     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5614     emit_cmpimm(s1l,1);
5615     emit_cmovl_reg(alt,addr);
5616   }
5617   if((opcode[i]&0x3f)==7) // BGTZ
5618   {
5619     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5620     emit_cmpimm(s1l,1);
5621     emit_cmovl_reg(ntaddr,addr);
5622   }
5623   if((opcode[i]&0x3f)==0x16) // BLEZL
5624   {
5625     assert((opcode[i]&0x3f)!=0x16);
5626   }
5627   if((opcode[i]&0x3f)==0x17) // BGTZL
5628   {
5629     assert((opcode[i]&0x3f)!=0x17);
5630   }
5631   assert(opcode[i]!=1); // BLTZ/BGEZ
5632
5633   //FIXME: Check CSREG
5634   if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
5635     if((source[i]&0x30000)==0) // BC1F
5636     {
5637       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5638       emit_testimm(s1l,0x800000);
5639       emit_cmovne_reg(alt,addr);
5640     }
5641     if((source[i]&0x30000)==0x10000) // BC1T
5642     {
5643       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5644       emit_testimm(s1l,0x800000);
5645       emit_cmovne_reg(alt,addr);
5646     }
5647     if((source[i]&0x30000)==0x20000) // BC1FL
5648     {
5649       emit_testimm(s1l,0x800000);
5650       nottaken=out;
5651       emit_jne(0);
5652     }
5653     if((source[i]&0x30000)==0x30000) // BC1TL
5654     {
5655       emit_testimm(s1l,0x800000);
5656       nottaken=out;
5657       emit_jeq(0);
5658     }
5659   }
5660
5661   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5662   wb_dirtys(regs[i].regmap,regs[i].dirty);
5663   if(likely[i]||unconditional)
5664   {
5665     emit_movimm(ba[i],HOST_BTREG);
5666   }
5667   else if(addr!=HOST_BTREG)
5668   {
5669     emit_mov(addr,HOST_BTREG);
5670   }
5671   void *branch_addr=out;
5672   emit_jmp(0);
5673   int target_addr=start+i*4+5;
5674   void *stub=out;
5675   void *compiled_target_addr=check_addr(target_addr);
5676   emit_extjump_ds(branch_addr, target_addr);
5677   if(compiled_target_addr) {
5678     set_jump_target(branch_addr, compiled_target_addr);
5679     add_link(target_addr,stub);
5680   }
5681   else set_jump_target(branch_addr, stub);
5682   if(likely[i]) {
5683     // Not-taken path
5684     set_jump_target(nottaken, out);
5685     wb_dirtys(regs[i].regmap,regs[i].dirty);
5686     void *branch_addr=out;
5687     emit_jmp(0);
5688     int target_addr=start+i*4+8;
5689     void *stub=out;
5690     void *compiled_target_addr=check_addr(target_addr);
5691     emit_extjump_ds(branch_addr, target_addr);
5692     if(compiled_target_addr) {
5693       set_jump_target(branch_addr, compiled_target_addr);
5694       add_link(target_addr,stub);
5695     }
5696     else set_jump_target(branch_addr, stub);
5697   }
5698 }
5699
5700 // Assemble the delay slot for the above
5701 static void pagespan_ds()
5702 {
5703   assem_debug("initial delay slot:\n");
5704   u_int vaddr=start+1;
5705   u_int page=get_page(vaddr);
5706   u_int vpage=get_vpage(vaddr);
5707   ll_add(jump_dirty+vpage,vaddr,(void *)out);
5708   do_dirty_stub_ds();
5709   ll_add(jump_in+page,vaddr,(void *)out);
5710   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
5711   if(regs[0].regmap[HOST_CCREG]!=CCREG)
5712     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
5713   if(regs[0].regmap[HOST_BTREG]!=BTREG)
5714     emit_writeword(HOST_BTREG,&branch_target);
5715   load_regs(regs[0].regmap_entry,regs[0].regmap,rs1[0],rs2[0]);
5716   address_generation(0,&regs[0],regs[0].regmap_entry);
5717   if(itype[0]==STORE||itype[0]==STORELR||(opcode[0]&0x3b)==0x39||(opcode[0]&0x3b)==0x3a)
5718     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
5719   is_delayslot=0;
5720   switch(itype[0]) {
5721     case ALU:
5722       alu_assemble(0,&regs[0]);break;
5723     case IMM16:
5724       imm16_assemble(0,&regs[0]);break;
5725     case SHIFT:
5726       shift_assemble(0,&regs[0]);break;
5727     case SHIFTIMM:
5728       shiftimm_assemble(0,&regs[0]);break;
5729     case LOAD:
5730       load_assemble(0,&regs[0]);break;
5731     case LOADLR:
5732       loadlr_assemble(0,&regs[0]);break;
5733     case STORE:
5734       store_assemble(0,&regs[0]);break;
5735     case STORELR:
5736       storelr_assemble(0,&regs[0]);break;
5737     case COP0:
5738       cop0_assemble(0,&regs[0]);break;
5739     case COP1:
5740       cop1_assemble(0,&regs[0]);break;
5741     case C1LS:
5742       c1ls_assemble(0,&regs[0]);break;
5743     case COP2:
5744       cop2_assemble(0,&regs[0]);break;
5745     case C2LS:
5746       c2ls_assemble(0,&regs[0]);break;
5747     case C2OP:
5748       c2op_assemble(0,&regs[0]);break;
5749     case MULTDIV:
5750       multdiv_assemble(0,&regs[0]);break;
5751     case MOV:
5752       mov_assemble(0,&regs[0]);break;
5753     case SYSCALL:
5754     case HLECALL:
5755     case INTCALL:
5756     case SPAN:
5757     case UJUMP:
5758     case RJUMP:
5759     case CJUMP:
5760     case SJUMP:
5761       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
5762   }
5763   int btaddr=get_reg(regs[0].regmap,BTREG);
5764   if(btaddr<0) {
5765     btaddr=get_reg(regs[0].regmap,-1);
5766     emit_readword(&branch_target,btaddr);
5767   }
5768   assert(btaddr!=HOST_CCREG);
5769   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
5770 #ifdef HOST_IMM8
5771   host_tempreg_acquire();
5772   emit_movimm(start+4,HOST_TEMPREG);
5773   emit_cmp(btaddr,HOST_TEMPREG);
5774   host_tempreg_release();
5775 #else
5776   emit_cmpimm(btaddr,start+4);
5777 #endif
5778   void *branch = out;
5779   emit_jeq(0);
5780   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
5781   do_jump_vaddr(btaddr);
5782   set_jump_target(branch, out);
5783   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
5784   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
5785 }
5786
5787 // Basic liveness analysis for MIPS registers
5788 void unneeded_registers(int istart,int iend,int r)
5789 {
5790   int i;
5791   uint64_t u,gte_u,b,gte_b;
5792   uint64_t temp_u,temp_gte_u=0;
5793   uint64_t gte_u_unknown=0;
5794   if(new_dynarec_hacks&NDHACK_GTE_UNNEEDED)
5795     gte_u_unknown=~0ll;
5796   if(iend==slen-1) {
5797     u=1;
5798     gte_u=gte_u_unknown;
5799   }else{
5800     //u=unneeded_reg[iend+1];
5801     u=1;
5802     gte_u=gte_unneeded[iend+1];
5803   }
5804
5805   for (i=iend;i>=istart;i--)
5806   {
5807     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
5808     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
5809     {
5810       // If subroutine call, flag return address as a possible branch target
5811       if(rt1[i]==31 && i<slen-2) bt[i+2]=1;
5812
5813       if(ba[i]<start || ba[i]>=(start+slen*4))
5814       {
5815         // Branch out of this block, flush all regs
5816         u=1;
5817         gte_u=gte_u_unknown;
5818         branch_unneeded_reg[i]=u;
5819         // Merge in delay slot
5820         u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5821         u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5822         u|=1;
5823         gte_u|=gte_rt[i+1];
5824         gte_u&=~gte_rs[i+1];
5825         // If branch is "likely" (and conditional)
5826         // then we skip the delay slot on the fall-thru path
5827         if(likely[i]) {
5828           if(i<slen-1) {
5829             u&=unneeded_reg[i+2];
5830             gte_u&=gte_unneeded[i+2];
5831           }
5832           else
5833           {
5834             u=1;
5835             gte_u=gte_u_unknown;
5836           }
5837         }
5838       }
5839       else
5840       {
5841         // Internal branch, flag target
5842         bt[(ba[i]-start)>>2]=1;
5843         if(ba[i]<=start+i*4) {
5844           // Backward branch
5845           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
5846           {
5847             // Unconditional branch
5848             temp_u=1;
5849             temp_gte_u=0;
5850           } else {
5851             // Conditional branch (not taken case)
5852             temp_u=unneeded_reg[i+2];
5853             temp_gte_u&=gte_unneeded[i+2];
5854           }
5855           // Merge in delay slot
5856           temp_u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5857           temp_u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5858           temp_u|=1;
5859           temp_gte_u|=gte_rt[i+1];
5860           temp_gte_u&=~gte_rs[i+1];
5861           // If branch is "likely" (and conditional)
5862           // then we skip the delay slot on the fall-thru path
5863           if(likely[i]) {
5864             if(i<slen-1) {
5865               temp_u&=unneeded_reg[i+2];
5866               temp_gte_u&=gte_unneeded[i+2];
5867             }
5868             else
5869             {
5870               temp_u=1;
5871               temp_gte_u=gte_u_unknown;
5872             }
5873           }
5874           temp_u|=(1LL<<rt1[i])|(1LL<<rt2[i]);
5875           temp_u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5876           temp_u|=1;
5877           temp_gte_u|=gte_rt[i];
5878           temp_gte_u&=~gte_rs[i];
5879           unneeded_reg[i]=temp_u;
5880           gte_unneeded[i]=temp_gte_u;
5881           // Only go three levels deep.  This recursion can take an
5882           // excessive amount of time if there are a lot of nested loops.
5883           if(r<2) {
5884             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
5885           }else{
5886             unneeded_reg[(ba[i]-start)>>2]=1;
5887             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
5888           }
5889         } /*else*/ if(1) {
5890           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
5891           {
5892             // Unconditional branch
5893             u=unneeded_reg[(ba[i]-start)>>2];
5894             gte_u=gte_unneeded[(ba[i]-start)>>2];
5895             branch_unneeded_reg[i]=u;
5896             // Merge in delay slot
5897             u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5898             u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5899             u|=1;
5900             gte_u|=gte_rt[i+1];
5901             gte_u&=~gte_rs[i+1];
5902           } else {
5903             // Conditional branch
5904             b=unneeded_reg[(ba[i]-start)>>2];
5905             gte_b=gte_unneeded[(ba[i]-start)>>2];
5906             branch_unneeded_reg[i]=b;
5907             // Branch delay slot
5908             b|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5909             b&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5910             b|=1;
5911             gte_b|=gte_rt[i+1];
5912             gte_b&=~gte_rs[i+1];
5913             // If branch is "likely" then we skip the
5914             // delay slot on the fall-thru path
5915             if(likely[i]) {
5916               u=b;
5917               gte_u=gte_b;
5918               if(i<slen-1) {
5919                 u&=unneeded_reg[i+2];
5920                 gte_u&=gte_unneeded[i+2];
5921               }
5922             } else {
5923               u&=b;
5924               gte_u&=gte_b;
5925             }
5926             if(i<slen-1) {
5927               branch_unneeded_reg[i]&=unneeded_reg[i+2];
5928             } else {
5929               branch_unneeded_reg[i]=1;
5930             }
5931           }
5932         }
5933       }
5934     }
5935     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
5936     {
5937       // SYSCALL instruction (software interrupt)
5938       u=1;
5939     }
5940     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
5941     {
5942       // ERET instruction (return from interrupt)
5943       u=1;
5944     }
5945     //u=1; // DEBUG
5946     // Written registers are unneeded
5947     u|=1LL<<rt1[i];
5948     u|=1LL<<rt2[i];
5949     gte_u|=gte_rt[i];
5950     // Accessed registers are needed
5951     u&=~(1LL<<rs1[i]);
5952     u&=~(1LL<<rs2[i]);
5953     gte_u&=~gte_rs[i];
5954     if(gte_rs[i]&&rt1[i]&&(unneeded_reg[i+1]&(1ll<<rt1[i])))
5955       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
5956     // Source-target dependencies
5957     // R0 is always unneeded
5958     u|=1;
5959     // Save it
5960     unneeded_reg[i]=u;
5961     gte_unneeded[i]=gte_u;
5962     /*
5963     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
5964     printf("U:");
5965     int r;
5966     for(r=1;r<=CCREG;r++) {
5967       if((unneeded_reg[i]>>r)&1) {
5968         if(r==HIREG) printf(" HI");
5969         else if(r==LOREG) printf(" LO");
5970         else printf(" r%d",r);
5971       }
5972     }
5973     printf("\n");
5974     */
5975   }
5976 }
5977
5978 // Write back dirty registers as soon as we will no longer modify them,
5979 // so that we don't end up with lots of writes at the branches.
5980 void clean_registers(int istart,int iend,int wr)
5981 {
5982   int i;
5983   int r;
5984   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
5985   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
5986   if(iend==slen-1) {
5987     will_dirty_i=will_dirty_next=0;
5988     wont_dirty_i=wont_dirty_next=0;
5989   }else{
5990     will_dirty_i=will_dirty_next=will_dirty[iend+1];
5991     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
5992   }
5993   for (i=iend;i>=istart;i--)
5994   {
5995     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
5996     {
5997       if(ba[i]<start || ba[i]>=(start+slen*4))
5998       {
5999         // Branch out of this block, flush all regs
6000         if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
6001         {
6002           // Unconditional branch
6003           will_dirty_i=0;
6004           wont_dirty_i=0;
6005           // Merge in delay slot (will dirty)
6006           for(r=0;r<HOST_REGS;r++) {
6007             if(r!=EXCLUDE_REG) {
6008               if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6009               if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6010               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6011               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6012               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6013               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6014               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6015               if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6016               if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6017               if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6018               if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6019               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6020               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6021               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6022             }
6023           }
6024         }
6025         else
6026         {
6027           // Conditional branch
6028           will_dirty_i=0;
6029           wont_dirty_i=wont_dirty_next;
6030           // Merge in delay slot (will dirty)
6031           for(r=0;r<HOST_REGS;r++) {
6032             if(r!=EXCLUDE_REG) {
6033               if(!likely[i]) {
6034                 // Might not dirty if likely branch is not taken
6035                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6036                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6037                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6038                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6039                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6040                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6041                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6042                 //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6043                 //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6044                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6045                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6046                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6047                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6048                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6049               }
6050             }
6051           }
6052         }
6053         // Merge in delay slot (wont dirty)
6054         for(r=0;r<HOST_REGS;r++) {
6055           if(r!=EXCLUDE_REG) {
6056             if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6057             if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6058             if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6059             if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6060             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6061             if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6062             if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6063             if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6064             if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6065             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6066           }
6067         }
6068         if(wr) {
6069           #ifndef DESTRUCTIVE_WRITEBACK
6070           branch_regs[i].dirty&=wont_dirty_i;
6071           #endif
6072           branch_regs[i].dirty|=will_dirty_i;
6073         }
6074       }
6075       else
6076       {
6077         // Internal branch
6078         if(ba[i]<=start+i*4) {
6079           // Backward branch
6080           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
6081           {
6082             // Unconditional branch
6083             temp_will_dirty=0;
6084             temp_wont_dirty=0;
6085             // Merge in delay slot (will dirty)
6086             for(r=0;r<HOST_REGS;r++) {
6087               if(r!=EXCLUDE_REG) {
6088                 if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6089                 if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6090                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6091                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6092                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6093                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6094                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6095                 if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6096                 if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6097                 if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6098                 if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6099                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6100                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6101                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6102               }
6103             }
6104           } else {
6105             // Conditional branch (not taken case)
6106             temp_will_dirty=will_dirty_next;
6107             temp_wont_dirty=wont_dirty_next;
6108             // Merge in delay slot (will dirty)
6109             for(r=0;r<HOST_REGS;r++) {
6110               if(r!=EXCLUDE_REG) {
6111                 if(!likely[i]) {
6112                   // Will not dirty if likely branch is not taken
6113                   if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6114                   if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6115                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6116                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6117                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6118                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6119                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6120                   //if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6121                   //if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6122                   if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6123                   if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6124                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6125                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6126                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6127                 }
6128               }
6129             }
6130           }
6131           // Merge in delay slot (wont dirty)
6132           for(r=0;r<HOST_REGS;r++) {
6133             if(r!=EXCLUDE_REG) {
6134               if((regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6135               if((regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6136               if((regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6137               if((regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6138               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6139               if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6140               if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6141               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6142               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6143               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6144             }
6145           }
6146           // Deal with changed mappings
6147           if(i<iend) {
6148             for(r=0;r<HOST_REGS;r++) {
6149               if(r!=EXCLUDE_REG) {
6150                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6151                   temp_will_dirty&=~(1<<r);
6152                   temp_wont_dirty&=~(1<<r);
6153                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6154                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6155                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6156                   } else {
6157                     temp_will_dirty|=1<<r;
6158                     temp_wont_dirty|=1<<r;
6159                   }
6160                 }
6161               }
6162             }
6163           }
6164           if(wr) {
6165             will_dirty[i]=temp_will_dirty;
6166             wont_dirty[i]=temp_wont_dirty;
6167             clean_registers((ba[i]-start)>>2,i-1,0);
6168           }else{
6169             // Limit recursion.  It can take an excessive amount
6170             // of time if there are a lot of nested loops.
6171             will_dirty[(ba[i]-start)>>2]=0;
6172             wont_dirty[(ba[i]-start)>>2]=-1;
6173           }
6174         }
6175         /*else*/ if(1)
6176         {
6177           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
6178           {
6179             // Unconditional branch
6180             will_dirty_i=0;
6181             wont_dirty_i=0;
6182           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6183             for(r=0;r<HOST_REGS;r++) {
6184               if(r!=EXCLUDE_REG) {
6185                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6186                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6187                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6188                 }
6189                 if(branch_regs[i].regmap[r]>=0) {
6190                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6191                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6192                 }
6193               }
6194             }
6195           //}
6196             // Merge in delay slot
6197             for(r=0;r<HOST_REGS;r++) {
6198               if(r!=EXCLUDE_REG) {
6199                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6200                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6201                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6202                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6203                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6204                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6205                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6206                 if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6207                 if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6208                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6209                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6210                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6211                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6212                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6213               }
6214             }
6215           } else {
6216             // Conditional branch
6217             will_dirty_i=will_dirty_next;
6218             wont_dirty_i=wont_dirty_next;
6219           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6220             for(r=0;r<HOST_REGS;r++) {
6221               if(r!=EXCLUDE_REG) {
6222                 signed char target_reg=branch_regs[i].regmap[r];
6223                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6224                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6225                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6226                 }
6227                 else if(target_reg>=0) {
6228                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6229                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6230                 }
6231                 // Treat delay slot as part of branch too
6232                 /*if(regs[i+1].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6233                   will_dirty[i+1]&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6234                   wont_dirty[i+1]|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6235                 }
6236                 else
6237                 {
6238                   will_dirty[i+1]&=~(1<<r);
6239                 }*/
6240               }
6241             }
6242           //}
6243             // Merge in delay slot
6244             for(r=0;r<HOST_REGS;r++) {
6245               if(r!=EXCLUDE_REG) {
6246                 if(!likely[i]) {
6247                   // Might not dirty if likely branch is not taken
6248                   if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6249                   if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6250                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6251                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6252                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6253                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6254                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6255                   //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6256                   //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6257                   if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6258                   if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6259                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6260                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6261                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6262                 }
6263               }
6264             }
6265           }
6266           // Merge in delay slot (won't dirty)
6267           for(r=0;r<HOST_REGS;r++) {
6268             if(r!=EXCLUDE_REG) {
6269               if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6270               if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6271               if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6272               if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6273               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6274               if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6275               if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6276               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6277               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6278               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6279             }
6280           }
6281           if(wr) {
6282             #ifndef DESTRUCTIVE_WRITEBACK
6283             branch_regs[i].dirty&=wont_dirty_i;
6284             #endif
6285             branch_regs[i].dirty|=will_dirty_i;
6286           }
6287         }
6288       }
6289     }
6290     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6291     {
6292       // SYSCALL instruction (software interrupt)
6293       will_dirty_i=0;
6294       wont_dirty_i=0;
6295     }
6296     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6297     {
6298       // ERET instruction (return from interrupt)
6299       will_dirty_i=0;
6300       wont_dirty_i=0;
6301     }
6302     will_dirty_next=will_dirty_i;
6303     wont_dirty_next=wont_dirty_i;
6304     for(r=0;r<HOST_REGS;r++) {
6305       if(r!=EXCLUDE_REG) {
6306         if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6307         if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6308         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6309         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6310         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6311         if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6312         if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6313         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6314         if(i>istart) {
6315           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP)
6316           {
6317             // Don't store a register immediately after writing it,
6318             // may prevent dual-issue.
6319             if((regs[i].regmap[r]&63)==rt1[i-1]) wont_dirty_i|=1<<r;
6320             if((regs[i].regmap[r]&63)==rt2[i-1]) wont_dirty_i|=1<<r;
6321           }
6322         }
6323       }
6324     }
6325     // Save it
6326     will_dirty[i]=will_dirty_i;
6327     wont_dirty[i]=wont_dirty_i;
6328     // Mark registers that won't be dirtied as not dirty
6329     if(wr) {
6330       /*printf("wr (%d,%d) %x will:",istart,iend,start+i*4);
6331       for(r=0;r<HOST_REGS;r++) {
6332         if((will_dirty_i>>r)&1) {
6333           printf(" r%d",r);
6334         }
6335       }
6336       printf("\n");*/
6337
6338       //if(i==istart||(itype[i-1]!=RJUMP&&itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP)) {
6339         regs[i].dirty|=will_dirty_i;
6340         #ifndef DESTRUCTIVE_WRITEBACK
6341         regs[i].dirty&=wont_dirty_i;
6342         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6343         {
6344           if(i<iend-1&&itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000) {
6345             for(r=0;r<HOST_REGS;r++) {
6346               if(r!=EXCLUDE_REG) {
6347                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6348                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6349                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6350               }
6351             }
6352           }
6353         }
6354         else
6355         {
6356           if(i<iend) {
6357             for(r=0;r<HOST_REGS;r++) {
6358               if(r!=EXCLUDE_REG) {
6359                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6360                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6361                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6362               }
6363             }
6364           }
6365         }
6366         #endif
6367       //}
6368     }
6369     // Deal with changed mappings
6370     temp_will_dirty=will_dirty_i;
6371     temp_wont_dirty=wont_dirty_i;
6372     for(r=0;r<HOST_REGS;r++) {
6373       if(r!=EXCLUDE_REG) {
6374         int nr;
6375         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6376           if(wr) {
6377             #ifndef DESTRUCTIVE_WRITEBACK
6378             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6379             #endif
6380             regs[i].wasdirty|=will_dirty_i&(1<<r);
6381           }
6382         }
6383         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6384           // Register moved to a different register
6385           will_dirty_i&=~(1<<r);
6386           wont_dirty_i&=~(1<<r);
6387           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6388           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6389           if(wr) {
6390             #ifndef DESTRUCTIVE_WRITEBACK
6391             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6392             #endif
6393             regs[i].wasdirty|=will_dirty_i&(1<<r);
6394           }
6395         }
6396         else {
6397           will_dirty_i&=~(1<<r);
6398           wont_dirty_i&=~(1<<r);
6399           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6400             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6401             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6402           } else {
6403             wont_dirty_i|=1<<r;
6404             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6405           }
6406         }
6407       }
6408     }
6409   }
6410 }
6411
6412 #ifdef DISASM
6413   /* disassembly */
6414 void disassemble_inst(int i)
6415 {
6416     if (bt[i]) printf("*"); else printf(" ");
6417     switch(itype[i]) {
6418       case UJUMP:
6419         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6420       case CJUMP:
6421         printf (" %x: %s r%d,r%d,%8x\n",start+i*4,insn[i],rs1[i],rs2[i],i?start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14):*ba);break;
6422       case SJUMP:
6423         printf (" %x: %s r%d,%8x\n",start+i*4,insn[i],rs1[i],start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14));break;
6424       case RJUMP:
6425         if (opcode[i]==0x9&&rt1[i]!=31)
6426           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i]);
6427         else
6428           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6429         break;
6430       case SPAN:
6431         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],rs1[i],rs2[i],ba[i]);break;
6432       case IMM16:
6433         if(opcode[i]==0xf) //LUI
6434           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],rt1[i],imm[i]&0xffff);
6435         else
6436           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6437         break;
6438       case LOAD:
6439       case LOADLR:
6440         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6441         break;
6442       case STORE:
6443       case STORELR:
6444         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rs2[i],rs1[i],imm[i]);
6445         break;
6446       case ALU:
6447       case SHIFT:
6448         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i],rs2[i]);
6449         break;
6450       case MULTDIV:
6451         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rs1[i],rs2[i]);
6452         break;
6453       case SHIFTIMM:
6454         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6455         break;
6456       case MOV:
6457         if((opcode2[i]&0x1d)==0x10)
6458           printf (" %x: %s r%d\n",start+i*4,insn[i],rt1[i]);
6459         else if((opcode2[i]&0x1d)==0x11)
6460           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6461         else
6462           printf (" %x: %s\n",start+i*4,insn[i]);
6463         break;
6464       case COP0:
6465         if(opcode2[i]==0)
6466           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC0
6467         else if(opcode2[i]==4)
6468           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC0
6469         else printf (" %x: %s\n",start+i*4,insn[i]);
6470         break;
6471       case COP1:
6472         if(opcode2[i]<3)
6473           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC1
6474         else if(opcode2[i]>3)
6475           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC1
6476         else printf (" %x: %s\n",start+i*4,insn[i]);
6477         break;
6478       case COP2:
6479         if(opcode2[i]<3)
6480           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC2
6481         else if(opcode2[i]>3)
6482           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC2
6483         else printf (" %x: %s\n",start+i*4,insn[i]);
6484         break;
6485       case C1LS:
6486         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6487         break;
6488       case C2LS:
6489         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6490         break;
6491       case INTCALL:
6492         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6493         break;
6494       default:
6495         //printf (" %s %8x\n",insn[i],source[i]);
6496         printf (" %x: %s\n",start+i*4,insn[i]);
6497     }
6498 }
6499 #else
6500 static void disassemble_inst(int i) {}
6501 #endif // DISASM
6502
6503 #define DRC_TEST_VAL 0x74657374
6504
6505 static void new_dynarec_test(void)
6506 {
6507   int (*testfunc)(void);
6508   void *beginning;
6509   int ret[2];
6510   size_t i;
6511
6512   // check structure linkage
6513   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6514   {
6515     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6516   }
6517
6518   SysPrintf("testing if we can run recompiled code...\n");
6519   ((volatile u_int *)out)[0]++; // make cache dirty
6520
6521   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6522     out = ndrc->translation_cache;
6523     beginning = start_block();
6524     emit_movimm(DRC_TEST_VAL + i, 0); // test
6525     emit_ret();
6526     literal_pool(0);
6527     end_block(beginning);
6528     testfunc = beginning;
6529     ret[i] = testfunc();
6530   }
6531
6532   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6533     SysPrintf("test passed.\n");
6534   else
6535     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6536   out = ndrc->translation_cache;
6537 }
6538
6539 // clear the state completely, instead of just marking
6540 // things invalid like invalidate_all_pages() does
6541 void new_dynarec_clear_full(void)
6542 {
6543   int n;
6544   out = ndrc->translation_cache;
6545   memset(invalid_code,1,sizeof(invalid_code));
6546   memset(hash_table,0xff,sizeof(hash_table));
6547   memset(mini_ht,-1,sizeof(mini_ht));
6548   memset(restore_candidate,0,sizeof(restore_candidate));
6549   memset(shadow,0,sizeof(shadow));
6550   copy=shadow;
6551   expirep=16384; // Expiry pointer, +2 blocks
6552   pending_exception=0;
6553   literalcount=0;
6554   stop_after_jal=0;
6555   inv_code_start=inv_code_end=~0;
6556   // TLB
6557   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6558   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6559   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6560 }
6561
6562 void new_dynarec_init(void)
6563 {
6564   SysPrintf("Init new dynarec\n");
6565
6566 #ifdef BASE_ADDR_DYNAMIC
6567   #ifdef VITA
6568   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6569   if (sceBlock < 0)
6570     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6571   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6572   if (ret < 0)
6573     SysPrintf("sceKernelGetMemBlockBase failed\n");
6574   #else
6575   uintptr_t desired_addr = 0;
6576   #ifdef __ELF__
6577   extern char _end;
6578   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6579   #endif
6580   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6581             PROT_READ | PROT_WRITE | PROT_EXEC,
6582             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6583   if (ndrc == MAP_FAILED) {
6584     SysPrintf("mmap() failed: %s\n", strerror(errno));
6585     abort();
6586   }
6587   #endif
6588 #else
6589   #ifndef NO_WRITE_EXEC
6590   // not all systems allow execute in data segment by default
6591   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6592                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6593     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6594   #endif
6595 #endif
6596   out = ndrc->translation_cache;
6597   cycle_multiplier=200;
6598   new_dynarec_clear_full();
6599 #ifdef HOST_IMM8
6600   // Copy this into local area so we don't have to put it in every literal pool
6601   invc_ptr=invalid_code;
6602 #endif
6603   arch_init();
6604   new_dynarec_test();
6605 #ifndef RAM_FIXED
6606   ram_offset=(uintptr_t)rdram-0x80000000;
6607 #endif
6608   if (ram_offset!=0)
6609     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6610 }
6611
6612 void new_dynarec_cleanup(void)
6613 {
6614   int n;
6615 #ifdef BASE_ADDR_DYNAMIC
6616   #ifdef VITA
6617   sceKernelFreeMemBlock(sceBlock);
6618   sceBlock = -1;
6619   #else
6620   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6621     SysPrintf("munmap() failed\n");
6622   #endif
6623 #endif
6624   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6625   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6626   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6627   #ifdef ROM_COPY
6628   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6629   #endif
6630 }
6631
6632 static u_int *get_source_start(u_int addr, u_int *limit)
6633 {
6634   if (addr < 0x00200000 ||
6635     (0xa0000000 <= addr && addr < 0xa0200000)) {
6636     // used for BIOS calls mostly?
6637     *limit = (addr&0xa0000000)|0x00200000;
6638     return (u_int *)(rdram + (addr&0x1fffff));
6639   }
6640   else if (!Config.HLE && (
6641     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6642     (0xbfc00000 <= addr && addr < 0xbfc80000))) {
6643     // BIOS
6644     *limit = (addr & 0xfff00000) | 0x80000;
6645     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6646   }
6647   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6648     *limit = (addr & 0x80600000) + 0x00200000;
6649     return (u_int *)(rdram + (addr&0x1fffff));
6650   }
6651   return NULL;
6652 }
6653
6654 static u_int scan_for_ret(u_int addr)
6655 {
6656   u_int limit = 0;
6657   u_int *mem;
6658
6659   mem = get_source_start(addr, &limit);
6660   if (mem == NULL)
6661     return addr;
6662
6663   if (limit > addr + 0x1000)
6664     limit = addr + 0x1000;
6665   for (; addr < limit; addr += 4, mem++) {
6666     if (*mem == 0x03e00008) // jr $ra
6667       return addr + 8;
6668   }
6669   return addr;
6670 }
6671
6672 struct savestate_block {
6673   uint32_t addr;
6674   uint32_t regflags;
6675 };
6676
6677 static int addr_cmp(const void *p1_, const void *p2_)
6678 {
6679   const struct savestate_block *p1 = p1_, *p2 = p2_;
6680   return p1->addr - p2->addr;
6681 }
6682
6683 int new_dynarec_save_blocks(void *save, int size)
6684 {
6685   struct savestate_block *blocks = save;
6686   int maxcount = size / sizeof(blocks[0]);
6687   struct savestate_block tmp_blocks[1024];
6688   struct ll_entry *head;
6689   int p, s, d, o, bcnt;
6690   u_int addr;
6691
6692   o = 0;
6693   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
6694     bcnt = 0;
6695     for (head = jump_in[p]; head != NULL; head = head->next) {
6696       tmp_blocks[bcnt].addr = head->vaddr;
6697       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
6698       bcnt++;
6699     }
6700     if (bcnt < 1)
6701       continue;
6702     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6703
6704     addr = tmp_blocks[0].addr;
6705     for (s = d = 0; s < bcnt; s++) {
6706       if (tmp_blocks[s].addr < addr)
6707         continue;
6708       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6709         tmp_blocks[d++] = tmp_blocks[s];
6710       addr = scan_for_ret(tmp_blocks[s].addr);
6711     }
6712
6713     if (o + d > maxcount)
6714       d = maxcount - o;
6715     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
6716     o += d;
6717   }
6718
6719   return o * sizeof(blocks[0]);
6720 }
6721
6722 void new_dynarec_load_blocks(const void *save, int size)
6723 {
6724   const struct savestate_block *blocks = save;
6725   int count = size / sizeof(blocks[0]);
6726   u_int regs_save[32];
6727   uint32_t f;
6728   int i, b;
6729
6730   get_addr(psxRegs.pc);
6731
6732   // change GPRs for speculation to at least partially work..
6733   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6734   for (i = 1; i < 32; i++)
6735     psxRegs.GPR.r[i] = 0x80000000;
6736
6737   for (b = 0; b < count; b++) {
6738     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6739       if (f & 1)
6740         psxRegs.GPR.r[i] = 0x1f800000;
6741     }
6742
6743     get_addr(blocks[b].addr);
6744
6745     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6746       if (f & 1)
6747         psxRegs.GPR.r[i] = 0x80000000;
6748     }
6749   }
6750
6751   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6752 }
6753
6754 int new_recompile_block(u_int addr)
6755 {
6756   u_int pagelimit = 0;
6757   u_int state_rflags = 0;
6758   int i;
6759
6760   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
6761   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
6762   //if(debug)
6763   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
6764
6765   // this is just for speculation
6766   for (i = 1; i < 32; i++) {
6767     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
6768       state_rflags |= 1 << i;
6769   }
6770
6771   start = (u_int)addr&~3;
6772   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
6773   new_dynarec_did_compile=1;
6774   if (Config.HLE && start == 0x80001000) // hlecall
6775   {
6776     // XXX: is this enough? Maybe check hleSoftCall?
6777     void *beginning=start_block();
6778     u_int page=get_page(start);
6779
6780     invalid_code[start>>12]=0;
6781     emit_movimm(start,0);
6782     emit_writeword(0,&pcaddr);
6783     emit_far_jump(new_dyna_leave);
6784     literal_pool(0);
6785     end_block(beginning);
6786     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
6787     return 0;
6788   }
6789
6790   source = get_source_start(start, &pagelimit);
6791   if (source == NULL) {
6792     SysPrintf("Compile at bogus memory address: %08x\n", addr);
6793     abort();
6794   }
6795
6796   /* Pass 1: disassemble */
6797   /* Pass 2: register dependencies, branch targets */
6798   /* Pass 3: register allocation */
6799   /* Pass 4: branch dependencies */
6800   /* Pass 5: pre-alloc */
6801   /* Pass 6: optimize clean/dirty state */
6802   /* Pass 7: flag 32-bit registers */
6803   /* Pass 8: assembly */
6804   /* Pass 9: linker */
6805   /* Pass 10: garbage collection / free memory */
6806
6807   int j;
6808   int done=0;
6809   unsigned int type,op,op2;
6810
6811   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
6812
6813   /* Pass 1 disassembly */
6814
6815   for(i=0;!done;i++) {
6816     bt[i]=0;likely[i]=0;ooo[i]=0;op2=0;
6817     minimum_free_regs[i]=0;
6818     opcode[i]=op=source[i]>>26;
6819     switch(op)
6820     {
6821       case 0x00: strcpy(insn[i],"special"); type=NI;
6822         op2=source[i]&0x3f;
6823         switch(op2)
6824         {
6825           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
6826           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
6827           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
6828           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
6829           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
6830           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
6831           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
6832           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
6833           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
6834           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
6835           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
6836           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
6837           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
6838           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
6839           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
6840           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
6841           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
6842           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
6843           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
6844           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
6845           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
6846           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
6847           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
6848           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
6849           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
6850           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
6851           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
6852           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
6853           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
6854           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
6855           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
6856           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
6857           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
6858           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
6859           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
6860 #if 0
6861           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
6862           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
6863           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
6864           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
6865           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
6866           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
6867           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
6868           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
6869           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
6870           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
6871           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
6872           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
6873           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
6874           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
6875           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
6876           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
6877           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
6878 #endif
6879         }
6880         break;
6881       case 0x01: strcpy(insn[i],"regimm"); type=NI;
6882         op2=(source[i]>>16)&0x1f;
6883         switch(op2)
6884         {
6885           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
6886           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
6887           case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
6888           case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
6889           case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
6890           case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
6891           case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
6892           case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
6893           case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
6894           case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
6895           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
6896           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
6897           case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
6898           case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
6899         }
6900         break;
6901       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
6902       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
6903       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
6904       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
6905       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
6906       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
6907       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
6908       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
6909       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
6910       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
6911       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
6912       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
6913       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
6914       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
6915       case 0x10: strcpy(insn[i],"cop0"); type=NI;
6916         op2=(source[i]>>21)&0x1f;
6917         switch(op2)
6918         {
6919           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
6920           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
6921           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
6922           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
6923           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
6924         }
6925         break;
6926       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
6927         op2=(source[i]>>21)&0x1f;
6928         break;
6929 #if 0
6930       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
6931       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
6932       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
6933       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
6934       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
6935       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
6936       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
6937       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
6938 #endif
6939       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
6940       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
6941       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
6942       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
6943       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
6944       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
6945       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
6946 #if 0
6947       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
6948 #endif
6949       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
6950       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
6951       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
6952       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
6953 #if 0
6954       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
6955       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
6956 #endif
6957       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
6958       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
6959       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
6960       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
6961 #if 0
6962       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
6963       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
6964       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
6965 #endif
6966       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
6967       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
6968 #if 0
6969       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
6970       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
6971       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
6972 #endif
6973       case 0x12: strcpy(insn[i],"COP2"); type=NI;
6974         op2=(source[i]>>21)&0x1f;
6975         //if (op2 & 0x10)
6976         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
6977           if (gte_handlers[source[i]&0x3f]!=NULL) {
6978             if (gte_regnames[source[i]&0x3f]!=NULL)
6979               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
6980             else
6981               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
6982             type=C2OP;
6983           }
6984         }
6985         else switch(op2)
6986         {
6987           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
6988           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
6989           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
6990           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
6991         }
6992         break;
6993       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
6994       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
6995       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
6996       default: strcpy(insn[i],"???"); type=NI;
6997         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
6998         break;
6999     }
7000     itype[i]=type;
7001     opcode2[i]=op2;
7002     /* Get registers/immediates */
7003     lt1[i]=0;
7004     dep1[i]=0;
7005     dep2[i]=0;
7006     gte_rs[i]=gte_rt[i]=0;
7007     switch(type) {
7008       case LOAD:
7009         rs1[i]=(source[i]>>21)&0x1f;
7010         rs2[i]=0;
7011         rt1[i]=(source[i]>>16)&0x1f;
7012         rt2[i]=0;
7013         imm[i]=(short)source[i];
7014         break;
7015       case STORE:
7016       case STORELR:
7017         rs1[i]=(source[i]>>21)&0x1f;
7018         rs2[i]=(source[i]>>16)&0x1f;
7019         rt1[i]=0;
7020         rt2[i]=0;
7021         imm[i]=(short)source[i];
7022         break;
7023       case LOADLR:
7024         // LWL/LWR only load part of the register,
7025         // therefore the target register must be treated as a source too
7026         rs1[i]=(source[i]>>21)&0x1f;
7027         rs2[i]=(source[i]>>16)&0x1f;
7028         rt1[i]=(source[i]>>16)&0x1f;
7029         rt2[i]=0;
7030         imm[i]=(short)source[i];
7031         if(op==0x26) dep1[i]=rt1[i]; // LWR
7032         break;
7033       case IMM16:
7034         if (op==0x0f) rs1[i]=0; // LUI instruction has no source register
7035         else rs1[i]=(source[i]>>21)&0x1f;
7036         rs2[i]=0;
7037         rt1[i]=(source[i]>>16)&0x1f;
7038         rt2[i]=0;
7039         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7040           imm[i]=(unsigned short)source[i];
7041         }else{
7042           imm[i]=(short)source[i];
7043         }
7044         if(op==0x0d||op==0x0e) dep1[i]=rs1[i]; // ORI/XORI
7045         break;
7046       case UJUMP:
7047         rs1[i]=0;
7048         rs2[i]=0;
7049         rt1[i]=0;
7050         rt2[i]=0;
7051         // The JAL instruction writes to r31.
7052         if (op&1) {
7053           rt1[i]=31;
7054         }
7055         rs2[i]=CCREG;
7056         break;
7057       case RJUMP:
7058         rs1[i]=(source[i]>>21)&0x1f;
7059         rs2[i]=0;
7060         rt1[i]=0;
7061         rt2[i]=0;
7062         // The JALR instruction writes to rd.
7063         if (op2&1) {
7064           rt1[i]=(source[i]>>11)&0x1f;
7065         }
7066         rs2[i]=CCREG;
7067         break;
7068       case CJUMP:
7069         rs1[i]=(source[i]>>21)&0x1f;
7070         rs2[i]=(source[i]>>16)&0x1f;
7071         rt1[i]=0;
7072         rt2[i]=0;
7073         if(op&2) { // BGTZ/BLEZ
7074           rs2[i]=0;
7075         }
7076         likely[i]=op>>4;
7077         break;
7078       case SJUMP:
7079         rs1[i]=(source[i]>>21)&0x1f;
7080         rs2[i]=CCREG;
7081         rt1[i]=0;
7082         rt2[i]=0;
7083         if(op2&0x10) { // BxxAL
7084           rt1[i]=31;
7085           // NOTE: If the branch is not taken, r31 is still overwritten
7086         }
7087         likely[i]=(op2&2)>>1;
7088         break;
7089       case ALU:
7090         rs1[i]=(source[i]>>21)&0x1f; // source
7091         rs2[i]=(source[i]>>16)&0x1f; // subtract amount
7092         rt1[i]=(source[i]>>11)&0x1f; // destination
7093         rt2[i]=0;
7094         if(op2>=0x24&&op2<=0x27) { // AND/OR/XOR/NOR
7095           dep1[i]=rs1[i];dep2[i]=rs2[i];
7096         }
7097         else if(op2>=0x2c&&op2<=0x2f) { // DADD/DSUB
7098           dep1[i]=rs1[i];dep2[i]=rs2[i];
7099         }
7100         break;
7101       case MULTDIV:
7102         rs1[i]=(source[i]>>21)&0x1f; // source
7103         rs2[i]=(source[i]>>16)&0x1f; // divisor
7104         rt1[i]=HIREG;
7105         rt2[i]=LOREG;
7106         break;
7107       case MOV:
7108         rs1[i]=0;
7109         rs2[i]=0;
7110         rt1[i]=0;
7111         rt2[i]=0;
7112         if(op2==0x10) rs1[i]=HIREG; // MFHI
7113         if(op2==0x11) rt1[i]=HIREG; // MTHI
7114         if(op2==0x12) rs1[i]=LOREG; // MFLO
7115         if(op2==0x13) rt1[i]=LOREG; // MTLO
7116         if((op2&0x1d)==0x10) rt1[i]=(source[i]>>11)&0x1f; // MFxx
7117         if((op2&0x1d)==0x11) rs1[i]=(source[i]>>21)&0x1f; // MTxx
7118         dep1[i]=rs1[i];
7119         break;
7120       case SHIFT:
7121         rs1[i]=(source[i]>>16)&0x1f; // target of shift
7122         rs2[i]=(source[i]>>21)&0x1f; // shift amount
7123         rt1[i]=(source[i]>>11)&0x1f; // destination
7124         rt2[i]=0;
7125         break;
7126       case SHIFTIMM:
7127         rs1[i]=(source[i]>>16)&0x1f;
7128         rs2[i]=0;
7129         rt1[i]=(source[i]>>11)&0x1f;
7130         rt2[i]=0;
7131         imm[i]=(source[i]>>6)&0x1f;
7132         // DSxx32 instructions
7133         if(op2>=0x3c) imm[i]|=0x20;
7134         break;
7135       case COP0:
7136         rs1[i]=0;
7137         rs2[i]=0;
7138         rt1[i]=0;
7139         rt2[i]=0;
7140         if(op2==0||op2==2) rt1[i]=(source[i]>>16)&0x1F; // MFC0/CFC0
7141         if(op2==4||op2==6) rs1[i]=(source[i]>>16)&0x1F; // MTC0/CTC0
7142         if(op2==4&&((source[i]>>11)&0x1f)==12) rt2[i]=CSREG; // Status
7143         if(op2==16) if((source[i]&0x3f)==0x18) rs2[i]=CCREG; // ERET
7144         break;
7145       case COP1:
7146         rs1[i]=0;
7147         rs2[i]=0;
7148         rt1[i]=0;
7149         rt2[i]=0;
7150         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7151         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7152         rs2[i]=CSREG;
7153         break;
7154       case COP2:
7155         rs1[i]=0;
7156         rs2[i]=0;
7157         rt1[i]=0;
7158         rt2[i]=0;
7159         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC2/CFC2
7160         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC2/CTC2
7161         rs2[i]=CSREG;
7162         int gr=(source[i]>>11)&0x1F;
7163         switch(op2)
7164         {
7165           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7166           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7167           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7168           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7169         }
7170         break;
7171       case C1LS:
7172         rs1[i]=(source[i]>>21)&0x1F;
7173         rs2[i]=CSREG;
7174         rt1[i]=0;
7175         rt2[i]=0;
7176         imm[i]=(short)source[i];
7177         break;
7178       case C2LS:
7179         rs1[i]=(source[i]>>21)&0x1F;
7180         rs2[i]=0;
7181         rt1[i]=0;
7182         rt2[i]=0;
7183         imm[i]=(short)source[i];
7184         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7185         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7186         break;
7187       case C2OP:
7188         rs1[i]=0;
7189         rs2[i]=0;
7190         rt1[i]=0;
7191         rt2[i]=0;
7192         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7193         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7194         gte_rt[i]|=1ll<<63; // every op changes flags
7195         if((source[i]&0x3f)==GTE_MVMVA) {
7196           int v = (source[i] >> 15) & 3;
7197           gte_rs[i]&=~0xe3fll;
7198           if(v==3) gte_rs[i]|=0xe00ll;
7199           else gte_rs[i]|=3ll<<(v*2);
7200         }
7201         break;
7202       case SYSCALL:
7203       case HLECALL:
7204       case INTCALL:
7205         rs1[i]=CCREG;
7206         rs2[i]=0;
7207         rt1[i]=0;
7208         rt2[i]=0;
7209         break;
7210       default:
7211         rs1[i]=0;
7212         rs2[i]=0;
7213         rt1[i]=0;
7214         rt2[i]=0;
7215     }
7216     /* Calculate branch target addresses */
7217     if(type==UJUMP)
7218       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7219     else if(type==CJUMP&&rs1[i]==rs2[i]&&(op&1))
7220       ba[i]=start+i*4+8; // Ignore never taken branch
7221     else if(type==SJUMP&&rs1[i]==0&&!(op2&1))
7222       ba[i]=start+i*4+8; // Ignore never taken branch
7223     else if(type==CJUMP||type==SJUMP)
7224       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7225     else ba[i]=-1;
7226     if(i>0&&(itype[i-1]==RJUMP||itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)) {
7227       int do_in_intrp=0;
7228       // branch in delay slot?
7229       if(type==RJUMP||type==UJUMP||type==CJUMP||type==SJUMP) {
7230         // don't handle first branch and call interpreter if it's hit
7231         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7232         do_in_intrp=1;
7233       }
7234       // basic load delay detection
7235       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&rt1[i]!=0) {
7236         int t=(ba[i-1]-start)/4;
7237         if(0 <= t && t < i &&(rt1[i]==rs1[t]||rt1[i]==rs2[t])&&itype[t]!=CJUMP&&itype[t]!=SJUMP) {
7238           // jump target wants DS result - potential load delay effect
7239           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7240           do_in_intrp=1;
7241           bt[t+1]=1; // expected return from interpreter
7242         }
7243         else if(i>=2&&rt1[i-2]==2&&rt1[i]==2&&rs1[i]!=2&&rs2[i]!=2&&rs1[i-1]!=2&&rs2[i-1]!=2&&
7244               !(i>=3&&(itype[i-3]==RJUMP||itype[i-3]==UJUMP||itype[i-3]==CJUMP||itype[i-3]==SJUMP))) {
7245           // v0 overwrite like this is a sign of trouble, bail out
7246           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7247           do_in_intrp=1;
7248         }
7249       }
7250       if(do_in_intrp) {
7251         rs1[i-1]=CCREG;
7252         rs2[i-1]=rt1[i-1]=rt2[i-1]=0;
7253         ba[i-1]=-1;
7254         itype[i-1]=INTCALL;
7255         done=2;
7256         i--; // don't compile the DS
7257       }
7258     }
7259     /* Is this the end of the block? */
7260     if(i>0&&(itype[i-1]==UJUMP||itype[i-1]==RJUMP||(source[i-1]>>16)==0x1000)) {
7261       if(rt1[i-1]==0) { // Continue past subroutine call (JAL)
7262         done=2;
7263       }
7264       else {
7265         if(stop_after_jal) done=1;
7266         // Stop on BREAK
7267         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7268       }
7269       // Don't recompile stuff that's already compiled
7270       if(check_addr(start+i*4+4)) done=1;
7271       // Don't get too close to the limit
7272       if(i>MAXBLOCK/2) done=1;
7273     }
7274     if(itype[i]==SYSCALL&&stop_after_jal) done=1;
7275     if(itype[i]==HLECALL||itype[i]==INTCALL) done=2;
7276     if(done==2) {
7277       // Does the block continue due to a branch?
7278       for(j=i-1;j>=0;j--)
7279       {
7280         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7281         if(ba[j]==start+i*4+4) done=j=0;
7282         if(ba[j]==start+i*4+8) done=j=0;
7283       }
7284     }
7285     //assert(i<MAXBLOCK-1);
7286     if(start+i*4==pagelimit-4) done=1;
7287     assert(start+i*4<pagelimit);
7288     if (i==MAXBLOCK-1) done=1;
7289     // Stop if we're compiling junk
7290     if(itype[i]==NI&&opcode[i]==0x11) {
7291       done=stop_after_jal=1;
7292       SysPrintf("Disabled speculative precompilation\n");
7293     }
7294   }
7295   slen=i;
7296   if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP||itype[i-1]==RJUMP) {
7297     if(start+i*4==pagelimit) {
7298       itype[i-1]=SPAN;
7299     }
7300   }
7301   assert(slen>0);
7302
7303   /* Pass 2 - Register dependencies and branch targets */
7304
7305   unneeded_registers(0,slen-1,0);
7306
7307   /* Pass 3 - Register allocation */
7308
7309   struct regstat current; // Current register allocations/status
7310   current.dirty=0;
7311   current.u=unneeded_reg[0];
7312   clear_all_regs(current.regmap);
7313   alloc_reg(&current,0,CCREG);
7314   dirty_reg(&current,CCREG);
7315   current.isconst=0;
7316   current.wasconst=0;
7317   current.waswritten=0;
7318   int ds=0;
7319   int cc=0;
7320   int hr=-1;
7321
7322   if((u_int)addr&1) {
7323     // First instruction is delay slot
7324     cc=-1;
7325     bt[1]=1;
7326     ds=1;
7327     unneeded_reg[0]=1;
7328     current.regmap[HOST_BTREG]=BTREG;
7329   }
7330
7331   for(i=0;i<slen;i++)
7332   {
7333     if(bt[i])
7334     {
7335       int hr;
7336       for(hr=0;hr<HOST_REGS;hr++)
7337       {
7338         // Is this really necessary?
7339         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7340       }
7341       current.isconst=0;
7342       current.waswritten=0;
7343     }
7344
7345     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7346     regs[i].wasconst=current.isconst;
7347     regs[i].wasdirty=current.dirty;
7348     regs[i].loadedconst=0;
7349     if(itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP&&itype[i]!=RJUMP) {
7350       if(i+1<slen) {
7351         current.u=unneeded_reg[i+1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7352         current.u|=1;
7353       } else {
7354         current.u=1;
7355       }
7356     } else {
7357       if(i+1<slen) {
7358         current.u=branch_unneeded_reg[i]&~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
7359         current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7360         current.u|=1;
7361       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7362     }
7363     is_ds[i]=ds;
7364     if(ds) {
7365       ds=0; // Skip delay slot, already allocated as part of branch
7366       // ...but we need to alloc it in case something jumps here
7367       if(i+1<slen) {
7368         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7369       }else{
7370         current.u=branch_unneeded_reg[i-1];
7371       }
7372       current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7373       current.u|=1;
7374       struct regstat temp;
7375       memcpy(&temp,&current,sizeof(current));
7376       temp.wasdirty=temp.dirty;
7377       // TODO: Take into account unconditional branches, as below
7378       delayslot_alloc(&temp,i);
7379       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7380       regs[i].wasdirty=temp.wasdirty;
7381       regs[i].dirty=temp.dirty;
7382       regs[i].isconst=0;
7383       regs[i].wasconst=0;
7384       current.isconst=0;
7385       // Create entry (branch target) regmap
7386       for(hr=0;hr<HOST_REGS;hr++)
7387       {
7388         int r=temp.regmap[hr];
7389         if(r>=0) {
7390           if(r!=regmap_pre[i][hr]) {
7391             regs[i].regmap_entry[hr]=-1;
7392           }
7393           else
7394           {
7395               assert(r < 64);
7396               if((current.u>>r)&1) {
7397                 regs[i].regmap_entry[hr]=-1;
7398                 regs[i].regmap[hr]=-1;
7399                 //Don't clear regs in the delay slot as the branch might need them
7400                 //current.regmap[hr]=-1;
7401               }else
7402                 regs[i].regmap_entry[hr]=r;
7403           }
7404         } else {
7405           // First instruction expects CCREG to be allocated
7406           if(i==0&&hr==HOST_CCREG)
7407             regs[i].regmap_entry[hr]=CCREG;
7408           else
7409             regs[i].regmap_entry[hr]=-1;
7410         }
7411       }
7412     }
7413     else { // Not delay slot
7414       switch(itype[i]) {
7415         case UJUMP:
7416           //current.isconst=0; // DEBUG
7417           //current.wasconst=0; // DEBUG
7418           //regs[i].wasconst=0; // DEBUG
7419           clear_const(&current,rt1[i]);
7420           alloc_cc(&current,i);
7421           dirty_reg(&current,CCREG);
7422           if (rt1[i]==31) {
7423             alloc_reg(&current,i,31);
7424             dirty_reg(&current,31);
7425             //assert(rs1[i+1]!=31&&rs2[i+1]!=31);
7426             //assert(rt1[i+1]!=rt1[i]);
7427             #ifdef REG_PREFETCH
7428             alloc_reg(&current,i,PTEMP);
7429             #endif
7430           }
7431           ooo[i]=1;
7432           delayslot_alloc(&current,i+1);
7433           //current.isconst=0; // DEBUG
7434           ds=1;
7435           //printf("i=%d, isconst=%x\n",i,current.isconst);
7436           break;
7437         case RJUMP:
7438           //current.isconst=0;
7439           //current.wasconst=0;
7440           //regs[i].wasconst=0;
7441           clear_const(&current,rs1[i]);
7442           clear_const(&current,rt1[i]);
7443           alloc_cc(&current,i);
7444           dirty_reg(&current,CCREG);
7445           if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
7446             alloc_reg(&current,i,rs1[i]);
7447             if (rt1[i]!=0) {
7448               alloc_reg(&current,i,rt1[i]);
7449               dirty_reg(&current,rt1[i]);
7450               assert(rs1[i+1]!=rt1[i]&&rs2[i+1]!=rt1[i]);
7451               assert(rt1[i+1]!=rt1[i]);
7452               #ifdef REG_PREFETCH
7453               alloc_reg(&current,i,PTEMP);
7454               #endif
7455             }
7456             #ifdef USE_MINI_HT
7457             if(rs1[i]==31) { // JALR
7458               alloc_reg(&current,i,RHASH);
7459               alloc_reg(&current,i,RHTBL);
7460             }
7461             #endif
7462             delayslot_alloc(&current,i+1);
7463           } else {
7464             // The delay slot overwrites our source register,
7465             // allocate a temporary register to hold the old value.
7466             current.isconst=0;
7467             current.wasconst=0;
7468             regs[i].wasconst=0;
7469             delayslot_alloc(&current,i+1);
7470             current.isconst=0;
7471             alloc_reg(&current,i,RTEMP);
7472           }
7473           //current.isconst=0; // DEBUG
7474           ooo[i]=1;
7475           ds=1;
7476           break;
7477         case CJUMP:
7478           //current.isconst=0;
7479           //current.wasconst=0;
7480           //regs[i].wasconst=0;
7481           clear_const(&current,rs1[i]);
7482           clear_const(&current,rs2[i]);
7483           if((opcode[i]&0x3E)==4) // BEQ/BNE
7484           {
7485             alloc_cc(&current,i);
7486             dirty_reg(&current,CCREG);
7487             if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7488             if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7489             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]))||
7490                (rs2[i]&&(rs2[i]==rt1[i+1]||rs2[i]==rt2[i+1]))) {
7491               // The delay slot overwrites one of our conditions.
7492               // Allocate the branch condition registers instead.
7493               current.isconst=0;
7494               current.wasconst=0;
7495               regs[i].wasconst=0;
7496               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7497               if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7498             }
7499             else
7500             {
7501               ooo[i]=1;
7502               delayslot_alloc(&current,i+1);
7503             }
7504           }
7505           else
7506           if((opcode[i]&0x3E)==6) // BLEZ/BGTZ
7507           {
7508             alloc_cc(&current,i);
7509             dirty_reg(&current,CCREG);
7510             alloc_reg(&current,i,rs1[i]);
7511             if(rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) {
7512               // The delay slot overwrites one of our conditions.
7513               // Allocate the branch condition registers instead.
7514               current.isconst=0;
7515               current.wasconst=0;
7516               regs[i].wasconst=0;
7517               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7518             }
7519             else
7520             {
7521               ooo[i]=1;
7522               delayslot_alloc(&current,i+1);
7523             }
7524           }
7525           else
7526           // Don't alloc the delay slot yet because we might not execute it
7527           if((opcode[i]&0x3E)==0x14) // BEQL/BNEL
7528           {
7529             current.isconst=0;
7530             current.wasconst=0;
7531             regs[i].wasconst=0;
7532             alloc_cc(&current,i);
7533             dirty_reg(&current,CCREG);
7534             alloc_reg(&current,i,rs1[i]);
7535             alloc_reg(&current,i,rs2[i]);
7536           }
7537           else
7538           if((opcode[i]&0x3E)==0x16) // BLEZL/BGTZL
7539           {
7540             current.isconst=0;
7541             current.wasconst=0;
7542             regs[i].wasconst=0;
7543             alloc_cc(&current,i);
7544             dirty_reg(&current,CCREG);
7545             alloc_reg(&current,i,rs1[i]);
7546           }
7547           ds=1;
7548           //current.isconst=0;
7549           break;
7550         case SJUMP:
7551           //current.isconst=0;
7552           //current.wasconst=0;
7553           //regs[i].wasconst=0;
7554           clear_const(&current,rs1[i]);
7555           clear_const(&current,rt1[i]);
7556           //if((opcode2[i]&0x1E)==0x0) // BLTZ/BGEZ
7557           if((opcode2[i]&0x0E)==0x0) // BLTZ/BGEZ
7558           {
7559             alloc_cc(&current,i);
7560             dirty_reg(&current,CCREG);
7561             alloc_reg(&current,i,rs1[i]);
7562             if (rt1[i]==31) { // BLTZAL/BGEZAL
7563               alloc_reg(&current,i,31);
7564               dirty_reg(&current,31);
7565               //#ifdef REG_PREFETCH
7566               //alloc_reg(&current,i,PTEMP);
7567               //#endif
7568             }
7569             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) // The delay slot overwrites the branch condition.
7570                ||(rt1[i]==31&&(rs1[i+1]==31||rs2[i+1]==31||rt1[i+1]==31||rt2[i+1]==31))) { // DS touches $ra
7571               // Allocate the branch condition registers instead.
7572               current.isconst=0;
7573               current.wasconst=0;
7574               regs[i].wasconst=0;
7575               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7576             }
7577             else
7578             {
7579               ooo[i]=1;
7580               delayslot_alloc(&current,i+1);
7581             }
7582           }
7583           else
7584           // Don't alloc the delay slot yet because we might not execute it
7585           if((opcode2[i]&0x1E)==0x2) // BLTZL/BGEZL
7586           {
7587             current.isconst=0;
7588             current.wasconst=0;
7589             regs[i].wasconst=0;
7590             alloc_cc(&current,i);
7591             dirty_reg(&current,CCREG);
7592             alloc_reg(&current,i,rs1[i]);
7593           }
7594           ds=1;
7595           //current.isconst=0;
7596           break;
7597         case IMM16:
7598           imm16_alloc(&current,i);
7599           break;
7600         case LOAD:
7601         case LOADLR:
7602           load_alloc(&current,i);
7603           break;
7604         case STORE:
7605         case STORELR:
7606           store_alloc(&current,i);
7607           break;
7608         case ALU:
7609           alu_alloc(&current,i);
7610           break;
7611         case SHIFT:
7612           shift_alloc(&current,i);
7613           break;
7614         case MULTDIV:
7615           multdiv_alloc(&current,i);
7616           break;
7617         case SHIFTIMM:
7618           shiftimm_alloc(&current,i);
7619           break;
7620         case MOV:
7621           mov_alloc(&current,i);
7622           break;
7623         case COP0:
7624           cop0_alloc(&current,i);
7625           break;
7626         case COP1:
7627         case COP2:
7628           cop12_alloc(&current,i);
7629           break;
7630         case C1LS:
7631           c1ls_alloc(&current,i);
7632           break;
7633         case C2LS:
7634           c2ls_alloc(&current,i);
7635           break;
7636         case C2OP:
7637           c2op_alloc(&current,i);
7638           break;
7639         case SYSCALL:
7640         case HLECALL:
7641         case INTCALL:
7642           syscall_alloc(&current,i);
7643           break;
7644         case SPAN:
7645           pagespan_alloc(&current,i);
7646           break;
7647       }
7648
7649       // Create entry (branch target) regmap
7650       for(hr=0;hr<HOST_REGS;hr++)
7651       {
7652         int r,or;
7653         r=current.regmap[hr];
7654         if(r>=0) {
7655           if(r!=regmap_pre[i][hr]) {
7656             // TODO: delay slot (?)
7657             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7658             if(or<0||(r&63)>=TEMPREG){
7659               regs[i].regmap_entry[hr]=-1;
7660             }
7661             else
7662             {
7663               // Just move it to a different register
7664               regs[i].regmap_entry[hr]=r;
7665               // If it was dirty before, it's still dirty
7666               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7667             }
7668           }
7669           else
7670           {
7671             // Unneeded
7672             if(r==0){
7673               regs[i].regmap_entry[hr]=0;
7674             }
7675             else
7676             {
7677               assert(r<64);
7678               if((current.u>>r)&1) {
7679                 regs[i].regmap_entry[hr]=-1;
7680                 //regs[i].regmap[hr]=-1;
7681                 current.regmap[hr]=-1;
7682               }else
7683                 regs[i].regmap_entry[hr]=r;
7684             }
7685           }
7686         } else {
7687           // Branches expect CCREG to be allocated at the target
7688           if(regmap_pre[i][hr]==CCREG)
7689             regs[i].regmap_entry[hr]=CCREG;
7690           else
7691             regs[i].regmap_entry[hr]=-1;
7692         }
7693       }
7694       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7695     }
7696
7697     if(i>0&&(itype[i-1]==STORE||itype[i-1]==STORELR||(itype[i-1]==C2LS&&opcode[i-1]==0x3a))&&(u_int)imm[i-1]<0x800)
7698       current.waswritten|=1<<rs1[i-1];
7699     current.waswritten&=~(1<<rt1[i]);
7700     current.waswritten&=~(1<<rt2[i]);
7701     if((itype[i]==STORE||itype[i]==STORELR||(itype[i]==C2LS&&opcode[i]==0x3a))&&(u_int)imm[i]>=0x800)
7702       current.waswritten&=~(1<<rs1[i]);
7703
7704     /* Branch post-alloc */
7705     if(i>0)
7706     {
7707       current.wasdirty=current.dirty;
7708       switch(itype[i-1]) {
7709         case UJUMP:
7710           memcpy(&branch_regs[i-1],&current,sizeof(current));
7711           branch_regs[i-1].isconst=0;
7712           branch_regs[i-1].wasconst=0;
7713           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7714           alloc_cc(&branch_regs[i-1],i-1);
7715           dirty_reg(&branch_regs[i-1],CCREG);
7716           if(rt1[i-1]==31) { // JAL
7717             alloc_reg(&branch_regs[i-1],i-1,31);
7718             dirty_reg(&branch_regs[i-1],31);
7719           }
7720           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7721           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7722           break;
7723         case RJUMP:
7724           memcpy(&branch_regs[i-1],&current,sizeof(current));
7725           branch_regs[i-1].isconst=0;
7726           branch_regs[i-1].wasconst=0;
7727           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7728           alloc_cc(&branch_regs[i-1],i-1);
7729           dirty_reg(&branch_regs[i-1],CCREG);
7730           alloc_reg(&branch_regs[i-1],i-1,rs1[i-1]);
7731           if(rt1[i-1]!=0) { // JALR
7732             alloc_reg(&branch_regs[i-1],i-1,rt1[i-1]);
7733             dirty_reg(&branch_regs[i-1],rt1[i-1]);
7734           }
7735           #ifdef USE_MINI_HT
7736           if(rs1[i-1]==31) { // JALR
7737             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7738             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7739           }
7740           #endif
7741           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7742           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7743           break;
7744         case CJUMP:
7745           if((opcode[i-1]&0x3E)==4) // BEQ/BNE
7746           {
7747             alloc_cc(&current,i-1);
7748             dirty_reg(&current,CCREG);
7749             if((rs1[i-1]&&(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]))||
7750                (rs2[i-1]&&(rs2[i-1]==rt1[i]||rs2[i-1]==rt2[i]))) {
7751               // The delay slot overwrote one of our conditions
7752               // Delay slot goes after the test (in order)
7753               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7754               current.u|=1;
7755               delayslot_alloc(&current,i);
7756               current.isconst=0;
7757             }
7758             else
7759             {
7760               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7761               // Alloc the branch condition registers
7762               if(rs1[i-1]) alloc_reg(&current,i-1,rs1[i-1]);
7763               if(rs2[i-1]) alloc_reg(&current,i-1,rs2[i-1]);
7764             }
7765             memcpy(&branch_regs[i-1],&current,sizeof(current));
7766             branch_regs[i-1].isconst=0;
7767             branch_regs[i-1].wasconst=0;
7768             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7769             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7770           }
7771           else
7772           if((opcode[i-1]&0x3E)==6) // BLEZ/BGTZ
7773           {
7774             alloc_cc(&current,i-1);
7775             dirty_reg(&current,CCREG);
7776             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
7777               // The delay slot overwrote the branch condition
7778               // Delay slot goes after the test (in order)
7779               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7780               current.u|=1;
7781               delayslot_alloc(&current,i);
7782               current.isconst=0;
7783             }
7784             else
7785             {
7786               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
7787               // Alloc the branch condition register
7788               alloc_reg(&current,i-1,rs1[i-1]);
7789             }
7790             memcpy(&branch_regs[i-1],&current,sizeof(current));
7791             branch_regs[i-1].isconst=0;
7792             branch_regs[i-1].wasconst=0;
7793             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7794             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7795           }
7796           else
7797           // Alloc the delay slot in case the branch is taken
7798           if((opcode[i-1]&0x3E)==0x14) // BEQL/BNEL
7799           {
7800             memcpy(&branch_regs[i-1],&current,sizeof(current));
7801             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7802             alloc_cc(&branch_regs[i-1],i);
7803             dirty_reg(&branch_regs[i-1],CCREG);
7804             delayslot_alloc(&branch_regs[i-1],i);
7805             branch_regs[i-1].isconst=0;
7806             alloc_reg(&current,i,CCREG); // Not taken path
7807             dirty_reg(&current,CCREG);
7808             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7809           }
7810           else
7811           if((opcode[i-1]&0x3E)==0x16) // BLEZL/BGTZL
7812           {
7813             memcpy(&branch_regs[i-1],&current,sizeof(current));
7814             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7815             alloc_cc(&branch_regs[i-1],i);
7816             dirty_reg(&branch_regs[i-1],CCREG);
7817             delayslot_alloc(&branch_regs[i-1],i);
7818             branch_regs[i-1].isconst=0;
7819             alloc_reg(&current,i,CCREG); // Not taken path
7820             dirty_reg(&current,CCREG);
7821             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7822           }
7823           break;
7824         case SJUMP:
7825           //if((opcode2[i-1]&0x1E)==0) // BLTZ/BGEZ
7826           if((opcode2[i-1]&0x0E)==0) // BLTZ/BGEZ
7827           {
7828             alloc_cc(&current,i-1);
7829             dirty_reg(&current,CCREG);
7830             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
7831               // The delay slot overwrote the branch condition
7832               // Delay slot goes after the test (in order)
7833               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7834               current.u|=1;
7835               delayslot_alloc(&current,i);
7836               current.isconst=0;
7837             }
7838             else
7839             {
7840               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
7841               // Alloc the branch condition register
7842               alloc_reg(&current,i-1,rs1[i-1]);
7843             }
7844             memcpy(&branch_regs[i-1],&current,sizeof(current));
7845             branch_regs[i-1].isconst=0;
7846             branch_regs[i-1].wasconst=0;
7847             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7848             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7849           }
7850           else
7851           // Alloc the delay slot in case the branch is taken
7852           if((opcode2[i-1]&0x1E)==2) // BLTZL/BGEZL
7853           {
7854             memcpy(&branch_regs[i-1],&current,sizeof(current));
7855             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7856             alloc_cc(&branch_regs[i-1],i);
7857             dirty_reg(&branch_regs[i-1],CCREG);
7858             delayslot_alloc(&branch_regs[i-1],i);
7859             branch_regs[i-1].isconst=0;
7860             alloc_reg(&current,i,CCREG); // Not taken path
7861             dirty_reg(&current,CCREG);
7862             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7863           }
7864           // FIXME: BLTZAL/BGEZAL
7865           if(opcode2[i-1]&0x10) { // BxxZAL
7866             alloc_reg(&branch_regs[i-1],i-1,31);
7867             dirty_reg(&branch_regs[i-1],31);
7868           }
7869           break;
7870       }
7871
7872       if(itype[i-1]==UJUMP||itype[i-1]==RJUMP||(source[i-1]>>16)==0x1000)
7873       {
7874         if(rt1[i-1]==31) // JAL/JALR
7875         {
7876           // Subroutine call will return here, don't alloc any registers
7877           current.dirty=0;
7878           clear_all_regs(current.regmap);
7879           alloc_reg(&current,i,CCREG);
7880           dirty_reg(&current,CCREG);
7881         }
7882         else if(i+1<slen)
7883         {
7884           // Internal branch will jump here, match registers to caller
7885           current.dirty=0;
7886           clear_all_regs(current.regmap);
7887           alloc_reg(&current,i,CCREG);
7888           dirty_reg(&current,CCREG);
7889           for(j=i-1;j>=0;j--)
7890           {
7891             if(ba[j]==start+i*4+4) {
7892               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
7893               current.dirty=branch_regs[j].dirty;
7894               break;
7895             }
7896           }
7897           while(j>=0) {
7898             if(ba[j]==start+i*4+4) {
7899               for(hr=0;hr<HOST_REGS;hr++) {
7900                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
7901                   current.regmap[hr]=-1;
7902                 }
7903                 current.dirty&=branch_regs[j].dirty;
7904               }
7905             }
7906             j--;
7907           }
7908         }
7909       }
7910     }
7911
7912     // Count cycles in between branches
7913     ccadj[i]=cc;
7914     if(i>0&&(itype[i-1]==RJUMP||itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP||itype[i]==SYSCALL||itype[i]==HLECALL))
7915     {
7916       cc=0;
7917     }
7918 #if !defined(DRC_DBG)
7919     else if(itype[i]==C2OP&&gte_cycletab[source[i]&0x3f]>2)
7920     {
7921       // GTE runs in parallel until accessed, divide by 2 for a rough guess
7922       cc+=gte_cycletab[source[i]&0x3f]/2;
7923     }
7924     else if(/*itype[i]==LOAD||itype[i]==STORE||*/itype[i]==C1LS) // load,store causes weird timing issues
7925     {
7926       cc+=2; // 2 cycle penalty (after CLOCK_DIVIDER)
7927     }
7928     else if(i>1&&itype[i]==STORE&&itype[i-1]==STORE&&itype[i-2]==STORE&&!bt[i])
7929     {
7930       cc+=4;
7931     }
7932     else if(itype[i]==C2LS)
7933     {
7934       cc+=4;
7935     }
7936 #endif
7937     else
7938     {
7939       cc++;
7940     }
7941
7942     if(!is_ds[i]) {
7943       regs[i].dirty=current.dirty;
7944       regs[i].isconst=current.isconst;
7945       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
7946     }
7947     for(hr=0;hr<HOST_REGS;hr++) {
7948       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
7949         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
7950           regs[i].wasconst&=~(1<<hr);
7951         }
7952       }
7953     }
7954     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
7955     regs[i].waswritten=current.waswritten;
7956   }
7957
7958   /* Pass 4 - Cull unused host registers */
7959
7960   uint64_t nr=0;
7961
7962   for (i=slen-1;i>=0;i--)
7963   {
7964     int hr;
7965     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
7966     {
7967       if(ba[i]<start || ba[i]>=(start+slen*4))
7968       {
7969         // Branch out of this block, don't need anything
7970         nr=0;
7971       }
7972       else
7973       {
7974         // Internal branch
7975         // Need whatever matches the target
7976         nr=0;
7977         int t=(ba[i]-start)>>2;
7978         for(hr=0;hr<HOST_REGS;hr++)
7979         {
7980           if(regs[i].regmap_entry[hr]>=0) {
7981             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
7982           }
7983         }
7984       }
7985       // Conditional branch may need registers for following instructions
7986       if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
7987       {
7988         if(i<slen-2) {
7989           nr|=needed_reg[i+2];
7990           for(hr=0;hr<HOST_REGS;hr++)
7991           {
7992             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
7993             //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]);
7994           }
7995         }
7996       }
7997       // Don't need stuff which is overwritten
7998       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7999       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8000       // Merge in delay slot
8001       for(hr=0;hr<HOST_REGS;hr++)
8002       {
8003         if(!likely[i]) {
8004           // These are overwritten unless the branch is "likely"
8005           // and the delay slot is nullified if not taken
8006           if(rt1[i+1]&&rt1[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8007           if(rt2[i+1]&&rt2[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8008         }
8009         if(rs1[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8010         if(rs2[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8011         if(rs1[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8012         if(rs2[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8013         if(itype[i+1]==STORE || itype[i+1]==STORELR || (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) {
8014           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8015           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8016         }
8017       }
8018     }
8019     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
8020     {
8021       // SYSCALL instruction (software interrupt)
8022       nr=0;
8023     }
8024     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
8025     {
8026       // ERET instruction (return from interrupt)
8027       nr=0;
8028     }
8029     else // Non-branch
8030     {
8031       if(i<slen-1) {
8032         for(hr=0;hr<HOST_REGS;hr++) {
8033           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8034           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8035           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8036           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8037         }
8038       }
8039     }
8040     for(hr=0;hr<HOST_REGS;hr++)
8041     {
8042       // Overwritten registers are not needed
8043       if(rt1[i]&&rt1[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8044       if(rt2[i]&&rt2[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8045       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8046       // Source registers are needed
8047       if(rs1[i]==regmap_pre[i][hr]) nr|=1<<hr;
8048       if(rs2[i]==regmap_pre[i][hr]) nr|=1<<hr;
8049       if(rs1[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8050       if(rs2[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8051       if(itype[i]==STORE || itype[i]==STORELR || (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) {
8052         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8053         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8054       }
8055       // Don't store a register immediately after writing it,
8056       // may prevent dual-issue.
8057       // But do so if this is a branch target, otherwise we
8058       // might have to load the register before the branch.
8059       if(i>0&&!bt[i]&&((regs[i].wasdirty>>hr)&1)) {
8060         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8061           if(rt1[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8062           if(rt2[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8063         }
8064         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8065           if(rt1[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8066           if(rt2[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8067         }
8068       }
8069     }
8070     // Cycle count is needed at branches.  Assume it is needed at the target too.
8071     if(i==0||bt[i]||itype[i]==CJUMP||itype[i]==SPAN) {
8072       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8073       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8074     }
8075     // Save it
8076     needed_reg[i]=nr;
8077
8078     // Deallocate unneeded registers
8079     for(hr=0;hr<HOST_REGS;hr++)
8080     {
8081       if(!((nr>>hr)&1)) {
8082         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8083         if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8084            (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8085            (regs[i].regmap[hr]&63)!=PTEMP && (regs[i].regmap[hr]&63)!=CCREG)
8086         {
8087           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
8088           {
8089             if(likely[i]) {
8090               regs[i].regmap[hr]=-1;
8091               regs[i].isconst&=~(1<<hr);
8092               if(i<slen-2) {
8093                 regmap_pre[i+2][hr]=-1;
8094                 regs[i+2].wasconst&=~(1<<hr);
8095               }
8096             }
8097           }
8098         }
8099         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8100         {
8101           int map=0,temp=0;
8102           if(itype[i+1]==STORE || itype[i+1]==STORELR ||
8103              (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8104             map=INVCP;
8105           }
8106           if(itype[i+1]==LOADLR || itype[i+1]==STORELR ||
8107              itype[i+1]==C1LS || itype[i+1]==C2LS)
8108             temp=FTEMP;
8109           if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8110              (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8111              (regs[i].regmap[hr]&63)!=rt1[i+1] && (regs[i].regmap[hr]&63)!=rt2[i+1] &&
8112              regs[i].regmap[hr]!=rs1[i+1] && regs[i].regmap[hr]!=rs2[i+1] &&
8113              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8114              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8115              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8116              regs[i].regmap[hr]!=map )
8117           {
8118             regs[i].regmap[hr]=-1;
8119             regs[i].isconst&=~(1<<hr);
8120             if((branch_regs[i].regmap[hr]&63)!=rs1[i] && (branch_regs[i].regmap[hr]&63)!=rs2[i] &&
8121                (branch_regs[i].regmap[hr]&63)!=rt1[i] && (branch_regs[i].regmap[hr]&63)!=rt2[i] &&
8122                (branch_regs[i].regmap[hr]&63)!=rt1[i+1] && (branch_regs[i].regmap[hr]&63)!=rt2[i+1] &&
8123                branch_regs[i].regmap[hr]!=rs1[i+1] && branch_regs[i].regmap[hr]!=rs2[i+1] &&
8124                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8125                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8126                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8127                branch_regs[i].regmap[hr]!=map)
8128             {
8129               branch_regs[i].regmap[hr]=-1;
8130               branch_regs[i].regmap_entry[hr]=-1;
8131               if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
8132               {
8133                 if(!likely[i]&&i<slen-2) {
8134                   regmap_pre[i+2][hr]=-1;
8135                   regs[i+2].wasconst&=~(1<<hr);
8136                 }
8137               }
8138             }
8139           }
8140         }
8141         else
8142         {
8143           // Non-branch
8144           if(i>0)
8145           {
8146             int map=-1,temp=-1;
8147             if(itype[i]==STORE || itype[i]==STORELR ||
8148                       (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8149               map=INVCP;
8150             }
8151             if(itype[i]==LOADLR || itype[i]==STORELR ||
8152                itype[i]==C1LS || itype[i]==C2LS)
8153               temp=FTEMP;
8154             if((regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8155                regs[i].regmap[hr]!=rs1[i] && regs[i].regmap[hr]!=rs2[i] &&
8156                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map &&
8157                (itype[i]!=SPAN||regs[i].regmap[hr]!=CCREG))
8158             {
8159               if(i<slen-1&&!is_ds[i]) {
8160                 assert(regs[i].regmap[hr]<64);
8161                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8162                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8163                 {
8164                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8165                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8166                 }
8167                 regmap_pre[i+1][hr]=-1;
8168                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8169                 regs[i+1].wasconst&=~(1<<hr);
8170               }
8171               regs[i].regmap[hr]=-1;
8172               regs[i].isconst&=~(1<<hr);
8173             }
8174           }
8175         }
8176       } // if needed
8177     } // for hr
8178   }
8179
8180   /* Pass 5 - Pre-allocate registers */
8181
8182   // If a register is allocated during a loop, try to allocate it for the
8183   // entire loop, if possible.  This avoids loading/storing registers
8184   // inside of the loop.
8185
8186   signed char f_regmap[HOST_REGS];
8187   clear_all_regs(f_regmap);
8188   for(i=0;i<slen-1;i++)
8189   {
8190     if(itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8191     {
8192       if(ba[i]>=start && ba[i]<(start+i*4))
8193       if(itype[i+1]==NOP||itype[i+1]==MOV||itype[i+1]==ALU
8194       ||itype[i+1]==SHIFTIMM||itype[i+1]==IMM16||itype[i+1]==LOAD
8195       ||itype[i+1]==STORE||itype[i+1]==STORELR||itype[i+1]==C1LS
8196       ||itype[i+1]==SHIFT||itype[i+1]==COP1
8197       ||itype[i+1]==COP2||itype[i+1]==C2LS||itype[i+1]==C2OP)
8198       {
8199         int t=(ba[i]-start)>>2;
8200         if(t>0&&(itype[t-1]!=UJUMP&&itype[t-1]!=RJUMP&&itype[t-1]!=CJUMP&&itype[t-1]!=SJUMP)) // loop_preload can't handle jumps into delay slots
8201         if(t<2||(itype[t-2]!=UJUMP&&itype[t-2]!=RJUMP)||rt1[t-2]!=31) // call/ret assumes no registers allocated
8202         for(hr=0;hr<HOST_REGS;hr++)
8203         {
8204           if(regs[i].regmap[hr]>=0) {
8205             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8206               // dealloc old register
8207               int n;
8208               for(n=0;n<HOST_REGS;n++)
8209               {
8210                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8211               }
8212               // and alloc new one
8213               f_regmap[hr]=regs[i].regmap[hr];
8214             }
8215           }
8216           if(branch_regs[i].regmap[hr]>=0) {
8217             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8218               // dealloc old register
8219               int n;
8220               for(n=0;n<HOST_REGS;n++)
8221               {
8222                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8223               }
8224               // and alloc new one
8225               f_regmap[hr]=branch_regs[i].regmap[hr];
8226             }
8227           }
8228           if(ooo[i]) {
8229             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8230               f_regmap[hr]=branch_regs[i].regmap[hr];
8231           }else{
8232             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8233               f_regmap[hr]=branch_regs[i].regmap[hr];
8234           }
8235           // Avoid dirty->clean transition
8236           #ifdef DESTRUCTIVE_WRITEBACK
8237           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;
8238           #endif
8239           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8240           // case above, however it's always a good idea.  We can't hoist the
8241           // load if the register was already allocated, so there's no point
8242           // wasting time analyzing most of these cases.  It only "succeeds"
8243           // when the mapping was different and the load can be replaced with
8244           // a mov, which is of negligible benefit.  So such cases are
8245           // skipped below.
8246           if(f_regmap[hr]>0) {
8247             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8248               int r=f_regmap[hr];
8249               for(j=t;j<=i;j++)
8250               {
8251                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8252                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8253                 assert(r < 64);
8254                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8255                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8256                   int k;
8257                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8258                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8259                     if(r>63) {
8260                       if(get_reg(regs[i].regmap,r&63)<0) break;
8261                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8262                     }
8263                     k=i;
8264                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8265                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8266                         //printf("no free regs for store %x\n",start+(k-1)*4);
8267                         break;
8268                       }
8269                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8270                         //printf("no-match due to different register\n");
8271                         break;
8272                       }
8273                       if(itype[k-2]==UJUMP||itype[k-2]==RJUMP||itype[k-2]==CJUMP||itype[k-2]==SJUMP) {
8274                         //printf("no-match due to branch\n");
8275                         break;
8276                       }
8277                       // call/ret fast path assumes no registers allocated
8278                       if(k>2&&(itype[k-3]==UJUMP||itype[k-3]==RJUMP)&&rt1[k-3]==31) {
8279                         break;
8280                       }
8281                       assert(r < 64);
8282                       k--;
8283                     }
8284                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8285                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8286                       while(k<i) {
8287                         regs[k].regmap_entry[hr]=f_regmap[hr];
8288                         regs[k].regmap[hr]=f_regmap[hr];
8289                         regmap_pre[k+1][hr]=f_regmap[hr];
8290                         regs[k].wasdirty&=~(1<<hr);
8291                         regs[k].dirty&=~(1<<hr);
8292                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8293                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8294                         regs[k].wasconst&=~(1<<hr);
8295                         regs[k].isconst&=~(1<<hr);
8296                         k++;
8297                       }
8298                     }
8299                     else {
8300                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8301                       break;
8302                     }
8303                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8304                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8305                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8306                       regs[i].regmap_entry[hr]=f_regmap[hr];
8307                       regs[i].regmap[hr]=f_regmap[hr];
8308                       regs[i].wasdirty&=~(1<<hr);
8309                       regs[i].dirty&=~(1<<hr);
8310                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8311                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8312                       regs[i].wasconst&=~(1<<hr);
8313                       regs[i].isconst&=~(1<<hr);
8314                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8315                       branch_regs[i].wasdirty&=~(1<<hr);
8316                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8317                       branch_regs[i].regmap[hr]=f_regmap[hr];
8318                       branch_regs[i].dirty&=~(1<<hr);
8319                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8320                       branch_regs[i].wasconst&=~(1<<hr);
8321                       branch_regs[i].isconst&=~(1<<hr);
8322                       if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000) {
8323                         regmap_pre[i+2][hr]=f_regmap[hr];
8324                         regs[i+2].wasdirty&=~(1<<hr);
8325                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8326                       }
8327                     }
8328                   }
8329                   for(k=t;k<j;k++) {
8330                     // Alloc register clean at beginning of loop,
8331                     // but may dirty it in pass 6
8332                     regs[k].regmap_entry[hr]=f_regmap[hr];
8333                     regs[k].regmap[hr]=f_regmap[hr];
8334                     regs[k].dirty&=~(1<<hr);
8335                     regs[k].wasconst&=~(1<<hr);
8336                     regs[k].isconst&=~(1<<hr);
8337                     if(itype[k]==UJUMP||itype[k]==RJUMP||itype[k]==CJUMP||itype[k]==SJUMP) {
8338                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8339                       branch_regs[k].regmap[hr]=f_regmap[hr];
8340                       branch_regs[k].dirty&=~(1<<hr);
8341                       branch_regs[k].wasconst&=~(1<<hr);
8342                       branch_regs[k].isconst&=~(1<<hr);
8343                       if(itype[k]!=RJUMP&&itype[k]!=UJUMP&&(source[k]>>16)!=0x1000) {
8344                         regmap_pre[k+2][hr]=f_regmap[hr];
8345                         regs[k+2].wasdirty&=~(1<<hr);
8346                       }
8347                     }
8348                     else
8349                     {
8350                       regmap_pre[k+1][hr]=f_regmap[hr];
8351                       regs[k+1].wasdirty&=~(1<<hr);
8352                     }
8353                   }
8354                   if(regs[j].regmap[hr]==f_regmap[hr])
8355                     regs[j].regmap_entry[hr]=f_regmap[hr];
8356                   break;
8357                 }
8358                 if(j==i) break;
8359                 if(regs[j].regmap[hr]>=0)
8360                   break;
8361                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8362                   //printf("no-match due to different register\n");
8363                   break;
8364                 }
8365                 if(itype[j]==UJUMP||itype[j]==RJUMP||(source[j]>>16)==0x1000)
8366                 {
8367                   // Stop on unconditional branch
8368                   break;
8369                 }
8370                 if(itype[j]==CJUMP||itype[j]==SJUMP)
8371                 {
8372                   if(ooo[j]) {
8373                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8374                       break;
8375                   }else{
8376                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8377                       break;
8378                   }
8379                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8380                     //printf("no-match due to different register (branch)\n");
8381                     break;
8382                   }
8383                 }
8384                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8385                   //printf("No free regs for store %x\n",start+j*4);
8386                   break;
8387                 }
8388                 assert(f_regmap[hr]<64);
8389               }
8390             }
8391           }
8392         }
8393       }
8394     }else{
8395       // Non branch or undetermined branch target
8396       for(hr=0;hr<HOST_REGS;hr++)
8397       {
8398         if(hr!=EXCLUDE_REG) {
8399           if(regs[i].regmap[hr]>=0) {
8400             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8401               // dealloc old register
8402               int n;
8403               for(n=0;n<HOST_REGS;n++)
8404               {
8405                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8406               }
8407               // and alloc new one
8408               f_regmap[hr]=regs[i].regmap[hr];
8409             }
8410           }
8411         }
8412       }
8413       // Try to restore cycle count at branch targets
8414       if(bt[i]) {
8415         for(j=i;j<slen-1;j++) {
8416           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8417           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8418             //printf("no free regs for store %x\n",start+j*4);
8419             break;
8420           }
8421         }
8422         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8423           int k=i;
8424           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8425           while(k<j) {
8426             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8427             regs[k].regmap[HOST_CCREG]=CCREG;
8428             regmap_pre[k+1][HOST_CCREG]=CCREG;
8429             regs[k+1].wasdirty|=1<<HOST_CCREG;
8430             regs[k].dirty|=1<<HOST_CCREG;
8431             regs[k].wasconst&=~(1<<HOST_CCREG);
8432             regs[k].isconst&=~(1<<HOST_CCREG);
8433             k++;
8434           }
8435           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8436         }
8437         // Work backwards from the branch target
8438         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8439         {
8440           //printf("Extend backwards\n");
8441           int k;
8442           k=i;
8443           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8444             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8445               //printf("no free regs for store %x\n",start+(k-1)*4);
8446               break;
8447             }
8448             k--;
8449           }
8450           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8451             //printf("Extend CC, %x ->\n",start+k*4);
8452             while(k<=i) {
8453               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8454               regs[k].regmap[HOST_CCREG]=CCREG;
8455               regmap_pre[k+1][HOST_CCREG]=CCREG;
8456               regs[k+1].wasdirty|=1<<HOST_CCREG;
8457               regs[k].dirty|=1<<HOST_CCREG;
8458               regs[k].wasconst&=~(1<<HOST_CCREG);
8459               regs[k].isconst&=~(1<<HOST_CCREG);
8460               k++;
8461             }
8462           }
8463           else {
8464             //printf("Fail Extend CC, %x ->\n",start+k*4);
8465           }
8466         }
8467       }
8468       if(itype[i]!=STORE&&itype[i]!=STORELR&&itype[i]!=C1LS&&itype[i]!=SHIFT&&
8469          itype[i]!=NOP&&itype[i]!=MOV&&itype[i]!=ALU&&itype[i]!=SHIFTIMM&&
8470          itype[i]!=IMM16&&itype[i]!=LOAD&&itype[i]!=COP1)
8471       {
8472         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8473       }
8474     }
8475   }
8476
8477   // This allocates registers (if possible) one instruction prior
8478   // to use, which can avoid a load-use penalty on certain CPUs.
8479   for(i=0;i<slen-1;i++)
8480   {
8481     if(!i||(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP))
8482     {
8483       if(!bt[i+1])
8484       {
8485         if(itype[i]==ALU||itype[i]==MOV||itype[i]==LOAD||itype[i]==SHIFTIMM||itype[i]==IMM16
8486            ||((itype[i]==COP1||itype[i]==COP2)&&opcode2[i]<3))
8487         {
8488           if(rs1[i+1]) {
8489             if((hr=get_reg(regs[i+1].regmap,rs1[i+1]))>=0)
8490             {
8491               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8492               {
8493                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8494                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8495                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8496                 regs[i].isconst&=~(1<<hr);
8497                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8498                 constmap[i][hr]=constmap[i+1][hr];
8499                 regs[i+1].wasdirty&=~(1<<hr);
8500                 regs[i].dirty&=~(1<<hr);
8501               }
8502             }
8503           }
8504           if(rs2[i+1]) {
8505             if((hr=get_reg(regs[i+1].regmap,rs2[i+1]))>=0)
8506             {
8507               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8508               {
8509                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8510                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8511                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8512                 regs[i].isconst&=~(1<<hr);
8513                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8514                 constmap[i][hr]=constmap[i+1][hr];
8515                 regs[i+1].wasdirty&=~(1<<hr);
8516                 regs[i].dirty&=~(1<<hr);
8517               }
8518             }
8519           }
8520           // Preload target address for load instruction (non-constant)
8521           if(itype[i+1]==LOAD&&rs1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8522             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8523             {
8524               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8525               {
8526                 regs[i].regmap[hr]=rs1[i+1];
8527                 regmap_pre[i+1][hr]=rs1[i+1];
8528                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8529                 regs[i].isconst&=~(1<<hr);
8530                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8531                 constmap[i][hr]=constmap[i+1][hr];
8532                 regs[i+1].wasdirty&=~(1<<hr);
8533                 regs[i].dirty&=~(1<<hr);
8534               }
8535             }
8536           }
8537           // Load source into target register
8538           if(lt1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8539             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8540             {
8541               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8542               {
8543                 regs[i].regmap[hr]=rs1[i+1];
8544                 regmap_pre[i+1][hr]=rs1[i+1];
8545                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8546                 regs[i].isconst&=~(1<<hr);
8547                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8548                 constmap[i][hr]=constmap[i+1][hr];
8549                 regs[i+1].wasdirty&=~(1<<hr);
8550                 regs[i].dirty&=~(1<<hr);
8551               }
8552             }
8553           }
8554           // Address for store instruction (non-constant)
8555           if(itype[i+1]==STORE||itype[i+1]==STORELR
8556              ||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8557             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8558               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8559               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8560               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8561               assert(hr>=0);
8562               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8563               {
8564                 regs[i].regmap[hr]=rs1[i+1];
8565                 regmap_pre[i+1][hr]=rs1[i+1];
8566                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8567                 regs[i].isconst&=~(1<<hr);
8568                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8569                 constmap[i][hr]=constmap[i+1][hr];
8570                 regs[i+1].wasdirty&=~(1<<hr);
8571                 regs[i].dirty&=~(1<<hr);
8572               }
8573             }
8574           }
8575           if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8576             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8577               int nr;
8578               hr=get_reg(regs[i+1].regmap,FTEMP);
8579               assert(hr>=0);
8580               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8581               {
8582                 regs[i].regmap[hr]=rs1[i+1];
8583                 regmap_pre[i+1][hr]=rs1[i+1];
8584                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8585                 regs[i].isconst&=~(1<<hr);
8586                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8587                 constmap[i][hr]=constmap[i+1][hr];
8588                 regs[i+1].wasdirty&=~(1<<hr);
8589                 regs[i].dirty&=~(1<<hr);
8590               }
8591               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8592               {
8593                 // move it to another register
8594                 regs[i+1].regmap[hr]=-1;
8595                 regmap_pre[i+2][hr]=-1;
8596                 regs[i+1].regmap[nr]=FTEMP;
8597                 regmap_pre[i+2][nr]=FTEMP;
8598                 regs[i].regmap[nr]=rs1[i+1];
8599                 regmap_pre[i+1][nr]=rs1[i+1];
8600                 regs[i+1].regmap_entry[nr]=rs1[i+1];
8601                 regs[i].isconst&=~(1<<nr);
8602                 regs[i+1].isconst&=~(1<<nr);
8603                 regs[i].dirty&=~(1<<nr);
8604                 regs[i+1].wasdirty&=~(1<<nr);
8605                 regs[i+1].dirty&=~(1<<nr);
8606                 regs[i+2].wasdirty&=~(1<<nr);
8607               }
8608             }
8609           }
8610           if(itype[i+1]==LOAD||itype[i+1]==LOADLR||itype[i+1]==STORE||itype[i+1]==STORELR/*||itype[i+1]==C1LS||||itype[i+1]==C2LS*/) {
8611             if(itype[i+1]==LOAD)
8612               hr=get_reg(regs[i+1].regmap,rt1[i+1]);
8613             if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8614               hr=get_reg(regs[i+1].regmap,FTEMP);
8615             if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8616               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8617               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8618             }
8619             if(hr>=0&&regs[i].regmap[hr]<0) {
8620               int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
8621               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8622                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8623                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8624                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8625                 regs[i].isconst&=~(1<<hr);
8626                 regs[i+1].wasdirty&=~(1<<hr);
8627                 regs[i].dirty&=~(1<<hr);
8628               }
8629             }
8630           }
8631         }
8632       }
8633     }
8634   }
8635
8636   /* Pass 6 - Optimize clean/dirty state */
8637   clean_registers(0,slen-1,1);
8638
8639   /* Pass 7 - Identify 32-bit registers */
8640   for (i=slen-1;i>=0;i--)
8641   {
8642     if(itype[i]==CJUMP||itype[i]==SJUMP)
8643     {
8644       // Conditional branch
8645       if((source[i]>>16)!=0x1000&&i<slen-2) {
8646         // Mark this address as a branch target since it may be called
8647         // upon return from interrupt
8648         bt[i+2]=1;
8649       }
8650     }
8651   }
8652
8653   if(itype[slen-1]==SPAN) {
8654     bt[slen-1]=1; // Mark as a branch target so instruction can restart after exception
8655   }
8656
8657 #ifdef DISASM
8658   /* Debug/disassembly */
8659   for(i=0;i<slen;i++)
8660   {
8661     printf("U:");
8662     int r;
8663     for(r=1;r<=CCREG;r++) {
8664       if((unneeded_reg[i]>>r)&1) {
8665         if(r==HIREG) printf(" HI");
8666         else if(r==LOREG) printf(" LO");
8667         else printf(" r%d",r);
8668       }
8669     }
8670     printf("\n");
8671     #if defined(__i386__) || defined(__x86_64__)
8672     printf("pre: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7]);
8673     #endif
8674     #ifdef __arm__
8675     printf("pre: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][4],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7],regmap_pre[i][8],regmap_pre[i][9],regmap_pre[i][10],regmap_pre[i][12]);
8676     #endif
8677     #if defined(__i386__) || defined(__x86_64__)
8678     printf("needs: ");
8679     if(needed_reg[i]&1) printf("eax ");
8680     if((needed_reg[i]>>1)&1) printf("ecx ");
8681     if((needed_reg[i]>>2)&1) printf("edx ");
8682     if((needed_reg[i]>>3)&1) printf("ebx ");
8683     if((needed_reg[i]>>5)&1) printf("ebp ");
8684     if((needed_reg[i]>>6)&1) printf("esi ");
8685     if((needed_reg[i]>>7)&1) printf("edi ");
8686     printf("\n");
8687     printf("entry: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7]);
8688     printf("dirty: ");
8689     if(regs[i].wasdirty&1) printf("eax ");
8690     if((regs[i].wasdirty>>1)&1) printf("ecx ");
8691     if((regs[i].wasdirty>>2)&1) printf("edx ");
8692     if((regs[i].wasdirty>>3)&1) printf("ebx ");
8693     if((regs[i].wasdirty>>5)&1) printf("ebp ");
8694     if((regs[i].wasdirty>>6)&1) printf("esi ");
8695     if((regs[i].wasdirty>>7)&1) printf("edi ");
8696     #endif
8697     #ifdef __arm__
8698     printf("entry: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[4],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7],regs[i].regmap_entry[8],regs[i].regmap_entry[9],regs[i].regmap_entry[10],regs[i].regmap_entry[12]);
8699     printf("dirty: ");
8700     if(regs[i].wasdirty&1) printf("r0 ");
8701     if((regs[i].wasdirty>>1)&1) printf("r1 ");
8702     if((regs[i].wasdirty>>2)&1) printf("r2 ");
8703     if((regs[i].wasdirty>>3)&1) printf("r3 ");
8704     if((regs[i].wasdirty>>4)&1) printf("r4 ");
8705     if((regs[i].wasdirty>>5)&1) printf("r5 ");
8706     if((regs[i].wasdirty>>6)&1) printf("r6 ");
8707     if((regs[i].wasdirty>>7)&1) printf("r7 ");
8708     if((regs[i].wasdirty>>8)&1) printf("r8 ");
8709     if((regs[i].wasdirty>>9)&1) printf("r9 ");
8710     if((regs[i].wasdirty>>10)&1) printf("r10 ");
8711     if((regs[i].wasdirty>>12)&1) printf("r12 ");
8712     #endif
8713     printf("\n");
8714     disassemble_inst(i);
8715     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
8716     #if defined(__i386__) || defined(__x86_64__)
8717     printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7]);
8718     if(regs[i].dirty&1) printf("eax ");
8719     if((regs[i].dirty>>1)&1) printf("ecx ");
8720     if((regs[i].dirty>>2)&1) printf("edx ");
8721     if((regs[i].dirty>>3)&1) printf("ebx ");
8722     if((regs[i].dirty>>5)&1) printf("ebp ");
8723     if((regs[i].dirty>>6)&1) printf("esi ");
8724     if((regs[i].dirty>>7)&1) printf("edi ");
8725     #endif
8726     #ifdef __arm__
8727     printf("r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[4],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7],regs[i].regmap[8],regs[i].regmap[9],regs[i].regmap[10],regs[i].regmap[12]);
8728     if(regs[i].dirty&1) printf("r0 ");
8729     if((regs[i].dirty>>1)&1) printf("r1 ");
8730     if((regs[i].dirty>>2)&1) printf("r2 ");
8731     if((regs[i].dirty>>3)&1) printf("r3 ");
8732     if((regs[i].dirty>>4)&1) printf("r4 ");
8733     if((regs[i].dirty>>5)&1) printf("r5 ");
8734     if((regs[i].dirty>>6)&1) printf("r6 ");
8735     if((regs[i].dirty>>7)&1) printf("r7 ");
8736     if((regs[i].dirty>>8)&1) printf("r8 ");
8737     if((regs[i].dirty>>9)&1) printf("r9 ");
8738     if((regs[i].dirty>>10)&1) printf("r10 ");
8739     if((regs[i].dirty>>12)&1) printf("r12 ");
8740     #endif
8741     printf("\n");
8742     if(regs[i].isconst) {
8743       printf("constants: ");
8744       #if defined(__i386__) || defined(__x86_64__)
8745       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
8746       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
8747       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
8748       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
8749       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
8750       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
8751       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
8752       #endif
8753       #if defined(__arm__) || defined(__aarch64__)
8754       int r;
8755       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
8756         if ((regs[i].isconst >> r) & 1)
8757           printf(" r%d=%x", r, (u_int)constmap[i][r]);
8758       #endif
8759       printf("\n");
8760     }
8761     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
8762       #if defined(__i386__) || defined(__x86_64__)
8763       printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",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]);
8764       if(branch_regs[i].dirty&1) printf("eax ");
8765       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
8766       if((branch_regs[i].dirty>>2)&1) printf("edx ");
8767       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
8768       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
8769       if((branch_regs[i].dirty>>6)&1) printf("esi ");
8770       if((branch_regs[i].dirty>>7)&1) printf("edi ");
8771       #endif
8772       #ifdef __arm__
8773       printf("branch(%d): r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",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[4],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7],branch_regs[i].regmap[8],branch_regs[i].regmap[9],branch_regs[i].regmap[10],branch_regs[i].regmap[12]);
8774       if(branch_regs[i].dirty&1) printf("r0 ");
8775       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
8776       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
8777       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
8778       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
8779       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
8780       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
8781       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
8782       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
8783       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
8784       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
8785       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
8786       #endif
8787     }
8788   }
8789 #endif // DISASM
8790
8791   /* Pass 8 - Assembly */
8792   linkcount=0;stubcount=0;
8793   ds=0;is_delayslot=0;
8794   u_int dirty_pre=0;
8795   void *beginning=start_block();
8796   if((u_int)addr&1) {
8797     ds=1;
8798     pagespan_ds();
8799   }
8800   void *instr_addr0_override = NULL;
8801
8802   if (start == 0x80030000) {
8803     // nasty hack for the fastbios thing
8804     // override block entry to this code
8805     instr_addr0_override = out;
8806     emit_movimm(start,0);
8807     // abuse io address var as a flag that we
8808     // have already returned here once
8809     emit_readword(&address,1);
8810     emit_writeword(0,&pcaddr);
8811     emit_writeword(0,&address);
8812     emit_cmp(0,1);
8813     #ifdef __aarch64__
8814     emit_jeq(out + 4*2);
8815     emit_far_jump(new_dyna_leave);
8816     #else
8817     emit_jne(new_dyna_leave);
8818     #endif
8819   }
8820   for(i=0;i<slen;i++)
8821   {
8822     //if(ds) printf("ds: ");
8823     disassemble_inst(i);
8824     if(ds) {
8825       ds=0; // Skip delay slot
8826       if(bt[i]) assem_debug("OOPS - branch into delay slot\n");
8827       instr_addr[i] = NULL;
8828     } else {
8829       speculate_register_values(i);
8830       #ifndef DESTRUCTIVE_WRITEBACK
8831       if(i<2||(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000))
8832       {
8833         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
8834       }
8835       if((itype[i]==CJUMP||itype[i]==SJUMP)&&!likely[i]) {
8836         dirty_pre=branch_regs[i].dirty;
8837       }else{
8838         dirty_pre=regs[i].dirty;
8839       }
8840       #endif
8841       // write back
8842       if(i<2||(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000))
8843       {
8844         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
8845         loop_preload(regmap_pre[i],regs[i].regmap_entry);
8846       }
8847       // branch target entry point
8848       instr_addr[i] = out;
8849       assem_debug("<->\n");
8850       drc_dbg_emit_do_cmp(i);
8851
8852       // load regs
8853       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
8854         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
8855       load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i],rs2[i]);
8856       address_generation(i,&regs[i],regs[i].regmap_entry);
8857       load_consts(regmap_pre[i],regs[i].regmap,i);
8858       if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8859       {
8860         // Load the delay slot registers if necessary
8861         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i]&&(rs1[i+1]!=rt1[i]||rt1[i]==0))
8862           load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
8863         if(rs2[i+1]!=rs1[i+1]&&rs2[i+1]!=rs1[i]&&rs2[i+1]!=rs2[i]&&(rs2[i+1]!=rt1[i]||rt1[i]==0))
8864           load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
8865         if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a)
8866           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
8867       }
8868       else if(i+1<slen)
8869       {
8870         // Preload registers for following instruction
8871         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i])
8872           if(rs1[i+1]!=rt1[i]&&rs1[i+1]!=rt2[i])
8873             load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
8874         if(rs2[i+1]!=rs1[i+1]&&rs2[i+1]!=rs1[i]&&rs2[i+1]!=rs2[i])
8875           if(rs2[i+1]!=rt1[i]&&rs2[i+1]!=rt2[i])
8876             load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
8877       }
8878       // TODO: if(is_ooo(i)) address_generation(i+1);
8879       if(itype[i]==CJUMP)
8880         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
8881       if(itype[i]==STORE||itype[i]==STORELR||(opcode[i]&0x3b)==0x39||(opcode[i]&0x3b)==0x3a)
8882         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
8883       // assemble
8884       switch(itype[i]) {
8885         case ALU:
8886           alu_assemble(i,&regs[i]);break;
8887         case IMM16:
8888           imm16_assemble(i,&regs[i]);break;
8889         case SHIFT:
8890           shift_assemble(i,&regs[i]);break;
8891         case SHIFTIMM:
8892           shiftimm_assemble(i,&regs[i]);break;
8893         case LOAD:
8894           load_assemble(i,&regs[i]);break;
8895         case LOADLR:
8896           loadlr_assemble(i,&regs[i]);break;
8897         case STORE:
8898           store_assemble(i,&regs[i]);break;
8899         case STORELR:
8900           storelr_assemble(i,&regs[i]);break;
8901         case COP0:
8902           cop0_assemble(i,&regs[i]);break;
8903         case COP1:
8904           cop1_assemble(i,&regs[i]);break;
8905         case C1LS:
8906           c1ls_assemble(i,&regs[i]);break;
8907         case COP2:
8908           cop2_assemble(i,&regs[i]);break;
8909         case C2LS:
8910           c2ls_assemble(i,&regs[i]);break;
8911         case C2OP:
8912           c2op_assemble(i,&regs[i]);break;
8913         case MULTDIV:
8914           multdiv_assemble(i,&regs[i]);break;
8915         case MOV:
8916           mov_assemble(i,&regs[i]);break;
8917         case SYSCALL:
8918           syscall_assemble(i,&regs[i]);break;
8919         case HLECALL:
8920           hlecall_assemble(i,&regs[i]);break;
8921         case INTCALL:
8922           intcall_assemble(i,&regs[i]);break;
8923         case UJUMP:
8924           ujump_assemble(i,&regs[i]);ds=1;break;
8925         case RJUMP:
8926           rjump_assemble(i,&regs[i]);ds=1;break;
8927         case CJUMP:
8928           cjump_assemble(i,&regs[i]);ds=1;break;
8929         case SJUMP:
8930           sjump_assemble(i,&regs[i]);ds=1;break;
8931         case SPAN:
8932           pagespan_assemble(i,&regs[i]);break;
8933       }
8934       if(itype[i]==UJUMP||itype[i]==RJUMP||(source[i]>>16)==0x1000)
8935         literal_pool(1024);
8936       else
8937         literal_pool_jumpover(256);
8938     }
8939   }
8940   //assert(itype[i-2]==UJUMP||itype[i-2]==RJUMP||(source[i-2]>>16)==0x1000);
8941   // If the block did not end with an unconditional branch,
8942   // add a jump to the next instruction.
8943   if(i>1) {
8944     if(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000&&itype[i-1]!=SPAN) {
8945       assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
8946       assert(i==slen);
8947       if(itype[i-2]!=CJUMP&&itype[i-2]!=SJUMP) {
8948         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
8949         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
8950           emit_loadreg(CCREG,HOST_CCREG);
8951         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
8952       }
8953       else if(!likely[i-2])
8954       {
8955         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
8956         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
8957       }
8958       else
8959       {
8960         store_regs_bt(regs[i-2].regmap,regs[i-2].dirty,start+i*4);
8961         assert(regs[i-2].regmap[HOST_CCREG]==CCREG);
8962       }
8963       add_to_linker(out,start+i*4,0);
8964       emit_jmp(0);
8965     }
8966   }
8967   else
8968   {
8969     assert(i>0);
8970     assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
8971     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
8972     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
8973       emit_loadreg(CCREG,HOST_CCREG);
8974     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
8975     add_to_linker(out,start+i*4,0);
8976     emit_jmp(0);
8977   }
8978
8979   // TODO: delay slot stubs?
8980   // Stubs
8981   for(i=0;i<stubcount;i++)
8982   {
8983     switch(stubs[i].type)
8984     {
8985       case LOADB_STUB:
8986       case LOADH_STUB:
8987       case LOADW_STUB:
8988       case LOADD_STUB:
8989       case LOADBU_STUB:
8990       case LOADHU_STUB:
8991         do_readstub(i);break;
8992       case STOREB_STUB:
8993       case STOREH_STUB:
8994       case STOREW_STUB:
8995       case STORED_STUB:
8996         do_writestub(i);break;
8997       case CC_STUB:
8998         do_ccstub(i);break;
8999       case INVCODE_STUB:
9000         do_invstub(i);break;
9001       case FP_STUB:
9002         do_cop1stub(i);break;
9003       case STORELR_STUB:
9004         do_unalignedwritestub(i);break;
9005     }
9006   }
9007
9008   if (instr_addr0_override)
9009     instr_addr[0] = instr_addr0_override;
9010
9011   /* Pass 9 - Linker */
9012   for(i=0;i<linkcount;i++)
9013   {
9014     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9015     literal_pool(64);
9016     if (!link_addr[i].ext)
9017     {
9018       void *stub = out;
9019       void *addr = check_addr(link_addr[i].target);
9020       emit_extjump(link_addr[i].addr, link_addr[i].target);
9021       if (addr) {
9022         set_jump_target(link_addr[i].addr, addr);
9023         add_link(link_addr[i].target,stub);
9024       }
9025       else
9026         set_jump_target(link_addr[i].addr, stub);
9027     }
9028     else
9029     {
9030       // Internal branch
9031       int target=(link_addr[i].target-start)>>2;
9032       assert(target>=0&&target<slen);
9033       assert(instr_addr[target]);
9034       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9035       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9036       //#else
9037       set_jump_target(link_addr[i].addr, instr_addr[target]);
9038       //#endif
9039     }
9040   }
9041   // External Branch Targets (jump_in)
9042   if(copy+slen*4>(void *)shadow+sizeof(shadow)) copy=shadow;
9043   for(i=0;i<slen;i++)
9044   {
9045     if(bt[i]||i==0)
9046     {
9047       if(instr_addr[i]) // TODO - delay slots (=null)
9048       {
9049         u_int vaddr=start+i*4;
9050         u_int page=get_page(vaddr);
9051         u_int vpage=get_vpage(vaddr);
9052         literal_pool(256);
9053         {
9054           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9055           assem_debug("jump_in: %x\n",start+i*4);
9056           ll_add(jump_dirty+vpage,vaddr,out);
9057           void *entry_point = do_dirty_stub(i);
9058           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9059           // If there was an existing entry in the hash table,
9060           // replace it with the new address.
9061           // Don't add new entries.  We'll insert the
9062           // ones that actually get used in check_addr().
9063           struct ht_entry *ht_bin = hash_table_get(vaddr);
9064           if (ht_bin->vaddr[0] == vaddr)
9065             ht_bin->tcaddr[0] = entry_point;
9066           if (ht_bin->vaddr[1] == vaddr)
9067             ht_bin->tcaddr[1] = entry_point;
9068         }
9069       }
9070     }
9071   }
9072   // Write out the literal pool if necessary
9073   literal_pool(0);
9074   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9075   // Align code
9076   if(((u_int)out)&7) emit_addnop(13);
9077   #endif
9078   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9079   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9080   memcpy(copy,source,slen*4);
9081   copy+=slen*4;
9082
9083   end_block(beginning);
9084
9085   // If we're within 256K of the end of the buffer,
9086   // start over from the beginning. (Is 256K enough?)
9087   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9088     out = ndrc->translation_cache;
9089
9090   // Trap writes to any of the pages we compiled
9091   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9092     invalid_code[i]=0;
9093   }
9094   inv_code_start=inv_code_end=~0;
9095
9096   // for PCSX we need to mark all mirrors too
9097   if(get_page(start)<(RAM_SIZE>>12))
9098     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9099       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9100       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9101       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9102
9103   /* Pass 10 - Free memory by expiring oldest blocks */
9104
9105   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9106   while(expirep!=end)
9107   {
9108     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9109     uintptr_t base=(uintptr_t)ndrc->translation_cache+((expirep>>13)<<shift); // Base address of this block
9110     inv_debug("EXP: Phase %d\n",expirep);
9111     switch((expirep>>11)&3)
9112     {
9113       case 0:
9114         // Clear jump_in and jump_dirty
9115         ll_remove_matching_addrs(jump_in+(expirep&2047),base,shift);
9116         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base,shift);
9117         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base,shift);
9118         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base,shift);
9119         break;
9120       case 1:
9121         // Clear pointers
9122         ll_kill_pointers(jump_out[expirep&2047],base,shift);
9123         ll_kill_pointers(jump_out[(expirep&2047)+2048],base,shift);
9124         break;
9125       case 2:
9126         // Clear hash table
9127         for(i=0;i<32;i++) {
9128           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9129           if (((uintptr_t)ht_bin->tcaddr[1]>>shift) == (base>>shift) ||
9130              (((uintptr_t)ht_bin->tcaddr[1]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9131             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9132             ht_bin->vaddr[1] = -1;
9133             ht_bin->tcaddr[1] = NULL;
9134           }
9135           if (((uintptr_t)ht_bin->tcaddr[0]>>shift) == (base>>shift) ||
9136              (((uintptr_t)ht_bin->tcaddr[0]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9137             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9138             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9139             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9140             ht_bin->vaddr[1] = -1;
9141             ht_bin->tcaddr[1] = NULL;
9142           }
9143         }
9144         break;
9145       case 3:
9146         // Clear jump_out
9147         if((expirep&2047)==0)
9148           do_clear_cache();
9149         ll_remove_matching_addrs(jump_out+(expirep&2047),base,shift);
9150         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base,shift);
9151         break;
9152     }
9153     expirep=(expirep+1)&65535;
9154   }
9155   return 0;
9156 }
9157
9158 // vim:shiftwidth=2:expandtab