drc: adjust constants, 32bit is enough
[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 (t&&*adj) {
4482       int rel=t-i;
4483       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4484         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4485     }
4486     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4487     jaddr=out;
4488     emit_jns(0);
4489   }
4490   else
4491   {
4492     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4493     jaddr=out;
4494     emit_jns(0);
4495   }
4496   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4497 }
4498
4499 static void do_ccstub(int n)
4500 {
4501   literal_pool(256);
4502   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4503   set_jump_target(stubs[n].addr, out);
4504   int i=stubs[n].b;
4505   if(stubs[n].d==NULLDS) {
4506     // Delay slot instruction is nullified ("likely" branch)
4507     wb_dirtys(regs[i].regmap,regs[i].dirty);
4508   }
4509   else if(stubs[n].d!=TAKEN) {
4510     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4511   }
4512   else {
4513     if(internal_branch(ba[i]))
4514       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4515   }
4516   if(stubs[n].c!=-1)
4517   {
4518     // Save PC as return address
4519     emit_movimm(stubs[n].c,EAX);
4520     emit_writeword(EAX,&pcaddr);
4521   }
4522   else
4523   {
4524     // Return address depends on which way the branch goes
4525     if(itype[i]==CJUMP||itype[i]==SJUMP)
4526     {
4527       int s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4528       int s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4529       if(rs1[i]==0)
4530       {
4531         s1l=s2l;
4532         s2l=-1;
4533       }
4534       else if(rs2[i]==0)
4535       {
4536         s2l=-1;
4537       }
4538       assert(s1l>=0);
4539       #ifdef DESTRUCTIVE_WRITEBACK
4540       if(rs1[i]) {
4541         if((branch_regs[i].dirty>>s1l)&&1)
4542           emit_loadreg(rs1[i],s1l);
4543       }
4544       else {
4545         if((branch_regs[i].dirty>>s1l)&1)
4546           emit_loadreg(rs2[i],s1l);
4547       }
4548       if(s2l>=0)
4549         if((branch_regs[i].dirty>>s2l)&1)
4550           emit_loadreg(rs2[i],s2l);
4551       #endif
4552       int hr=0;
4553       int addr=-1,alt=-1,ntaddr=-1;
4554       while(hr<HOST_REGS)
4555       {
4556         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4557            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4558            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4559         {
4560           addr=hr++;break;
4561         }
4562         hr++;
4563       }
4564       while(hr<HOST_REGS)
4565       {
4566         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4567            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4568            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4569         {
4570           alt=hr++;break;
4571         }
4572         hr++;
4573       }
4574       if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
4575       {
4576         while(hr<HOST_REGS)
4577         {
4578           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4579              (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4580              (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4581           {
4582             ntaddr=hr;break;
4583           }
4584           hr++;
4585         }
4586         assert(hr<HOST_REGS);
4587       }
4588       if((opcode[i]&0x2f)==4) // BEQ
4589       {
4590         #ifdef HAVE_CMOV_IMM
4591         if(s2l>=0) emit_cmp(s1l,s2l);
4592         else emit_test(s1l,s1l);
4593         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4594         #else
4595         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4596         if(s2l>=0) emit_cmp(s1l,s2l);
4597         else emit_test(s1l,s1l);
4598         emit_cmovne_reg(alt,addr);
4599         #endif
4600       }
4601       if((opcode[i]&0x2f)==5) // BNE
4602       {
4603         #ifdef HAVE_CMOV_IMM
4604         if(s2l>=0) emit_cmp(s1l,s2l);
4605         else emit_test(s1l,s1l);
4606         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4607         #else
4608         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4609         if(s2l>=0) emit_cmp(s1l,s2l);
4610         else emit_test(s1l,s1l);
4611         emit_cmovne_reg(alt,addr);
4612         #endif
4613       }
4614       if((opcode[i]&0x2f)==6) // BLEZ
4615       {
4616         //emit_movimm(ba[i],alt);
4617         //emit_movimm(start+i*4+8,addr);
4618         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4619         emit_cmpimm(s1l,1);
4620         emit_cmovl_reg(alt,addr);
4621       }
4622       if((opcode[i]&0x2f)==7) // BGTZ
4623       {
4624         //emit_movimm(ba[i],addr);
4625         //emit_movimm(start+i*4+8,ntaddr);
4626         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4627         emit_cmpimm(s1l,1);
4628         emit_cmovl_reg(ntaddr,addr);
4629       }
4630       if((opcode[i]==1)&&(opcode2[i]&0x2D)==0) // BLTZ
4631       {
4632         //emit_movimm(ba[i],alt);
4633         //emit_movimm(start+i*4+8,addr);
4634         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4635         emit_test(s1l,s1l);
4636         emit_cmovs_reg(alt,addr);
4637       }
4638       if((opcode[i]==1)&&(opcode2[i]&0x2D)==1) // BGEZ
4639       {
4640         //emit_movimm(ba[i],addr);
4641         //emit_movimm(start+i*4+8,alt);
4642         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4643         emit_test(s1l,s1l);
4644         emit_cmovs_reg(alt,addr);
4645       }
4646       if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
4647         if(source[i]&0x10000) // BC1T
4648         {
4649           //emit_movimm(ba[i],alt);
4650           //emit_movimm(start+i*4+8,addr);
4651           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4652           emit_testimm(s1l,0x800000);
4653           emit_cmovne_reg(alt,addr);
4654         }
4655         else // BC1F
4656         {
4657           //emit_movimm(ba[i],addr);
4658           //emit_movimm(start+i*4+8,alt);
4659           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4660           emit_testimm(s1l,0x800000);
4661           emit_cmovne_reg(alt,addr);
4662         }
4663       }
4664       emit_writeword(addr,&pcaddr);
4665     }
4666     else
4667     if(itype[i]==RJUMP)
4668     {
4669       int r=get_reg(branch_regs[i].regmap,rs1[i]);
4670       if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4671         r=get_reg(branch_regs[i].regmap,RTEMP);
4672       }
4673       emit_writeword(r,&pcaddr);
4674     }
4675     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4676   }
4677   // Update cycle count
4678   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4679   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4680   emit_far_call(cc_interrupt);
4681   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4682   if(stubs[n].d==TAKEN) {
4683     if(internal_branch(ba[i]))
4684       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4685     else if(itype[i]==RJUMP) {
4686       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4687         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4688       else
4689         emit_loadreg(rs1[i],get_reg(branch_regs[i].regmap,rs1[i]));
4690     }
4691   }else if(stubs[n].d==NOTTAKEN) {
4692     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4693     else load_all_regs(branch_regs[i].regmap);
4694   }else if(stubs[n].d==NULLDS) {
4695     // Delay slot instruction is nullified ("likely" branch)
4696     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
4697     else load_all_regs(regs[i].regmap);
4698   }else{
4699     load_all_regs(branch_regs[i].regmap);
4700   }
4701   if (stubs[n].retaddr)
4702     emit_jmp(stubs[n].retaddr);
4703   else
4704     do_jump_vaddr(stubs[n].e);
4705 }
4706
4707 static void add_to_linker(void *addr, u_int target, int ext)
4708 {
4709   assert(linkcount < ARRAY_SIZE(link_addr));
4710   link_addr[linkcount].addr = addr;
4711   link_addr[linkcount].target = target;
4712   link_addr[linkcount].ext = ext;
4713   linkcount++;
4714 }
4715
4716 static void ujump_assemble_write_ra(int i)
4717 {
4718   int rt;
4719   unsigned int return_address;
4720   rt=get_reg(branch_regs[i].regmap,31);
4721   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]);
4722   //assert(rt>=0);
4723   return_address=start+i*4+8;
4724   if(rt>=0) {
4725     #ifdef USE_MINI_HT
4726     if(internal_branch(return_address)&&rt1[i+1]!=31) {
4727       int temp=-1; // note: must be ds-safe
4728       #ifdef HOST_TEMPREG
4729       temp=HOST_TEMPREG;
4730       #endif
4731       if(temp>=0) do_miniht_insert(return_address,rt,temp);
4732       else emit_movimm(return_address,rt);
4733     }
4734     else
4735     #endif
4736     {
4737       #ifdef REG_PREFETCH
4738       if(temp>=0)
4739       {
4740         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4741       }
4742       #endif
4743       emit_movimm(return_address,rt); // PC into link register
4744       #ifdef IMM_PREFETCH
4745       emit_prefetch(hash_table_get(return_address));
4746       #endif
4747     }
4748   }
4749 }
4750
4751 static void ujump_assemble(int i,struct regstat *i_regs)
4752 {
4753   int ra_done=0;
4754   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
4755   address_generation(i+1,i_regs,regs[i].regmap_entry);
4756   #ifdef REG_PREFETCH
4757   int temp=get_reg(branch_regs[i].regmap,PTEMP);
4758   if(rt1[i]==31&&temp>=0)
4759   {
4760     signed char *i_regmap=i_regs->regmap;
4761     int return_address=start+i*4+8;
4762     if(get_reg(branch_regs[i].regmap,31)>0)
4763     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4764   }
4765   #endif
4766   if(rt1[i]==31&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
4767     ujump_assemble_write_ra(i); // writeback ra for DS
4768     ra_done=1;
4769   }
4770   ds_assemble(i+1,i_regs);
4771   uint64_t bc_unneeded=branch_regs[i].u;
4772   bc_unneeded|=1|(1LL<<rt1[i]);
4773   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4774   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
4775   if(!ra_done&&rt1[i]==31)
4776     ujump_assemble_write_ra(i);
4777   int cc,adj;
4778   cc=get_reg(branch_regs[i].regmap,CCREG);
4779   assert(cc==HOST_CCREG);
4780   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4781   #ifdef REG_PREFETCH
4782   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
4783   #endif
4784   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
4785   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
4786   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4787   if(internal_branch(ba[i]))
4788     assem_debug("branch: internal\n");
4789   else
4790     assem_debug("branch: external\n");
4791   if(internal_branch(ba[i])&&is_ds[(ba[i]-start)>>2]) {
4792     ds_assemble_entry(i);
4793   }
4794   else {
4795     add_to_linker(out,ba[i],internal_branch(ba[i]));
4796     emit_jmp(0);
4797   }
4798 }
4799
4800 static void rjump_assemble_write_ra(int i)
4801 {
4802   int rt,return_address;
4803   assert(rt1[i+1]!=rt1[i]);
4804   assert(rt2[i+1]!=rt1[i]);
4805   rt=get_reg(branch_regs[i].regmap,rt1[i]);
4806   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]);
4807   assert(rt>=0);
4808   return_address=start+i*4+8;
4809   #ifdef REG_PREFETCH
4810   if(temp>=0)
4811   {
4812     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4813   }
4814   #endif
4815   emit_movimm(return_address,rt); // PC into link register
4816   #ifdef IMM_PREFETCH
4817   emit_prefetch(hash_table_get(return_address));
4818   #endif
4819 }
4820
4821 static void rjump_assemble(int i,struct regstat *i_regs)
4822 {
4823   int temp;
4824   int rs,cc;
4825   int ra_done=0;
4826   rs=get_reg(branch_regs[i].regmap,rs1[i]);
4827   assert(rs>=0);
4828   if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4829     // Delay slot abuse, make a copy of the branch address register
4830     temp=get_reg(branch_regs[i].regmap,RTEMP);
4831     assert(temp>=0);
4832     assert(regs[i].regmap[temp]==RTEMP);
4833     emit_mov(rs,temp);
4834     rs=temp;
4835   }
4836   address_generation(i+1,i_regs,regs[i].regmap_entry);
4837   #ifdef REG_PREFETCH
4838   if(rt1[i]==31)
4839   {
4840     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
4841       signed char *i_regmap=i_regs->regmap;
4842       int return_address=start+i*4+8;
4843       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
4844     }
4845   }
4846   #endif
4847   #ifdef USE_MINI_HT
4848   if(rs1[i]==31) {
4849     int rh=get_reg(regs[i].regmap,RHASH);
4850     if(rh>=0) do_preload_rhash(rh);
4851   }
4852   #endif
4853   if(rt1[i]!=0&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
4854     rjump_assemble_write_ra(i);
4855     ra_done=1;
4856   }
4857   ds_assemble(i+1,i_regs);
4858   uint64_t bc_unneeded=branch_regs[i].u;
4859   bc_unneeded|=1|(1LL<<rt1[i]);
4860   bc_unneeded&=~(1LL<<rs1[i]);
4861   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4862   load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],CCREG);
4863   if(!ra_done&&rt1[i]!=0)
4864     rjump_assemble_write_ra(i);
4865   cc=get_reg(branch_regs[i].regmap,CCREG);
4866   assert(cc==HOST_CCREG);
4867   (void)cc;
4868   #ifdef USE_MINI_HT
4869   int rh=get_reg(branch_regs[i].regmap,RHASH);
4870   int ht=get_reg(branch_regs[i].regmap,RHTBL);
4871   if(rs1[i]==31) {
4872     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
4873     do_preload_rhtbl(ht);
4874     do_rhash(rs,rh);
4875   }
4876   #endif
4877   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
4878   #ifdef DESTRUCTIVE_WRITEBACK
4879   if((branch_regs[i].dirty>>rs)&1) {
4880     if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
4881       emit_loadreg(rs1[i],rs);
4882     }
4883   }
4884   #endif
4885   #ifdef REG_PREFETCH
4886   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
4887   #endif
4888   #ifdef USE_MINI_HT
4889   if(rs1[i]==31) {
4890     do_miniht_load(ht,rh);
4891   }
4892   #endif
4893   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
4894   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
4895   //assert(adj==0);
4896   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
4897   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
4898   if(itype[i+1]==COP0&&(source[i+1]&0x3f)==0x10)
4899     // special case for RFE
4900     emit_jmp(0);
4901   else
4902     emit_jns(0);
4903   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
4904   #ifdef USE_MINI_HT
4905   if(rs1[i]==31) {
4906     do_miniht_jump(rs,rh,ht);
4907   }
4908   else
4909   #endif
4910   {
4911     do_jump_vaddr(rs);
4912   }
4913   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
4914   if(rt1[i]!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
4915   #endif
4916 }
4917
4918 static void cjump_assemble(int i,struct regstat *i_regs)
4919 {
4920   signed char *i_regmap=i_regs->regmap;
4921   int cc;
4922   int match;
4923   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4924   assem_debug("match=%d\n",match);
4925   int s1l,s2l;
4926   int unconditional=0,nop=0;
4927   int invert=0;
4928   int internal=internal_branch(ba[i]);
4929   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
4930   if(!match) invert=1;
4931   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
4932   if(i>(ba[i]-start)>>2) invert=1;
4933   #endif
4934   #ifdef __aarch64__
4935   invert=1; // because of near cond. branches
4936   #endif
4937
4938   if(ooo[i]) {
4939     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4940     s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4941   }
4942   else {
4943     s1l=get_reg(i_regmap,rs1[i]);
4944     s2l=get_reg(i_regmap,rs2[i]);
4945   }
4946   if(rs1[i]==0&&rs2[i]==0)
4947   {
4948     if(opcode[i]&1) nop=1;
4949     else unconditional=1;
4950     //assert(opcode[i]!=5);
4951     //assert(opcode[i]!=7);
4952     //assert(opcode[i]!=0x15);
4953     //assert(opcode[i]!=0x17);
4954   }
4955   else if(rs1[i]==0)
4956   {
4957     s1l=s2l;
4958     s2l=-1;
4959   }
4960   else if(rs2[i]==0)
4961   {
4962     s2l=-1;
4963   }
4964
4965   if(ooo[i]) {
4966     // Out of order execution (delay slot first)
4967     //printf("OOOE\n");
4968     address_generation(i+1,i_regs,regs[i].regmap_entry);
4969     ds_assemble(i+1,i_regs);
4970     int adj;
4971     uint64_t bc_unneeded=branch_regs[i].u;
4972     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
4973     bc_unneeded|=1;
4974     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
4975     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs2[i]);
4976     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
4977     cc=get_reg(branch_regs[i].regmap,CCREG);
4978     assert(cc==HOST_CCREG);
4979     if(unconditional)
4980       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4981     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
4982     //assem_debug("cycle count (adj)\n");
4983     if(unconditional) {
4984       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
4985       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
4986         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
4987         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4988         if(internal)
4989           assem_debug("branch: internal\n");
4990         else
4991           assem_debug("branch: external\n");
4992         if(internal&&is_ds[(ba[i]-start)>>2]) {
4993           ds_assemble_entry(i);
4994         }
4995         else {
4996           add_to_linker(out,ba[i],internal);
4997           emit_jmp(0);
4998         }
4999         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5000         if(((u_int)out)&7) emit_addnop(0);
5001         #endif
5002       }
5003     }
5004     else if(nop) {
5005       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5006       void *jaddr=out;
5007       emit_jns(0);
5008       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5009     }
5010     else {
5011       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5012       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5013       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5014
5015       //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]);
5016       assert(s1l>=0);
5017       if(opcode[i]==4) // BEQ
5018       {
5019         if(s2l>=0) emit_cmp(s1l,s2l);
5020         else emit_test(s1l,s1l);
5021         if(invert){
5022           nottaken=out;
5023           emit_jne(DJT_1);
5024         }else{
5025           add_to_linker(out,ba[i],internal);
5026           emit_jeq(0);
5027         }
5028       }
5029       if(opcode[i]==5) // BNE
5030       {
5031         if(s2l>=0) emit_cmp(s1l,s2l);
5032         else emit_test(s1l,s1l);
5033         if(invert){
5034           nottaken=out;
5035           emit_jeq(DJT_1);
5036         }else{
5037           add_to_linker(out,ba[i],internal);
5038           emit_jne(0);
5039         }
5040       }
5041       if(opcode[i]==6) // BLEZ
5042       {
5043         emit_cmpimm(s1l,1);
5044         if(invert){
5045           nottaken=out;
5046           emit_jge(DJT_1);
5047         }else{
5048           add_to_linker(out,ba[i],internal);
5049           emit_jl(0);
5050         }
5051       }
5052       if(opcode[i]==7) // BGTZ
5053       {
5054         emit_cmpimm(s1l,1);
5055         if(invert){
5056           nottaken=out;
5057           emit_jl(DJT_1);
5058         }else{
5059           add_to_linker(out,ba[i],internal);
5060           emit_jge(0);
5061         }
5062       }
5063       if(invert) {
5064         if(taken) set_jump_target(taken, out);
5065         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5066         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5067           if(adj) {
5068             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5069             add_to_linker(out,ba[i],internal);
5070           }else{
5071             emit_addnop(13);
5072             add_to_linker(out,ba[i],internal*2);
5073           }
5074           emit_jmp(0);
5075         }else
5076         #endif
5077         {
5078           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5079           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5080           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5081           if(internal)
5082             assem_debug("branch: internal\n");
5083           else
5084             assem_debug("branch: external\n");
5085           if(internal&&is_ds[(ba[i]-start)>>2]) {
5086             ds_assemble_entry(i);
5087           }
5088           else {
5089             add_to_linker(out,ba[i],internal);
5090             emit_jmp(0);
5091           }
5092         }
5093         set_jump_target(nottaken, out);
5094       }
5095
5096       if(nottaken1) set_jump_target(nottaken1, out);
5097       if(adj) {
5098         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5099       }
5100     } // (!unconditional)
5101   } // if(ooo)
5102   else
5103   {
5104     // In-order execution (branch first)
5105     //if(likely[i]) printf("IOL\n");
5106     //else
5107     //printf("IOE\n");
5108     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5109     if(!unconditional&&!nop) {
5110       //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]);
5111       assert(s1l>=0);
5112       if((opcode[i]&0x2f)==4) // BEQ
5113       {
5114         if(s2l>=0) emit_cmp(s1l,s2l);
5115         else emit_test(s1l,s1l);
5116         nottaken=out;
5117         emit_jne(DJT_2);
5118       }
5119       if((opcode[i]&0x2f)==5) // BNE
5120       {
5121         if(s2l>=0) emit_cmp(s1l,s2l);
5122         else emit_test(s1l,s1l);
5123         nottaken=out;
5124         emit_jeq(DJT_2);
5125       }
5126       if((opcode[i]&0x2f)==6) // BLEZ
5127       {
5128         emit_cmpimm(s1l,1);
5129         nottaken=out;
5130         emit_jge(DJT_2);
5131       }
5132       if((opcode[i]&0x2f)==7) // BGTZ
5133       {
5134         emit_cmpimm(s1l,1);
5135         nottaken=out;
5136         emit_jl(DJT_2);
5137       }
5138     } // if(!unconditional)
5139     int adj;
5140     uint64_t ds_unneeded=branch_regs[i].u;
5141     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5142     ds_unneeded|=1;
5143     // branch taken
5144     if(!nop) {
5145       if(taken) set_jump_target(taken, out);
5146       assem_debug("1:\n");
5147       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5148       // load regs
5149       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5150       address_generation(i+1,&branch_regs[i],0);
5151       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5152       ds_assemble(i+1,&branch_regs[i]);
5153       cc=get_reg(branch_regs[i].regmap,CCREG);
5154       if(cc==-1) {
5155         emit_loadreg(CCREG,cc=HOST_CCREG);
5156         // CHECK: Is the following instruction (fall thru) allocated ok?
5157       }
5158       assert(cc==HOST_CCREG);
5159       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5160       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5161       assem_debug("cycle count (adj)\n");
5162       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5163       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5164       if(internal)
5165         assem_debug("branch: internal\n");
5166       else
5167         assem_debug("branch: external\n");
5168       if(internal&&is_ds[(ba[i]-start)>>2]) {
5169         ds_assemble_entry(i);
5170       }
5171       else {
5172         add_to_linker(out,ba[i],internal);
5173         emit_jmp(0);
5174       }
5175     }
5176     // branch not taken
5177     if(!unconditional) {
5178       if(nottaken1) set_jump_target(nottaken1, out);
5179       set_jump_target(nottaken, out);
5180       assem_debug("2:\n");
5181       if(!likely[i]) {
5182         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5183         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5184         address_generation(i+1,&branch_regs[i],0);
5185         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5186         ds_assemble(i+1,&branch_regs[i]);
5187       }
5188       cc=get_reg(branch_regs[i].regmap,CCREG);
5189       if(cc==-1&&!likely[i]) {
5190         // Cycle count isn't in a register, temporarily load it then write it out
5191         emit_loadreg(CCREG,HOST_CCREG);
5192         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5193         void *jaddr=out;
5194         emit_jns(0);
5195         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5196         emit_storereg(CCREG,HOST_CCREG);
5197       }
5198       else{
5199         cc=get_reg(i_regmap,CCREG);
5200         assert(cc==HOST_CCREG);
5201         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5202         void *jaddr=out;
5203         emit_jns(0);
5204         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5205       }
5206     }
5207   }
5208 }
5209
5210 static void sjump_assemble(int i,struct regstat *i_regs)
5211 {
5212   signed char *i_regmap=i_regs->regmap;
5213   int cc;
5214   int match;
5215   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5216   assem_debug("smatch=%d\n",match);
5217   int s1l;
5218   int unconditional=0,nevertaken=0;
5219   int invert=0;
5220   int internal=internal_branch(ba[i]);
5221   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5222   if(!match) invert=1;
5223   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5224   if(i>(ba[i]-start)>>2) invert=1;
5225   #endif
5226   #ifdef __aarch64__
5227   invert=1; // because of near cond. branches
5228   #endif
5229
5230   //if(opcode2[i]>=0x10) return; // FIXME (BxxZAL)
5231   //assert(opcode2[i]<0x10||rs1[i]==0); // FIXME (BxxZAL)
5232
5233   if(ooo[i]) {
5234     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5235   }
5236   else {
5237     s1l=get_reg(i_regmap,rs1[i]);
5238   }
5239   if(rs1[i]==0)
5240   {
5241     if(opcode2[i]&1) unconditional=1;
5242     else nevertaken=1;
5243     // These are never taken (r0 is never less than zero)
5244     //assert(opcode2[i]!=0);
5245     //assert(opcode2[i]!=2);
5246     //assert(opcode2[i]!=0x10);
5247     //assert(opcode2[i]!=0x12);
5248   }
5249
5250   if(ooo[i]) {
5251     // Out of order execution (delay slot first)
5252     //printf("OOOE\n");
5253     address_generation(i+1,i_regs,regs[i].regmap_entry);
5254     ds_assemble(i+1,i_regs);
5255     int adj;
5256     uint64_t bc_unneeded=branch_regs[i].u;
5257     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5258     bc_unneeded|=1;
5259     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5260     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs1[i]);
5261     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5262     if(rt1[i]==31) {
5263       int rt,return_address;
5264       rt=get_reg(branch_regs[i].regmap,31);
5265       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]);
5266       if(rt>=0) {
5267         // Save the PC even if the branch is not taken
5268         return_address=start+i*4+8;
5269         emit_movimm(return_address,rt); // PC into link register
5270         #ifdef IMM_PREFETCH
5271         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5272         #endif
5273       }
5274     }
5275     cc=get_reg(branch_regs[i].regmap,CCREG);
5276     assert(cc==HOST_CCREG);
5277     if(unconditional)
5278       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5279     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5280     assem_debug("cycle count (adj)\n");
5281     if(unconditional) {
5282       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5283       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5284         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5285         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5286         if(internal)
5287           assem_debug("branch: internal\n");
5288         else
5289           assem_debug("branch: external\n");
5290         if(internal&&is_ds[(ba[i]-start)>>2]) {
5291           ds_assemble_entry(i);
5292         }
5293         else {
5294           add_to_linker(out,ba[i],internal);
5295           emit_jmp(0);
5296         }
5297         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5298         if(((u_int)out)&7) emit_addnop(0);
5299         #endif
5300       }
5301     }
5302     else if(nevertaken) {
5303       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5304       void *jaddr=out;
5305       emit_jns(0);
5306       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5307     }
5308     else {
5309       void *nottaken = NULL;
5310       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5311       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5312       {
5313         assert(s1l>=0);
5314         if((opcode2[i]&0xf)==0) // BLTZ/BLTZAL
5315         {
5316           emit_test(s1l,s1l);
5317           if(invert){
5318             nottaken=out;
5319             emit_jns(DJT_1);
5320           }else{
5321             add_to_linker(out,ba[i],internal);
5322             emit_js(0);
5323           }
5324         }
5325         if((opcode2[i]&0xf)==1) // BGEZ/BLTZAL
5326         {
5327           emit_test(s1l,s1l);
5328           if(invert){
5329             nottaken=out;
5330             emit_js(DJT_1);
5331           }else{
5332             add_to_linker(out,ba[i],internal);
5333             emit_jns(0);
5334           }
5335         }
5336       }
5337
5338       if(invert) {
5339         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5340         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5341           if(adj) {
5342             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5343             add_to_linker(out,ba[i],internal);
5344           }else{
5345             emit_addnop(13);
5346             add_to_linker(out,ba[i],internal*2);
5347           }
5348           emit_jmp(0);
5349         }else
5350         #endif
5351         {
5352           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5353           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5354           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5355           if(internal)
5356             assem_debug("branch: internal\n");
5357           else
5358             assem_debug("branch: external\n");
5359           if(internal&&is_ds[(ba[i]-start)>>2]) {
5360             ds_assemble_entry(i);
5361           }
5362           else {
5363             add_to_linker(out,ba[i],internal);
5364             emit_jmp(0);
5365           }
5366         }
5367         set_jump_target(nottaken, out);
5368       }
5369
5370       if(adj) {
5371         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5372       }
5373     } // (!unconditional)
5374   } // if(ooo)
5375   else
5376   {
5377     // In-order execution (branch first)
5378     //printf("IOE\n");
5379     void *nottaken = NULL;
5380     if(rt1[i]==31) {
5381       int rt,return_address;
5382       rt=get_reg(branch_regs[i].regmap,31);
5383       if(rt>=0) {
5384         // Save the PC even if the branch is not taken
5385         return_address=start+i*4+8;
5386         emit_movimm(return_address,rt); // PC into link register
5387         #ifdef IMM_PREFETCH
5388         emit_prefetch(hash_table_get(return_address));
5389         #endif
5390       }
5391     }
5392     if(!unconditional) {
5393       //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]);
5394         assert(s1l>=0);
5395         if((opcode2[i]&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5396         {
5397           emit_test(s1l,s1l);
5398           nottaken=out;
5399           emit_jns(DJT_1);
5400         }
5401         if((opcode2[i]&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5402         {
5403           emit_test(s1l,s1l);
5404           nottaken=out;
5405           emit_js(DJT_1);
5406         }
5407     } // if(!unconditional)
5408     int adj;
5409     uint64_t ds_unneeded=branch_regs[i].u;
5410     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5411     ds_unneeded|=1;
5412     // branch taken
5413     if(!nevertaken) {
5414       //assem_debug("1:\n");
5415       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5416       // load regs
5417       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5418       address_generation(i+1,&branch_regs[i],0);
5419       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5420       ds_assemble(i+1,&branch_regs[i]);
5421       cc=get_reg(branch_regs[i].regmap,CCREG);
5422       if(cc==-1) {
5423         emit_loadreg(CCREG,cc=HOST_CCREG);
5424         // CHECK: Is the following instruction (fall thru) allocated ok?
5425       }
5426       assert(cc==HOST_CCREG);
5427       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5428       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5429       assem_debug("cycle count (adj)\n");
5430       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5431       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5432       if(internal)
5433         assem_debug("branch: internal\n");
5434       else
5435         assem_debug("branch: external\n");
5436       if(internal&&is_ds[(ba[i]-start)>>2]) {
5437         ds_assemble_entry(i);
5438       }
5439       else {
5440         add_to_linker(out,ba[i],internal);
5441         emit_jmp(0);
5442       }
5443     }
5444     // branch not taken
5445     if(!unconditional) {
5446       set_jump_target(nottaken, out);
5447       assem_debug("1:\n");
5448       if(!likely[i]) {
5449         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5450         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5451         address_generation(i+1,&branch_regs[i],0);
5452         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5453         ds_assemble(i+1,&branch_regs[i]);
5454       }
5455       cc=get_reg(branch_regs[i].regmap,CCREG);
5456       if(cc==-1&&!likely[i]) {
5457         // Cycle count isn't in a register, temporarily load it then write it out
5458         emit_loadreg(CCREG,HOST_CCREG);
5459         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5460         void *jaddr=out;
5461         emit_jns(0);
5462         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5463         emit_storereg(CCREG,HOST_CCREG);
5464       }
5465       else{
5466         cc=get_reg(i_regmap,CCREG);
5467         assert(cc==HOST_CCREG);
5468         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5469         void *jaddr=out;
5470         emit_jns(0);
5471         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5472       }
5473     }
5474   }
5475 }
5476
5477 static void pagespan_assemble(int i,struct regstat *i_regs)
5478 {
5479   int s1l=get_reg(i_regs->regmap,rs1[i]);
5480   int s2l=get_reg(i_regs->regmap,rs2[i]);
5481   void *taken = NULL;
5482   void *nottaken = NULL;
5483   int unconditional=0;
5484   if(rs1[i]==0)
5485   {
5486     s1l=s2l;
5487     s2l=-1;
5488   }
5489   else if(rs2[i]==0)
5490   {
5491     s2l=-1;
5492   }
5493   int hr=0;
5494   int addr=-1,alt=-1,ntaddr=-1;
5495   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5496   else {
5497     while(hr<HOST_REGS)
5498     {
5499       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5500          (i_regs->regmap[hr]&63)!=rs1[i] &&
5501          (i_regs->regmap[hr]&63)!=rs2[i] )
5502       {
5503         addr=hr++;break;
5504       }
5505       hr++;
5506     }
5507   }
5508   while(hr<HOST_REGS)
5509   {
5510     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5511        (i_regs->regmap[hr]&63)!=rs1[i] &&
5512        (i_regs->regmap[hr]&63)!=rs2[i] )
5513     {
5514       alt=hr++;break;
5515     }
5516     hr++;
5517   }
5518   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
5519   {
5520     while(hr<HOST_REGS)
5521     {
5522       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5523          (i_regs->regmap[hr]&63)!=rs1[i] &&
5524          (i_regs->regmap[hr]&63)!=rs2[i] )
5525       {
5526         ntaddr=hr;break;
5527       }
5528       hr++;
5529     }
5530   }
5531   assert(hr<HOST_REGS);
5532   if((opcode[i]&0x2e)==4||opcode[i]==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5533     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5534   }
5535   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5536   if(opcode[i]==2) // J
5537   {
5538     unconditional=1;
5539   }
5540   if(opcode[i]==3) // JAL
5541   {
5542     // TODO: mini_ht
5543     int rt=get_reg(i_regs->regmap,31);
5544     emit_movimm(start+i*4+8,rt);
5545     unconditional=1;
5546   }
5547   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
5548   {
5549     emit_mov(s1l,addr);
5550     if(opcode2[i]==9) // JALR
5551     {
5552       int rt=get_reg(i_regs->regmap,rt1[i]);
5553       emit_movimm(start+i*4+8,rt);
5554     }
5555   }
5556   if((opcode[i]&0x3f)==4) // BEQ
5557   {
5558     if(rs1[i]==rs2[i])
5559     {
5560       unconditional=1;
5561     }
5562     else
5563     #ifdef HAVE_CMOV_IMM
5564     if(1) {
5565       if(s2l>=0) emit_cmp(s1l,s2l);
5566       else emit_test(s1l,s1l);
5567       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5568     }
5569     else
5570     #endif
5571     {
5572       assert(s1l>=0);
5573       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5574       if(s2l>=0) emit_cmp(s1l,s2l);
5575       else emit_test(s1l,s1l);
5576       emit_cmovne_reg(alt,addr);
5577     }
5578   }
5579   if((opcode[i]&0x3f)==5) // BNE
5580   {
5581     #ifdef HAVE_CMOV_IMM
5582     if(s2l>=0) emit_cmp(s1l,s2l);
5583     else emit_test(s1l,s1l);
5584     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5585     #else
5586     assert(s1l>=0);
5587     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5588     if(s2l>=0) emit_cmp(s1l,s2l);
5589     else emit_test(s1l,s1l);
5590     emit_cmovne_reg(alt,addr);
5591     #endif
5592   }
5593   if((opcode[i]&0x3f)==0x14) // BEQL
5594   {
5595     if(s2l>=0) emit_cmp(s1l,s2l);
5596     else emit_test(s1l,s1l);
5597     if(nottaken) set_jump_target(nottaken, out);
5598     nottaken=out;
5599     emit_jne(0);
5600   }
5601   if((opcode[i]&0x3f)==0x15) // BNEL
5602   {
5603     if(s2l>=0) emit_cmp(s1l,s2l);
5604     else emit_test(s1l,s1l);
5605     nottaken=out;
5606     emit_jeq(0);
5607     if(taken) set_jump_target(taken, out);
5608   }
5609   if((opcode[i]&0x3f)==6) // BLEZ
5610   {
5611     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5612     emit_cmpimm(s1l,1);
5613     emit_cmovl_reg(alt,addr);
5614   }
5615   if((opcode[i]&0x3f)==7) // BGTZ
5616   {
5617     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5618     emit_cmpimm(s1l,1);
5619     emit_cmovl_reg(ntaddr,addr);
5620   }
5621   if((opcode[i]&0x3f)==0x16) // BLEZL
5622   {
5623     assert((opcode[i]&0x3f)!=0x16);
5624   }
5625   if((opcode[i]&0x3f)==0x17) // BGTZL
5626   {
5627     assert((opcode[i]&0x3f)!=0x17);
5628   }
5629   assert(opcode[i]!=1); // BLTZ/BGEZ
5630
5631   //FIXME: Check CSREG
5632   if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
5633     if((source[i]&0x30000)==0) // BC1F
5634     {
5635       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5636       emit_testimm(s1l,0x800000);
5637       emit_cmovne_reg(alt,addr);
5638     }
5639     if((source[i]&0x30000)==0x10000) // BC1T
5640     {
5641       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5642       emit_testimm(s1l,0x800000);
5643       emit_cmovne_reg(alt,addr);
5644     }
5645     if((source[i]&0x30000)==0x20000) // BC1FL
5646     {
5647       emit_testimm(s1l,0x800000);
5648       nottaken=out;
5649       emit_jne(0);
5650     }
5651     if((source[i]&0x30000)==0x30000) // BC1TL
5652     {
5653       emit_testimm(s1l,0x800000);
5654       nottaken=out;
5655       emit_jeq(0);
5656     }
5657   }
5658
5659   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5660   wb_dirtys(regs[i].regmap,regs[i].dirty);
5661   if(likely[i]||unconditional)
5662   {
5663     emit_movimm(ba[i],HOST_BTREG);
5664   }
5665   else if(addr!=HOST_BTREG)
5666   {
5667     emit_mov(addr,HOST_BTREG);
5668   }
5669   void *branch_addr=out;
5670   emit_jmp(0);
5671   int target_addr=start+i*4+5;
5672   void *stub=out;
5673   void *compiled_target_addr=check_addr(target_addr);
5674   emit_extjump_ds(branch_addr, target_addr);
5675   if(compiled_target_addr) {
5676     set_jump_target(branch_addr, compiled_target_addr);
5677     add_link(target_addr,stub);
5678   }
5679   else set_jump_target(branch_addr, stub);
5680   if(likely[i]) {
5681     // Not-taken path
5682     set_jump_target(nottaken, out);
5683     wb_dirtys(regs[i].regmap,regs[i].dirty);
5684     void *branch_addr=out;
5685     emit_jmp(0);
5686     int target_addr=start+i*4+8;
5687     void *stub=out;
5688     void *compiled_target_addr=check_addr(target_addr);
5689     emit_extjump_ds(branch_addr, target_addr);
5690     if(compiled_target_addr) {
5691       set_jump_target(branch_addr, compiled_target_addr);
5692       add_link(target_addr,stub);
5693     }
5694     else set_jump_target(branch_addr, stub);
5695   }
5696 }
5697
5698 // Assemble the delay slot for the above
5699 static void pagespan_ds()
5700 {
5701   assem_debug("initial delay slot:\n");
5702   u_int vaddr=start+1;
5703   u_int page=get_page(vaddr);
5704   u_int vpage=get_vpage(vaddr);
5705   ll_add(jump_dirty+vpage,vaddr,(void *)out);
5706   do_dirty_stub_ds();
5707   ll_add(jump_in+page,vaddr,(void *)out);
5708   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
5709   if(regs[0].regmap[HOST_CCREG]!=CCREG)
5710     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
5711   if(regs[0].regmap[HOST_BTREG]!=BTREG)
5712     emit_writeword(HOST_BTREG,&branch_target);
5713   load_regs(regs[0].regmap_entry,regs[0].regmap,rs1[0],rs2[0]);
5714   address_generation(0,&regs[0],regs[0].regmap_entry);
5715   if(itype[0]==STORE||itype[0]==STORELR||(opcode[0]&0x3b)==0x39||(opcode[0]&0x3b)==0x3a)
5716     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
5717   is_delayslot=0;
5718   switch(itype[0]) {
5719     case ALU:
5720       alu_assemble(0,&regs[0]);break;
5721     case IMM16:
5722       imm16_assemble(0,&regs[0]);break;
5723     case SHIFT:
5724       shift_assemble(0,&regs[0]);break;
5725     case SHIFTIMM:
5726       shiftimm_assemble(0,&regs[0]);break;
5727     case LOAD:
5728       load_assemble(0,&regs[0]);break;
5729     case LOADLR:
5730       loadlr_assemble(0,&regs[0]);break;
5731     case STORE:
5732       store_assemble(0,&regs[0]);break;
5733     case STORELR:
5734       storelr_assemble(0,&regs[0]);break;
5735     case COP0:
5736       cop0_assemble(0,&regs[0]);break;
5737     case COP1:
5738       cop1_assemble(0,&regs[0]);break;
5739     case C1LS:
5740       c1ls_assemble(0,&regs[0]);break;
5741     case COP2:
5742       cop2_assemble(0,&regs[0]);break;
5743     case C2LS:
5744       c2ls_assemble(0,&regs[0]);break;
5745     case C2OP:
5746       c2op_assemble(0,&regs[0]);break;
5747     case MULTDIV:
5748       multdiv_assemble(0,&regs[0]);break;
5749     case MOV:
5750       mov_assemble(0,&regs[0]);break;
5751     case SYSCALL:
5752     case HLECALL:
5753     case INTCALL:
5754     case SPAN:
5755     case UJUMP:
5756     case RJUMP:
5757     case CJUMP:
5758     case SJUMP:
5759       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
5760   }
5761   int btaddr=get_reg(regs[0].regmap,BTREG);
5762   if(btaddr<0) {
5763     btaddr=get_reg(regs[0].regmap,-1);
5764     emit_readword(&branch_target,btaddr);
5765   }
5766   assert(btaddr!=HOST_CCREG);
5767   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
5768 #ifdef HOST_IMM8
5769   host_tempreg_acquire();
5770   emit_movimm(start+4,HOST_TEMPREG);
5771   emit_cmp(btaddr,HOST_TEMPREG);
5772   host_tempreg_release();
5773 #else
5774   emit_cmpimm(btaddr,start+4);
5775 #endif
5776   void *branch = out;
5777   emit_jeq(0);
5778   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
5779   do_jump_vaddr(btaddr);
5780   set_jump_target(branch, out);
5781   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
5782   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
5783 }
5784
5785 // Basic liveness analysis for MIPS registers
5786 void unneeded_registers(int istart,int iend,int r)
5787 {
5788   int i;
5789   uint64_t u,gte_u,b,gte_b;
5790   uint64_t temp_u,temp_gte_u=0;
5791   uint64_t gte_u_unknown=0;
5792   if(new_dynarec_hacks&NDHACK_GTE_UNNEEDED)
5793     gte_u_unknown=~0ll;
5794   if(iend==slen-1) {
5795     u=1;
5796     gte_u=gte_u_unknown;
5797   }else{
5798     //u=unneeded_reg[iend+1];
5799     u=1;
5800     gte_u=gte_unneeded[iend+1];
5801   }
5802
5803   for (i=iend;i>=istart;i--)
5804   {
5805     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
5806     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
5807     {
5808       // If subroutine call, flag return address as a possible branch target
5809       if(rt1[i]==31 && i<slen-2) bt[i+2]=1;
5810
5811       if(ba[i]<start || ba[i]>=(start+slen*4))
5812       {
5813         // Branch out of this block, flush all regs
5814         u=1;
5815         gte_u=gte_u_unknown;
5816         branch_unneeded_reg[i]=u;
5817         // Merge in delay slot
5818         u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5819         u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5820         u|=1;
5821         gte_u|=gte_rt[i+1];
5822         gte_u&=~gte_rs[i+1];
5823         // If branch is "likely" (and conditional)
5824         // then we skip the delay slot on the fall-thru path
5825         if(likely[i]) {
5826           if(i<slen-1) {
5827             u&=unneeded_reg[i+2];
5828             gte_u&=gte_unneeded[i+2];
5829           }
5830           else
5831           {
5832             u=1;
5833             gte_u=gte_u_unknown;
5834           }
5835         }
5836       }
5837       else
5838       {
5839         // Internal branch, flag target
5840         bt[(ba[i]-start)>>2]=1;
5841         if(ba[i]<=start+i*4) {
5842           // Backward branch
5843           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
5844           {
5845             // Unconditional branch
5846             temp_u=1;
5847             temp_gte_u=0;
5848           } else {
5849             // Conditional branch (not taken case)
5850             temp_u=unneeded_reg[i+2];
5851             temp_gte_u&=gte_unneeded[i+2];
5852           }
5853           // Merge in delay slot
5854           temp_u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5855           temp_u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5856           temp_u|=1;
5857           temp_gte_u|=gte_rt[i+1];
5858           temp_gte_u&=~gte_rs[i+1];
5859           // If branch is "likely" (and conditional)
5860           // then we skip the delay slot on the fall-thru path
5861           if(likely[i]) {
5862             if(i<slen-1) {
5863               temp_u&=unneeded_reg[i+2];
5864               temp_gte_u&=gte_unneeded[i+2];
5865             }
5866             else
5867             {
5868               temp_u=1;
5869               temp_gte_u=gte_u_unknown;
5870             }
5871           }
5872           temp_u|=(1LL<<rt1[i])|(1LL<<rt2[i]);
5873           temp_u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5874           temp_u|=1;
5875           temp_gte_u|=gte_rt[i];
5876           temp_gte_u&=~gte_rs[i];
5877           unneeded_reg[i]=temp_u;
5878           gte_unneeded[i]=temp_gte_u;
5879           // Only go three levels deep.  This recursion can take an
5880           // excessive amount of time if there are a lot of nested loops.
5881           if(r<2) {
5882             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
5883           }else{
5884             unneeded_reg[(ba[i]-start)>>2]=1;
5885             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
5886           }
5887         } /*else*/ if(1) {
5888           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
5889           {
5890             // Unconditional branch
5891             u=unneeded_reg[(ba[i]-start)>>2];
5892             gte_u=gte_unneeded[(ba[i]-start)>>2];
5893             branch_unneeded_reg[i]=u;
5894             // Merge in delay slot
5895             u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5896             u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5897             u|=1;
5898             gte_u|=gte_rt[i+1];
5899             gte_u&=~gte_rs[i+1];
5900           } else {
5901             // Conditional branch
5902             b=unneeded_reg[(ba[i]-start)>>2];
5903             gte_b=gte_unneeded[(ba[i]-start)>>2];
5904             branch_unneeded_reg[i]=b;
5905             // Branch delay slot
5906             b|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
5907             b&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5908             b|=1;
5909             gte_b|=gte_rt[i+1];
5910             gte_b&=~gte_rs[i+1];
5911             // If branch is "likely" then we skip the
5912             // delay slot on the fall-thru path
5913             if(likely[i]) {
5914               u=b;
5915               gte_u=gte_b;
5916               if(i<slen-1) {
5917                 u&=unneeded_reg[i+2];
5918                 gte_u&=gte_unneeded[i+2];
5919               }
5920             } else {
5921               u&=b;
5922               gte_u&=gte_b;
5923             }
5924             if(i<slen-1) {
5925               branch_unneeded_reg[i]&=unneeded_reg[i+2];
5926             } else {
5927               branch_unneeded_reg[i]=1;
5928             }
5929           }
5930         }
5931       }
5932     }
5933     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
5934     {
5935       // SYSCALL instruction (software interrupt)
5936       u=1;
5937     }
5938     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
5939     {
5940       // ERET instruction (return from interrupt)
5941       u=1;
5942     }
5943     //u=1; // DEBUG
5944     // Written registers are unneeded
5945     u|=1LL<<rt1[i];
5946     u|=1LL<<rt2[i];
5947     gte_u|=gte_rt[i];
5948     // Accessed registers are needed
5949     u&=~(1LL<<rs1[i]);
5950     u&=~(1LL<<rs2[i]);
5951     gte_u&=~gte_rs[i];
5952     if(gte_rs[i]&&rt1[i]&&(unneeded_reg[i+1]&(1ll<<rt1[i])))
5953       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
5954     // Source-target dependencies
5955     // R0 is always unneeded
5956     u|=1;
5957     // Save it
5958     unneeded_reg[i]=u;
5959     gte_unneeded[i]=gte_u;
5960     /*
5961     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
5962     printf("U:");
5963     int r;
5964     for(r=1;r<=CCREG;r++) {
5965       if((unneeded_reg[i]>>r)&1) {
5966         if(r==HIREG) printf(" HI");
5967         else if(r==LOREG) printf(" LO");
5968         else printf(" r%d",r);
5969       }
5970     }
5971     printf("\n");
5972     */
5973   }
5974 }
5975
5976 // Write back dirty registers as soon as we will no longer modify them,
5977 // so that we don't end up with lots of writes at the branches.
5978 void clean_registers(int istart,int iend,int wr)
5979 {
5980   int i;
5981   int r;
5982   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
5983   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
5984   if(iend==slen-1) {
5985     will_dirty_i=will_dirty_next=0;
5986     wont_dirty_i=wont_dirty_next=0;
5987   }else{
5988     will_dirty_i=will_dirty_next=will_dirty[iend+1];
5989     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
5990   }
5991   for (i=iend;i>=istart;i--)
5992   {
5993     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
5994     {
5995       if(ba[i]<start || ba[i]>=(start+slen*4))
5996       {
5997         // Branch out of this block, flush all regs
5998         if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
5999         {
6000           // Unconditional branch
6001           will_dirty_i=0;
6002           wont_dirty_i=0;
6003           // Merge in delay slot (will dirty)
6004           for(r=0;r<HOST_REGS;r++) {
6005             if(r!=EXCLUDE_REG) {
6006               if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6007               if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6008               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6009               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6010               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6011               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6012               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6013               if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6014               if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6015               if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6016               if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6017               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6018               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6019               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6020             }
6021           }
6022         }
6023         else
6024         {
6025           // Conditional branch
6026           will_dirty_i=0;
6027           wont_dirty_i=wont_dirty_next;
6028           // Merge in delay slot (will dirty)
6029           for(r=0;r<HOST_REGS;r++) {
6030             if(r!=EXCLUDE_REG) {
6031               if(!likely[i]) {
6032                 // Might not dirty if likely branch is not taken
6033                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6034                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6035                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6036                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6037                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6038                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6039                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6040                 //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6041                 //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6042                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6043                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6044                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6045                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6046                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6047               }
6048             }
6049           }
6050         }
6051         // Merge in delay slot (wont dirty)
6052         for(r=0;r<HOST_REGS;r++) {
6053           if(r!=EXCLUDE_REG) {
6054             if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6055             if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6056             if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6057             if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6058             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6059             if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6060             if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6061             if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6062             if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6063             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6064           }
6065         }
6066         if(wr) {
6067           #ifndef DESTRUCTIVE_WRITEBACK
6068           branch_regs[i].dirty&=wont_dirty_i;
6069           #endif
6070           branch_regs[i].dirty|=will_dirty_i;
6071         }
6072       }
6073       else
6074       {
6075         // Internal branch
6076         if(ba[i]<=start+i*4) {
6077           // Backward branch
6078           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
6079           {
6080             // Unconditional branch
6081             temp_will_dirty=0;
6082             temp_wont_dirty=0;
6083             // Merge in delay slot (will dirty)
6084             for(r=0;r<HOST_REGS;r++) {
6085               if(r!=EXCLUDE_REG) {
6086                 if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6087                 if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6088                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6089                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6090                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6091                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6092                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6093                 if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6094                 if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6095                 if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6096                 if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6097                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6098                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6099                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6100               }
6101             }
6102           } else {
6103             // Conditional branch (not taken case)
6104             temp_will_dirty=will_dirty_next;
6105             temp_wont_dirty=wont_dirty_next;
6106             // Merge in delay slot (will dirty)
6107             for(r=0;r<HOST_REGS;r++) {
6108               if(r!=EXCLUDE_REG) {
6109                 if(!likely[i]) {
6110                   // Will not dirty if likely branch is not taken
6111                   if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6112                   if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6113                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6114                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6115                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6116                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6117                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6118                   //if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6119                   //if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6120                   if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6121                   if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6122                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6123                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6124                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6125                 }
6126               }
6127             }
6128           }
6129           // Merge in delay slot (wont dirty)
6130           for(r=0;r<HOST_REGS;r++) {
6131             if(r!=EXCLUDE_REG) {
6132               if((regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6133               if((regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6134               if((regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6135               if((regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6136               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6137               if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6138               if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6139               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6140               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6141               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6142             }
6143           }
6144           // Deal with changed mappings
6145           if(i<iend) {
6146             for(r=0;r<HOST_REGS;r++) {
6147               if(r!=EXCLUDE_REG) {
6148                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6149                   temp_will_dirty&=~(1<<r);
6150                   temp_wont_dirty&=~(1<<r);
6151                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6152                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6153                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6154                   } else {
6155                     temp_will_dirty|=1<<r;
6156                     temp_wont_dirty|=1<<r;
6157                   }
6158                 }
6159               }
6160             }
6161           }
6162           if(wr) {
6163             will_dirty[i]=temp_will_dirty;
6164             wont_dirty[i]=temp_wont_dirty;
6165             clean_registers((ba[i]-start)>>2,i-1,0);
6166           }else{
6167             // Limit recursion.  It can take an excessive amount
6168             // of time if there are a lot of nested loops.
6169             will_dirty[(ba[i]-start)>>2]=0;
6170             wont_dirty[(ba[i]-start)>>2]=-1;
6171           }
6172         }
6173         /*else*/ if(1)
6174         {
6175           if(itype[i]==RJUMP||itype[i]==UJUMP||(source[i]>>16)==0x1000)
6176           {
6177             // Unconditional branch
6178             will_dirty_i=0;
6179             wont_dirty_i=0;
6180           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6181             for(r=0;r<HOST_REGS;r++) {
6182               if(r!=EXCLUDE_REG) {
6183                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6184                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6185                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6186                 }
6187                 if(branch_regs[i].regmap[r]>=0) {
6188                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6189                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6190                 }
6191               }
6192             }
6193           //}
6194             // Merge in delay slot
6195             for(r=0;r<HOST_REGS;r++) {
6196               if(r!=EXCLUDE_REG) {
6197                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6198                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6199                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6200                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6201                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6202                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6203                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6204                 if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6205                 if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6206                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6207                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6208                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6209                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6210                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6211               }
6212             }
6213           } else {
6214             // Conditional branch
6215             will_dirty_i=will_dirty_next;
6216             wont_dirty_i=wont_dirty_next;
6217           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6218             for(r=0;r<HOST_REGS;r++) {
6219               if(r!=EXCLUDE_REG) {
6220                 signed char target_reg=branch_regs[i].regmap[r];
6221                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6222                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6223                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6224                 }
6225                 else if(target_reg>=0) {
6226                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6227                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6228                 }
6229                 // Treat delay slot as part of branch too
6230                 /*if(regs[i+1].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6231                   will_dirty[i+1]&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6232                   wont_dirty[i+1]|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6233                 }
6234                 else
6235                 {
6236                   will_dirty[i+1]&=~(1<<r);
6237                 }*/
6238               }
6239             }
6240           //}
6241             // Merge in delay slot
6242             for(r=0;r<HOST_REGS;r++) {
6243               if(r!=EXCLUDE_REG) {
6244                 if(!likely[i]) {
6245                   // Might not dirty if likely branch is not taken
6246                   if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6247                   if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6248                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6249                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6250                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6251                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6252                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6253                   //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6254                   //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6255                   if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6256                   if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6257                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6258                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6259                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6260                 }
6261               }
6262             }
6263           }
6264           // Merge in delay slot (won't dirty)
6265           for(r=0;r<HOST_REGS;r++) {
6266             if(r!=EXCLUDE_REG) {
6267               if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6268               if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6269               if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6270               if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6271               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6272               if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6273               if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6274               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6275               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6276               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6277             }
6278           }
6279           if(wr) {
6280             #ifndef DESTRUCTIVE_WRITEBACK
6281             branch_regs[i].dirty&=wont_dirty_i;
6282             #endif
6283             branch_regs[i].dirty|=will_dirty_i;
6284           }
6285         }
6286       }
6287     }
6288     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6289     {
6290       // SYSCALL instruction (software interrupt)
6291       will_dirty_i=0;
6292       wont_dirty_i=0;
6293     }
6294     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6295     {
6296       // ERET instruction (return from interrupt)
6297       will_dirty_i=0;
6298       wont_dirty_i=0;
6299     }
6300     will_dirty_next=will_dirty_i;
6301     wont_dirty_next=wont_dirty_i;
6302     for(r=0;r<HOST_REGS;r++) {
6303       if(r!=EXCLUDE_REG) {
6304         if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6305         if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6306         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6307         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6308         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6309         if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6310         if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6311         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6312         if(i>istart) {
6313           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP)
6314           {
6315             // Don't store a register immediately after writing it,
6316             // may prevent dual-issue.
6317             if((regs[i].regmap[r]&63)==rt1[i-1]) wont_dirty_i|=1<<r;
6318             if((regs[i].regmap[r]&63)==rt2[i-1]) wont_dirty_i|=1<<r;
6319           }
6320         }
6321       }
6322     }
6323     // Save it
6324     will_dirty[i]=will_dirty_i;
6325     wont_dirty[i]=wont_dirty_i;
6326     // Mark registers that won't be dirtied as not dirty
6327     if(wr) {
6328       /*printf("wr (%d,%d) %x will:",istart,iend,start+i*4);
6329       for(r=0;r<HOST_REGS;r++) {
6330         if((will_dirty_i>>r)&1) {
6331           printf(" r%d",r);
6332         }
6333       }
6334       printf("\n");*/
6335
6336       //if(i==istart||(itype[i-1]!=RJUMP&&itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP)) {
6337         regs[i].dirty|=will_dirty_i;
6338         #ifndef DESTRUCTIVE_WRITEBACK
6339         regs[i].dirty&=wont_dirty_i;
6340         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6341         {
6342           if(i<iend-1&&itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000) {
6343             for(r=0;r<HOST_REGS;r++) {
6344               if(r!=EXCLUDE_REG) {
6345                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6346                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6347                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6348               }
6349             }
6350           }
6351         }
6352         else
6353         {
6354           if(i<iend) {
6355             for(r=0;r<HOST_REGS;r++) {
6356               if(r!=EXCLUDE_REG) {
6357                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6358                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6359                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6360               }
6361             }
6362           }
6363         }
6364         #endif
6365       //}
6366     }
6367     // Deal with changed mappings
6368     temp_will_dirty=will_dirty_i;
6369     temp_wont_dirty=wont_dirty_i;
6370     for(r=0;r<HOST_REGS;r++) {
6371       if(r!=EXCLUDE_REG) {
6372         int nr;
6373         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6374           if(wr) {
6375             #ifndef DESTRUCTIVE_WRITEBACK
6376             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6377             #endif
6378             regs[i].wasdirty|=will_dirty_i&(1<<r);
6379           }
6380         }
6381         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6382           // Register moved to a different register
6383           will_dirty_i&=~(1<<r);
6384           wont_dirty_i&=~(1<<r);
6385           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6386           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6387           if(wr) {
6388             #ifndef DESTRUCTIVE_WRITEBACK
6389             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6390             #endif
6391             regs[i].wasdirty|=will_dirty_i&(1<<r);
6392           }
6393         }
6394         else {
6395           will_dirty_i&=~(1<<r);
6396           wont_dirty_i&=~(1<<r);
6397           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6398             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6399             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6400           } else {
6401             wont_dirty_i|=1<<r;
6402             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6403           }
6404         }
6405       }
6406     }
6407   }
6408 }
6409
6410 #ifdef DISASM
6411   /* disassembly */
6412 void disassemble_inst(int i)
6413 {
6414     if (bt[i]) printf("*"); else printf(" ");
6415     switch(itype[i]) {
6416       case UJUMP:
6417         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6418       case CJUMP:
6419         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;
6420       case SJUMP:
6421         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;
6422       case RJUMP:
6423         if (opcode[i]==0x9&&rt1[i]!=31)
6424           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i]);
6425         else
6426           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6427         break;
6428       case SPAN:
6429         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],rs1[i],rs2[i],ba[i]);break;
6430       case IMM16:
6431         if(opcode[i]==0xf) //LUI
6432           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],rt1[i],imm[i]&0xffff);
6433         else
6434           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6435         break;
6436       case LOAD:
6437       case LOADLR:
6438         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6439         break;
6440       case STORE:
6441       case STORELR:
6442         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rs2[i],rs1[i],imm[i]);
6443         break;
6444       case ALU:
6445       case SHIFT:
6446         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i],rs2[i]);
6447         break;
6448       case MULTDIV:
6449         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rs1[i],rs2[i]);
6450         break;
6451       case SHIFTIMM:
6452         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6453         break;
6454       case MOV:
6455         if((opcode2[i]&0x1d)==0x10)
6456           printf (" %x: %s r%d\n",start+i*4,insn[i],rt1[i]);
6457         else if((opcode2[i]&0x1d)==0x11)
6458           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6459         else
6460           printf (" %x: %s\n",start+i*4,insn[i]);
6461         break;
6462       case COP0:
6463         if(opcode2[i]==0)
6464           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC0
6465         else if(opcode2[i]==4)
6466           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC0
6467         else printf (" %x: %s\n",start+i*4,insn[i]);
6468         break;
6469       case COP1:
6470         if(opcode2[i]<3)
6471           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC1
6472         else if(opcode2[i]>3)
6473           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC1
6474         else printf (" %x: %s\n",start+i*4,insn[i]);
6475         break;
6476       case COP2:
6477         if(opcode2[i]<3)
6478           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC2
6479         else if(opcode2[i]>3)
6480           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC2
6481         else printf (" %x: %s\n",start+i*4,insn[i]);
6482         break;
6483       case C1LS:
6484         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6485         break;
6486       case C2LS:
6487         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6488         break;
6489       case INTCALL:
6490         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6491         break;
6492       default:
6493         //printf (" %s %8x\n",insn[i],source[i]);
6494         printf (" %x: %s\n",start+i*4,insn[i]);
6495     }
6496 }
6497 #else
6498 static void disassemble_inst(int i) {}
6499 #endif // DISASM
6500
6501 #define DRC_TEST_VAL 0x74657374
6502
6503 static void new_dynarec_test(void)
6504 {
6505   int (*testfunc)(void);
6506   void *beginning;
6507   int ret[2];
6508   size_t i;
6509
6510   // check structure linkage
6511   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6512   {
6513     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6514   }
6515
6516   SysPrintf("testing if we can run recompiled code...\n");
6517   ((volatile u_int *)out)[0]++; // make cache dirty
6518
6519   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6520     out = ndrc->translation_cache;
6521     beginning = start_block();
6522     emit_movimm(DRC_TEST_VAL + i, 0); // test
6523     emit_ret();
6524     literal_pool(0);
6525     end_block(beginning);
6526     testfunc = beginning;
6527     ret[i] = testfunc();
6528   }
6529
6530   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6531     SysPrintf("test passed.\n");
6532   else
6533     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6534   out = ndrc->translation_cache;
6535 }
6536
6537 // clear the state completely, instead of just marking
6538 // things invalid like invalidate_all_pages() does
6539 void new_dynarec_clear_full(void)
6540 {
6541   int n;
6542   out = ndrc->translation_cache;
6543   memset(invalid_code,1,sizeof(invalid_code));
6544   memset(hash_table,0xff,sizeof(hash_table));
6545   memset(mini_ht,-1,sizeof(mini_ht));
6546   memset(restore_candidate,0,sizeof(restore_candidate));
6547   memset(shadow,0,sizeof(shadow));
6548   copy=shadow;
6549   expirep=16384; // Expiry pointer, +2 blocks
6550   pending_exception=0;
6551   literalcount=0;
6552   stop_after_jal=0;
6553   inv_code_start=inv_code_end=~0;
6554   // TLB
6555   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6556   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6557   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6558 }
6559
6560 void new_dynarec_init(void)
6561 {
6562   SysPrintf("Init new dynarec\n");
6563
6564 #ifdef BASE_ADDR_DYNAMIC
6565   #ifdef VITA
6566   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6567   if (sceBlock < 0)
6568     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6569   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6570   if (ret < 0)
6571     SysPrintf("sceKernelGetMemBlockBase failed\n");
6572   #else
6573   uintptr_t desired_addr = 0;
6574   #ifdef __ELF__
6575   extern char _end;
6576   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6577   #endif
6578   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6579             PROT_READ | PROT_WRITE | PROT_EXEC,
6580             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6581   if (ndrc == MAP_FAILED) {
6582     SysPrintf("mmap() failed: %s\n", strerror(errno));
6583     abort();
6584   }
6585   #endif
6586 #else
6587   #ifndef NO_WRITE_EXEC
6588   // not all systems allow execute in data segment by default
6589   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6590                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6591     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6592   #endif
6593 #endif
6594   out = ndrc->translation_cache;
6595   cycle_multiplier=200;
6596   new_dynarec_clear_full();
6597 #ifdef HOST_IMM8
6598   // Copy this into local area so we don't have to put it in every literal pool
6599   invc_ptr=invalid_code;
6600 #endif
6601   arch_init();
6602   new_dynarec_test();
6603 #ifndef RAM_FIXED
6604   ram_offset=(uintptr_t)rdram-0x80000000;
6605 #endif
6606   if (ram_offset!=0)
6607     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6608 }
6609
6610 void new_dynarec_cleanup(void)
6611 {
6612   int n;
6613 #ifdef BASE_ADDR_DYNAMIC
6614   #ifdef VITA
6615   sceKernelFreeMemBlock(sceBlock);
6616   sceBlock = -1;
6617   #else
6618   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6619     SysPrintf("munmap() failed\n");
6620   #endif
6621 #endif
6622   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6623   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6624   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6625   #ifdef ROM_COPY
6626   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6627   #endif
6628 }
6629
6630 static u_int *get_source_start(u_int addr, u_int *limit)
6631 {
6632   if (addr < 0x00200000 ||
6633     (0xa0000000 <= addr && addr < 0xa0200000)) {
6634     // used for BIOS calls mostly?
6635     *limit = (addr&0xa0000000)|0x00200000;
6636     return (u_int *)(rdram + (addr&0x1fffff));
6637   }
6638   else if (!Config.HLE && (
6639     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6640     (0xbfc00000 <= addr && addr < 0xbfc80000))) {
6641     // BIOS
6642     *limit = (addr & 0xfff00000) | 0x80000;
6643     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6644   }
6645   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6646     *limit = (addr & 0x80600000) + 0x00200000;
6647     return (u_int *)(rdram + (addr&0x1fffff));
6648   }
6649   return NULL;
6650 }
6651
6652 static u_int scan_for_ret(u_int addr)
6653 {
6654   u_int limit = 0;
6655   u_int *mem;
6656
6657   mem = get_source_start(addr, &limit);
6658   if (mem == NULL)
6659     return addr;
6660
6661   if (limit > addr + 0x1000)
6662     limit = addr + 0x1000;
6663   for (; addr < limit; addr += 4, mem++) {
6664     if (*mem == 0x03e00008) // jr $ra
6665       return addr + 8;
6666   }
6667   return addr;
6668 }
6669
6670 struct savestate_block {
6671   uint32_t addr;
6672   uint32_t regflags;
6673 };
6674
6675 static int addr_cmp(const void *p1_, const void *p2_)
6676 {
6677   const struct savestate_block *p1 = p1_, *p2 = p2_;
6678   return p1->addr - p2->addr;
6679 }
6680
6681 int new_dynarec_save_blocks(void *save, int size)
6682 {
6683   struct savestate_block *blocks = save;
6684   int maxcount = size / sizeof(blocks[0]);
6685   struct savestate_block tmp_blocks[1024];
6686   struct ll_entry *head;
6687   int p, s, d, o, bcnt;
6688   u_int addr;
6689
6690   o = 0;
6691   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
6692     bcnt = 0;
6693     for (head = jump_in[p]; head != NULL; head = head->next) {
6694       tmp_blocks[bcnt].addr = head->vaddr;
6695       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
6696       bcnt++;
6697     }
6698     if (bcnt < 1)
6699       continue;
6700     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6701
6702     addr = tmp_blocks[0].addr;
6703     for (s = d = 0; s < bcnt; s++) {
6704       if (tmp_blocks[s].addr < addr)
6705         continue;
6706       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6707         tmp_blocks[d++] = tmp_blocks[s];
6708       addr = scan_for_ret(tmp_blocks[s].addr);
6709     }
6710
6711     if (o + d > maxcount)
6712       d = maxcount - o;
6713     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
6714     o += d;
6715   }
6716
6717   return o * sizeof(blocks[0]);
6718 }
6719
6720 void new_dynarec_load_blocks(const void *save, int size)
6721 {
6722   const struct savestate_block *blocks = save;
6723   int count = size / sizeof(blocks[0]);
6724   u_int regs_save[32];
6725   uint32_t f;
6726   int i, b;
6727
6728   get_addr(psxRegs.pc);
6729
6730   // change GPRs for speculation to at least partially work..
6731   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6732   for (i = 1; i < 32; i++)
6733     psxRegs.GPR.r[i] = 0x80000000;
6734
6735   for (b = 0; b < count; b++) {
6736     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6737       if (f & 1)
6738         psxRegs.GPR.r[i] = 0x1f800000;
6739     }
6740
6741     get_addr(blocks[b].addr);
6742
6743     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
6744       if (f & 1)
6745         psxRegs.GPR.r[i] = 0x80000000;
6746     }
6747   }
6748
6749   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6750 }
6751
6752 int new_recompile_block(u_int addr)
6753 {
6754   u_int pagelimit = 0;
6755   u_int state_rflags = 0;
6756   int i;
6757
6758   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
6759   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
6760   //if(debug)
6761   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
6762
6763   // this is just for speculation
6764   for (i = 1; i < 32; i++) {
6765     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
6766       state_rflags |= 1 << i;
6767   }
6768
6769   start = (u_int)addr&~3;
6770   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
6771   new_dynarec_did_compile=1;
6772   if (Config.HLE && start == 0x80001000) // hlecall
6773   {
6774     // XXX: is this enough? Maybe check hleSoftCall?
6775     void *beginning=start_block();
6776     u_int page=get_page(start);
6777
6778     invalid_code[start>>12]=0;
6779     emit_movimm(start,0);
6780     emit_writeword(0,&pcaddr);
6781     emit_far_jump(new_dyna_leave);
6782     literal_pool(0);
6783     end_block(beginning);
6784     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
6785     return 0;
6786   }
6787
6788   source = get_source_start(start, &pagelimit);
6789   if (source == NULL) {
6790     SysPrintf("Compile at bogus memory address: %08x\n", addr);
6791     abort();
6792   }
6793
6794   /* Pass 1: disassemble */
6795   /* Pass 2: register dependencies, branch targets */
6796   /* Pass 3: register allocation */
6797   /* Pass 4: branch dependencies */
6798   /* Pass 5: pre-alloc */
6799   /* Pass 6: optimize clean/dirty state */
6800   /* Pass 7: flag 32-bit registers */
6801   /* Pass 8: assembly */
6802   /* Pass 9: linker */
6803   /* Pass 10: garbage collection / free memory */
6804
6805   int j;
6806   int done=0;
6807   unsigned int type,op,op2;
6808
6809   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
6810
6811   /* Pass 1 disassembly */
6812
6813   for(i=0;!done;i++) {
6814     bt[i]=0;likely[i]=0;ooo[i]=0;op2=0;
6815     minimum_free_regs[i]=0;
6816     opcode[i]=op=source[i]>>26;
6817     switch(op)
6818     {
6819       case 0x00: strcpy(insn[i],"special"); type=NI;
6820         op2=source[i]&0x3f;
6821         switch(op2)
6822         {
6823           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
6824           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
6825           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
6826           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
6827           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
6828           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
6829           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
6830           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
6831           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
6832           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
6833           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
6834           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
6835           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
6836           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
6837           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
6838           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
6839           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
6840           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
6841           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
6842           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
6843           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
6844           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
6845           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
6846           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
6847           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
6848           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
6849           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
6850           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
6851           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
6852           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
6853           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
6854           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
6855           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
6856           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
6857           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
6858 #if 0
6859           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
6860           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
6861           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
6862           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
6863           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
6864           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
6865           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
6866           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
6867           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
6868           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
6869           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
6870           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
6871           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
6872           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
6873           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
6874           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
6875           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
6876 #endif
6877         }
6878         break;
6879       case 0x01: strcpy(insn[i],"regimm"); type=NI;
6880         op2=(source[i]>>16)&0x1f;
6881         switch(op2)
6882         {
6883           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
6884           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
6885           case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
6886           case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
6887           case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
6888           case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
6889           case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
6890           case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
6891           case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
6892           case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
6893           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
6894           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
6895           case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
6896           case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
6897         }
6898         break;
6899       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
6900       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
6901       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
6902       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
6903       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
6904       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
6905       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
6906       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
6907       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
6908       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
6909       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
6910       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
6911       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
6912       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
6913       case 0x10: strcpy(insn[i],"cop0"); type=NI;
6914         op2=(source[i]>>21)&0x1f;
6915         switch(op2)
6916         {
6917           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
6918           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
6919           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
6920           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
6921           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
6922         }
6923         break;
6924       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
6925         op2=(source[i]>>21)&0x1f;
6926         break;
6927 #if 0
6928       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
6929       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
6930       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
6931       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
6932       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
6933       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
6934       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
6935       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
6936 #endif
6937       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
6938       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
6939       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
6940       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
6941       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
6942       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
6943       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
6944 #if 0
6945       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
6946 #endif
6947       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
6948       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
6949       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
6950       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
6951 #if 0
6952       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
6953       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
6954 #endif
6955       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
6956       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
6957       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
6958       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
6959 #if 0
6960       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
6961       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
6962       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
6963 #endif
6964       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
6965       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
6966 #if 0
6967       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
6968       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
6969       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
6970 #endif
6971       case 0x12: strcpy(insn[i],"COP2"); type=NI;
6972         op2=(source[i]>>21)&0x1f;
6973         //if (op2 & 0x10)
6974         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
6975           if (gte_handlers[source[i]&0x3f]!=NULL) {
6976             if (gte_regnames[source[i]&0x3f]!=NULL)
6977               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
6978             else
6979               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
6980             type=C2OP;
6981           }
6982         }
6983         else switch(op2)
6984         {
6985           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
6986           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
6987           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
6988           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
6989         }
6990         break;
6991       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
6992       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
6993       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
6994       default: strcpy(insn[i],"???"); type=NI;
6995         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
6996         break;
6997     }
6998     itype[i]=type;
6999     opcode2[i]=op2;
7000     /* Get registers/immediates */
7001     lt1[i]=0;
7002     dep1[i]=0;
7003     dep2[i]=0;
7004     gte_rs[i]=gte_rt[i]=0;
7005     switch(type) {
7006       case LOAD:
7007         rs1[i]=(source[i]>>21)&0x1f;
7008         rs2[i]=0;
7009         rt1[i]=(source[i]>>16)&0x1f;
7010         rt2[i]=0;
7011         imm[i]=(short)source[i];
7012         break;
7013       case STORE:
7014       case STORELR:
7015         rs1[i]=(source[i]>>21)&0x1f;
7016         rs2[i]=(source[i]>>16)&0x1f;
7017         rt1[i]=0;
7018         rt2[i]=0;
7019         imm[i]=(short)source[i];
7020         break;
7021       case LOADLR:
7022         // LWL/LWR only load part of the register,
7023         // therefore the target register must be treated as a source too
7024         rs1[i]=(source[i]>>21)&0x1f;
7025         rs2[i]=(source[i]>>16)&0x1f;
7026         rt1[i]=(source[i]>>16)&0x1f;
7027         rt2[i]=0;
7028         imm[i]=(short)source[i];
7029         if(op==0x26) dep1[i]=rt1[i]; // LWR
7030         break;
7031       case IMM16:
7032         if (op==0x0f) rs1[i]=0; // LUI instruction has no source register
7033         else rs1[i]=(source[i]>>21)&0x1f;
7034         rs2[i]=0;
7035         rt1[i]=(source[i]>>16)&0x1f;
7036         rt2[i]=0;
7037         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7038           imm[i]=(unsigned short)source[i];
7039         }else{
7040           imm[i]=(short)source[i];
7041         }
7042         if(op==0x0d||op==0x0e) dep1[i]=rs1[i]; // ORI/XORI
7043         break;
7044       case UJUMP:
7045         rs1[i]=0;
7046         rs2[i]=0;
7047         rt1[i]=0;
7048         rt2[i]=0;
7049         // The JAL instruction writes to r31.
7050         if (op&1) {
7051           rt1[i]=31;
7052         }
7053         rs2[i]=CCREG;
7054         break;
7055       case RJUMP:
7056         rs1[i]=(source[i]>>21)&0x1f;
7057         rs2[i]=0;
7058         rt1[i]=0;
7059         rt2[i]=0;
7060         // The JALR instruction writes to rd.
7061         if (op2&1) {
7062           rt1[i]=(source[i]>>11)&0x1f;
7063         }
7064         rs2[i]=CCREG;
7065         break;
7066       case CJUMP:
7067         rs1[i]=(source[i]>>21)&0x1f;
7068         rs2[i]=(source[i]>>16)&0x1f;
7069         rt1[i]=0;
7070         rt2[i]=0;
7071         if(op&2) { // BGTZ/BLEZ
7072           rs2[i]=0;
7073         }
7074         likely[i]=op>>4;
7075         break;
7076       case SJUMP:
7077         rs1[i]=(source[i]>>21)&0x1f;
7078         rs2[i]=CCREG;
7079         rt1[i]=0;
7080         rt2[i]=0;
7081         if(op2&0x10) { // BxxAL
7082           rt1[i]=31;
7083           // NOTE: If the branch is not taken, r31 is still overwritten
7084         }
7085         likely[i]=(op2&2)>>1;
7086         break;
7087       case ALU:
7088         rs1[i]=(source[i]>>21)&0x1f; // source
7089         rs2[i]=(source[i]>>16)&0x1f; // subtract amount
7090         rt1[i]=(source[i]>>11)&0x1f; // destination
7091         rt2[i]=0;
7092         if(op2>=0x24&&op2<=0x27) { // AND/OR/XOR/NOR
7093           dep1[i]=rs1[i];dep2[i]=rs2[i];
7094         }
7095         else if(op2>=0x2c&&op2<=0x2f) { // DADD/DSUB
7096           dep1[i]=rs1[i];dep2[i]=rs2[i];
7097         }
7098         break;
7099       case MULTDIV:
7100         rs1[i]=(source[i]>>21)&0x1f; // source
7101         rs2[i]=(source[i]>>16)&0x1f; // divisor
7102         rt1[i]=HIREG;
7103         rt2[i]=LOREG;
7104         break;
7105       case MOV:
7106         rs1[i]=0;
7107         rs2[i]=0;
7108         rt1[i]=0;
7109         rt2[i]=0;
7110         if(op2==0x10) rs1[i]=HIREG; // MFHI
7111         if(op2==0x11) rt1[i]=HIREG; // MTHI
7112         if(op2==0x12) rs1[i]=LOREG; // MFLO
7113         if(op2==0x13) rt1[i]=LOREG; // MTLO
7114         if((op2&0x1d)==0x10) rt1[i]=(source[i]>>11)&0x1f; // MFxx
7115         if((op2&0x1d)==0x11) rs1[i]=(source[i]>>21)&0x1f; // MTxx
7116         dep1[i]=rs1[i];
7117         break;
7118       case SHIFT:
7119         rs1[i]=(source[i]>>16)&0x1f; // target of shift
7120         rs2[i]=(source[i]>>21)&0x1f; // shift amount
7121         rt1[i]=(source[i]>>11)&0x1f; // destination
7122         rt2[i]=0;
7123         break;
7124       case SHIFTIMM:
7125         rs1[i]=(source[i]>>16)&0x1f;
7126         rs2[i]=0;
7127         rt1[i]=(source[i]>>11)&0x1f;
7128         rt2[i]=0;
7129         imm[i]=(source[i]>>6)&0x1f;
7130         // DSxx32 instructions
7131         if(op2>=0x3c) imm[i]|=0x20;
7132         break;
7133       case COP0:
7134         rs1[i]=0;
7135         rs2[i]=0;
7136         rt1[i]=0;
7137         rt2[i]=0;
7138         if(op2==0||op2==2) rt1[i]=(source[i]>>16)&0x1F; // MFC0/CFC0
7139         if(op2==4||op2==6) rs1[i]=(source[i]>>16)&0x1F; // MTC0/CTC0
7140         if(op2==4&&((source[i]>>11)&0x1f)==12) rt2[i]=CSREG; // Status
7141         if(op2==16) if((source[i]&0x3f)==0x18) rs2[i]=CCREG; // ERET
7142         break;
7143       case COP1:
7144         rs1[i]=0;
7145         rs2[i]=0;
7146         rt1[i]=0;
7147         rt2[i]=0;
7148         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7149         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7150         rs2[i]=CSREG;
7151         break;
7152       case COP2:
7153         rs1[i]=0;
7154         rs2[i]=0;
7155         rt1[i]=0;
7156         rt2[i]=0;
7157         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC2/CFC2
7158         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC2/CTC2
7159         rs2[i]=CSREG;
7160         int gr=(source[i]>>11)&0x1F;
7161         switch(op2)
7162         {
7163           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7164           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7165           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7166           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7167         }
7168         break;
7169       case C1LS:
7170         rs1[i]=(source[i]>>21)&0x1F;
7171         rs2[i]=CSREG;
7172         rt1[i]=0;
7173         rt2[i]=0;
7174         imm[i]=(short)source[i];
7175         break;
7176       case C2LS:
7177         rs1[i]=(source[i]>>21)&0x1F;
7178         rs2[i]=0;
7179         rt1[i]=0;
7180         rt2[i]=0;
7181         imm[i]=(short)source[i];
7182         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7183         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7184         break;
7185       case C2OP:
7186         rs1[i]=0;
7187         rs2[i]=0;
7188         rt1[i]=0;
7189         rt2[i]=0;
7190         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7191         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7192         gte_rt[i]|=1ll<<63; // every op changes flags
7193         if((source[i]&0x3f)==GTE_MVMVA) {
7194           int v = (source[i] >> 15) & 3;
7195           gte_rs[i]&=~0xe3fll;
7196           if(v==3) gte_rs[i]|=0xe00ll;
7197           else gte_rs[i]|=3ll<<(v*2);
7198         }
7199         break;
7200       case SYSCALL:
7201       case HLECALL:
7202       case INTCALL:
7203         rs1[i]=CCREG;
7204         rs2[i]=0;
7205         rt1[i]=0;
7206         rt2[i]=0;
7207         break;
7208       default:
7209         rs1[i]=0;
7210         rs2[i]=0;
7211         rt1[i]=0;
7212         rt2[i]=0;
7213     }
7214     /* Calculate branch target addresses */
7215     if(type==UJUMP)
7216       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7217     else if(type==CJUMP&&rs1[i]==rs2[i]&&(op&1))
7218       ba[i]=start+i*4+8; // Ignore never taken branch
7219     else if(type==SJUMP&&rs1[i]==0&&!(op2&1))
7220       ba[i]=start+i*4+8; // Ignore never taken branch
7221     else if(type==CJUMP||type==SJUMP)
7222       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7223     else ba[i]=-1;
7224     if(i>0&&(itype[i-1]==RJUMP||itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)) {
7225       int do_in_intrp=0;
7226       // branch in delay slot?
7227       if(type==RJUMP||type==UJUMP||type==CJUMP||type==SJUMP) {
7228         // don't handle first branch and call interpreter if it's hit
7229         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7230         do_in_intrp=1;
7231       }
7232       // basic load delay detection
7233       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&rt1[i]!=0) {
7234         int t=(ba[i-1]-start)/4;
7235         if(0 <= t && t < i &&(rt1[i]==rs1[t]||rt1[i]==rs2[t])&&itype[t]!=CJUMP&&itype[t]!=SJUMP) {
7236           // jump target wants DS result - potential load delay effect
7237           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7238           do_in_intrp=1;
7239           bt[t+1]=1; // expected return from interpreter
7240         }
7241         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&&
7242               !(i>=3&&(itype[i-3]==RJUMP||itype[i-3]==UJUMP||itype[i-3]==CJUMP||itype[i-3]==SJUMP))) {
7243           // v0 overwrite like this is a sign of trouble, bail out
7244           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7245           do_in_intrp=1;
7246         }
7247       }
7248       if(do_in_intrp) {
7249         rs1[i-1]=CCREG;
7250         rs2[i-1]=rt1[i-1]=rt2[i-1]=0;
7251         ba[i-1]=-1;
7252         itype[i-1]=INTCALL;
7253         done=2;
7254         i--; // don't compile the DS
7255       }
7256     }
7257     /* Is this the end of the block? */
7258     if(i>0&&(itype[i-1]==UJUMP||itype[i-1]==RJUMP||(source[i-1]>>16)==0x1000)) {
7259       if(rt1[i-1]==0) { // Continue past subroutine call (JAL)
7260         done=2;
7261       }
7262       else {
7263         if(stop_after_jal) done=1;
7264         // Stop on BREAK
7265         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7266       }
7267       // Don't recompile stuff that's already compiled
7268       if(check_addr(start+i*4+4)) done=1;
7269       // Don't get too close to the limit
7270       if(i>MAXBLOCK/2) done=1;
7271     }
7272     if(itype[i]==SYSCALL&&stop_after_jal) done=1;
7273     if(itype[i]==HLECALL||itype[i]==INTCALL) done=2;
7274     if(done==2) {
7275       // Does the block continue due to a branch?
7276       for(j=i-1;j>=0;j--)
7277       {
7278         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7279         if(ba[j]==start+i*4+4) done=j=0;
7280         if(ba[j]==start+i*4+8) done=j=0;
7281       }
7282     }
7283     //assert(i<MAXBLOCK-1);
7284     if(start+i*4==pagelimit-4) done=1;
7285     assert(start+i*4<pagelimit);
7286     if (i==MAXBLOCK-1) done=1;
7287     // Stop if we're compiling junk
7288     if(itype[i]==NI&&opcode[i]==0x11) {
7289       done=stop_after_jal=1;
7290       SysPrintf("Disabled speculative precompilation\n");
7291     }
7292   }
7293   slen=i;
7294   if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP||itype[i-1]==RJUMP) {
7295     if(start+i*4==pagelimit) {
7296       itype[i-1]=SPAN;
7297     }
7298   }
7299   assert(slen>0);
7300
7301   /* Pass 2 - Register dependencies and branch targets */
7302
7303   unneeded_registers(0,slen-1,0);
7304
7305   /* Pass 3 - Register allocation */
7306
7307   struct regstat current; // Current register allocations/status
7308   current.dirty=0;
7309   current.u=unneeded_reg[0];
7310   clear_all_regs(current.regmap);
7311   alloc_reg(&current,0,CCREG);
7312   dirty_reg(&current,CCREG);
7313   current.isconst=0;
7314   current.wasconst=0;
7315   current.waswritten=0;
7316   int ds=0;
7317   int cc=0;
7318   int hr=-1;
7319
7320   if((u_int)addr&1) {
7321     // First instruction is delay slot
7322     cc=-1;
7323     bt[1]=1;
7324     ds=1;
7325     unneeded_reg[0]=1;
7326     current.regmap[HOST_BTREG]=BTREG;
7327   }
7328
7329   for(i=0;i<slen;i++)
7330   {
7331     if(bt[i])
7332     {
7333       int hr;
7334       for(hr=0;hr<HOST_REGS;hr++)
7335       {
7336         // Is this really necessary?
7337         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7338       }
7339       current.isconst=0;
7340       current.waswritten=0;
7341     }
7342
7343     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7344     regs[i].wasconst=current.isconst;
7345     regs[i].wasdirty=current.dirty;
7346     regs[i].loadedconst=0;
7347     if(itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP&&itype[i]!=RJUMP) {
7348       if(i+1<slen) {
7349         current.u=unneeded_reg[i+1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7350         current.u|=1;
7351       } else {
7352         current.u=1;
7353       }
7354     } else {
7355       if(i+1<slen) {
7356         current.u=branch_unneeded_reg[i]&~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
7357         current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7358         current.u|=1;
7359       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7360     }
7361     is_ds[i]=ds;
7362     if(ds) {
7363       ds=0; // Skip delay slot, already allocated as part of branch
7364       // ...but we need to alloc it in case something jumps here
7365       if(i+1<slen) {
7366         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7367       }else{
7368         current.u=branch_unneeded_reg[i-1];
7369       }
7370       current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7371       current.u|=1;
7372       struct regstat temp;
7373       memcpy(&temp,&current,sizeof(current));
7374       temp.wasdirty=temp.dirty;
7375       // TODO: Take into account unconditional branches, as below
7376       delayslot_alloc(&temp,i);
7377       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7378       regs[i].wasdirty=temp.wasdirty;
7379       regs[i].dirty=temp.dirty;
7380       regs[i].isconst=0;
7381       regs[i].wasconst=0;
7382       current.isconst=0;
7383       // Create entry (branch target) regmap
7384       for(hr=0;hr<HOST_REGS;hr++)
7385       {
7386         int r=temp.regmap[hr];
7387         if(r>=0) {
7388           if(r!=regmap_pre[i][hr]) {
7389             regs[i].regmap_entry[hr]=-1;
7390           }
7391           else
7392           {
7393               assert(r < 64);
7394               if((current.u>>r)&1) {
7395                 regs[i].regmap_entry[hr]=-1;
7396                 regs[i].regmap[hr]=-1;
7397                 //Don't clear regs in the delay slot as the branch might need them
7398                 //current.regmap[hr]=-1;
7399               }else
7400                 regs[i].regmap_entry[hr]=r;
7401           }
7402         } else {
7403           // First instruction expects CCREG to be allocated
7404           if(i==0&&hr==HOST_CCREG)
7405             regs[i].regmap_entry[hr]=CCREG;
7406           else
7407             regs[i].regmap_entry[hr]=-1;
7408         }
7409       }
7410     }
7411     else { // Not delay slot
7412       switch(itype[i]) {
7413         case UJUMP:
7414           //current.isconst=0; // DEBUG
7415           //current.wasconst=0; // DEBUG
7416           //regs[i].wasconst=0; // DEBUG
7417           clear_const(&current,rt1[i]);
7418           alloc_cc(&current,i);
7419           dirty_reg(&current,CCREG);
7420           if (rt1[i]==31) {
7421             alloc_reg(&current,i,31);
7422             dirty_reg(&current,31);
7423             //assert(rs1[i+1]!=31&&rs2[i+1]!=31);
7424             //assert(rt1[i+1]!=rt1[i]);
7425             #ifdef REG_PREFETCH
7426             alloc_reg(&current,i,PTEMP);
7427             #endif
7428           }
7429           ooo[i]=1;
7430           delayslot_alloc(&current,i+1);
7431           //current.isconst=0; // DEBUG
7432           ds=1;
7433           //printf("i=%d, isconst=%x\n",i,current.isconst);
7434           break;
7435         case RJUMP:
7436           //current.isconst=0;
7437           //current.wasconst=0;
7438           //regs[i].wasconst=0;
7439           clear_const(&current,rs1[i]);
7440           clear_const(&current,rt1[i]);
7441           alloc_cc(&current,i);
7442           dirty_reg(&current,CCREG);
7443           if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
7444             alloc_reg(&current,i,rs1[i]);
7445             if (rt1[i]!=0) {
7446               alloc_reg(&current,i,rt1[i]);
7447               dirty_reg(&current,rt1[i]);
7448               assert(rs1[i+1]!=rt1[i]&&rs2[i+1]!=rt1[i]);
7449               assert(rt1[i+1]!=rt1[i]);
7450               #ifdef REG_PREFETCH
7451               alloc_reg(&current,i,PTEMP);
7452               #endif
7453             }
7454             #ifdef USE_MINI_HT
7455             if(rs1[i]==31) { // JALR
7456               alloc_reg(&current,i,RHASH);
7457               alloc_reg(&current,i,RHTBL);
7458             }
7459             #endif
7460             delayslot_alloc(&current,i+1);
7461           } else {
7462             // The delay slot overwrites our source register,
7463             // allocate a temporary register to hold the old value.
7464             current.isconst=0;
7465             current.wasconst=0;
7466             regs[i].wasconst=0;
7467             delayslot_alloc(&current,i+1);
7468             current.isconst=0;
7469             alloc_reg(&current,i,RTEMP);
7470           }
7471           //current.isconst=0; // DEBUG
7472           ooo[i]=1;
7473           ds=1;
7474           break;
7475         case CJUMP:
7476           //current.isconst=0;
7477           //current.wasconst=0;
7478           //regs[i].wasconst=0;
7479           clear_const(&current,rs1[i]);
7480           clear_const(&current,rs2[i]);
7481           if((opcode[i]&0x3E)==4) // BEQ/BNE
7482           {
7483             alloc_cc(&current,i);
7484             dirty_reg(&current,CCREG);
7485             if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7486             if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7487             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]))||
7488                (rs2[i]&&(rs2[i]==rt1[i+1]||rs2[i]==rt2[i+1]))) {
7489               // The delay slot overwrites one of our conditions.
7490               // Allocate the branch condition registers instead.
7491               current.isconst=0;
7492               current.wasconst=0;
7493               regs[i].wasconst=0;
7494               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7495               if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7496             }
7497             else
7498             {
7499               ooo[i]=1;
7500               delayslot_alloc(&current,i+1);
7501             }
7502           }
7503           else
7504           if((opcode[i]&0x3E)==6) // BLEZ/BGTZ
7505           {
7506             alloc_cc(&current,i);
7507             dirty_reg(&current,CCREG);
7508             alloc_reg(&current,i,rs1[i]);
7509             if(rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) {
7510               // The delay slot overwrites one of our conditions.
7511               // Allocate the branch condition registers instead.
7512               current.isconst=0;
7513               current.wasconst=0;
7514               regs[i].wasconst=0;
7515               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7516             }
7517             else
7518             {
7519               ooo[i]=1;
7520               delayslot_alloc(&current,i+1);
7521             }
7522           }
7523           else
7524           // Don't alloc the delay slot yet because we might not execute it
7525           if((opcode[i]&0x3E)==0x14) // BEQL/BNEL
7526           {
7527             current.isconst=0;
7528             current.wasconst=0;
7529             regs[i].wasconst=0;
7530             alloc_cc(&current,i);
7531             dirty_reg(&current,CCREG);
7532             alloc_reg(&current,i,rs1[i]);
7533             alloc_reg(&current,i,rs2[i]);
7534           }
7535           else
7536           if((opcode[i]&0x3E)==0x16) // BLEZL/BGTZL
7537           {
7538             current.isconst=0;
7539             current.wasconst=0;
7540             regs[i].wasconst=0;
7541             alloc_cc(&current,i);
7542             dirty_reg(&current,CCREG);
7543             alloc_reg(&current,i,rs1[i]);
7544           }
7545           ds=1;
7546           //current.isconst=0;
7547           break;
7548         case SJUMP:
7549           //current.isconst=0;
7550           //current.wasconst=0;
7551           //regs[i].wasconst=0;
7552           clear_const(&current,rs1[i]);
7553           clear_const(&current,rt1[i]);
7554           //if((opcode2[i]&0x1E)==0x0) // BLTZ/BGEZ
7555           if((opcode2[i]&0x0E)==0x0) // BLTZ/BGEZ
7556           {
7557             alloc_cc(&current,i);
7558             dirty_reg(&current,CCREG);
7559             alloc_reg(&current,i,rs1[i]);
7560             if (rt1[i]==31) { // BLTZAL/BGEZAL
7561               alloc_reg(&current,i,31);
7562               dirty_reg(&current,31);
7563               //#ifdef REG_PREFETCH
7564               //alloc_reg(&current,i,PTEMP);
7565               //#endif
7566             }
7567             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) // The delay slot overwrites the branch condition.
7568                ||(rt1[i]==31&&(rs1[i+1]==31||rs2[i+1]==31||rt1[i+1]==31||rt2[i+1]==31))) { // DS touches $ra
7569               // Allocate the branch condition registers instead.
7570               current.isconst=0;
7571               current.wasconst=0;
7572               regs[i].wasconst=0;
7573               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7574             }
7575             else
7576             {
7577               ooo[i]=1;
7578               delayslot_alloc(&current,i+1);
7579             }
7580           }
7581           else
7582           // Don't alloc the delay slot yet because we might not execute it
7583           if((opcode2[i]&0x1E)==0x2) // BLTZL/BGEZL
7584           {
7585             current.isconst=0;
7586             current.wasconst=0;
7587             regs[i].wasconst=0;
7588             alloc_cc(&current,i);
7589             dirty_reg(&current,CCREG);
7590             alloc_reg(&current,i,rs1[i]);
7591           }
7592           ds=1;
7593           //current.isconst=0;
7594           break;
7595         case IMM16:
7596           imm16_alloc(&current,i);
7597           break;
7598         case LOAD:
7599         case LOADLR:
7600           load_alloc(&current,i);
7601           break;
7602         case STORE:
7603         case STORELR:
7604           store_alloc(&current,i);
7605           break;
7606         case ALU:
7607           alu_alloc(&current,i);
7608           break;
7609         case SHIFT:
7610           shift_alloc(&current,i);
7611           break;
7612         case MULTDIV:
7613           multdiv_alloc(&current,i);
7614           break;
7615         case SHIFTIMM:
7616           shiftimm_alloc(&current,i);
7617           break;
7618         case MOV:
7619           mov_alloc(&current,i);
7620           break;
7621         case COP0:
7622           cop0_alloc(&current,i);
7623           break;
7624         case COP1:
7625         case COP2:
7626           cop12_alloc(&current,i);
7627           break;
7628         case C1LS:
7629           c1ls_alloc(&current,i);
7630           break;
7631         case C2LS:
7632           c2ls_alloc(&current,i);
7633           break;
7634         case C2OP:
7635           c2op_alloc(&current,i);
7636           break;
7637         case SYSCALL:
7638         case HLECALL:
7639         case INTCALL:
7640           syscall_alloc(&current,i);
7641           break;
7642         case SPAN:
7643           pagespan_alloc(&current,i);
7644           break;
7645       }
7646
7647       // Create entry (branch target) regmap
7648       for(hr=0;hr<HOST_REGS;hr++)
7649       {
7650         int r,or;
7651         r=current.regmap[hr];
7652         if(r>=0) {
7653           if(r!=regmap_pre[i][hr]) {
7654             // TODO: delay slot (?)
7655             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7656             if(or<0||(r&63)>=TEMPREG){
7657               regs[i].regmap_entry[hr]=-1;
7658             }
7659             else
7660             {
7661               // Just move it to a different register
7662               regs[i].regmap_entry[hr]=r;
7663               // If it was dirty before, it's still dirty
7664               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7665             }
7666           }
7667           else
7668           {
7669             // Unneeded
7670             if(r==0){
7671               regs[i].regmap_entry[hr]=0;
7672             }
7673             else
7674             {
7675               assert(r<64);
7676               if((current.u>>r)&1) {
7677                 regs[i].regmap_entry[hr]=-1;
7678                 //regs[i].regmap[hr]=-1;
7679                 current.regmap[hr]=-1;
7680               }else
7681                 regs[i].regmap_entry[hr]=r;
7682             }
7683           }
7684         } else {
7685           // Branches expect CCREG to be allocated at the target
7686           if(regmap_pre[i][hr]==CCREG)
7687             regs[i].regmap_entry[hr]=CCREG;
7688           else
7689             regs[i].regmap_entry[hr]=-1;
7690         }
7691       }
7692       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7693     }
7694
7695     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)
7696       current.waswritten|=1<<rs1[i-1];
7697     current.waswritten&=~(1<<rt1[i]);
7698     current.waswritten&=~(1<<rt2[i]);
7699     if((itype[i]==STORE||itype[i]==STORELR||(itype[i]==C2LS&&opcode[i]==0x3a))&&(u_int)imm[i]>=0x800)
7700       current.waswritten&=~(1<<rs1[i]);
7701
7702     /* Branch post-alloc */
7703     if(i>0)
7704     {
7705       current.wasdirty=current.dirty;
7706       switch(itype[i-1]) {
7707         case UJUMP:
7708           memcpy(&branch_regs[i-1],&current,sizeof(current));
7709           branch_regs[i-1].isconst=0;
7710           branch_regs[i-1].wasconst=0;
7711           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7712           alloc_cc(&branch_regs[i-1],i-1);
7713           dirty_reg(&branch_regs[i-1],CCREG);
7714           if(rt1[i-1]==31) { // JAL
7715             alloc_reg(&branch_regs[i-1],i-1,31);
7716             dirty_reg(&branch_regs[i-1],31);
7717           }
7718           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7719           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7720           break;
7721         case RJUMP:
7722           memcpy(&branch_regs[i-1],&current,sizeof(current));
7723           branch_regs[i-1].isconst=0;
7724           branch_regs[i-1].wasconst=0;
7725           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7726           alloc_cc(&branch_regs[i-1],i-1);
7727           dirty_reg(&branch_regs[i-1],CCREG);
7728           alloc_reg(&branch_regs[i-1],i-1,rs1[i-1]);
7729           if(rt1[i-1]!=0) { // JALR
7730             alloc_reg(&branch_regs[i-1],i-1,rt1[i-1]);
7731             dirty_reg(&branch_regs[i-1],rt1[i-1]);
7732           }
7733           #ifdef USE_MINI_HT
7734           if(rs1[i-1]==31) { // JALR
7735             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7736             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7737           }
7738           #endif
7739           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7740           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7741           break;
7742         case CJUMP:
7743           if((opcode[i-1]&0x3E)==4) // BEQ/BNE
7744           {
7745             alloc_cc(&current,i-1);
7746             dirty_reg(&current,CCREG);
7747             if((rs1[i-1]&&(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]))||
7748                (rs2[i-1]&&(rs2[i-1]==rt1[i]||rs2[i-1]==rt2[i]))) {
7749               // The delay slot overwrote one of our conditions
7750               // Delay slot goes after the test (in order)
7751               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7752               current.u|=1;
7753               delayslot_alloc(&current,i);
7754               current.isconst=0;
7755             }
7756             else
7757             {
7758               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
7759               // Alloc the branch condition registers
7760               if(rs1[i-1]) alloc_reg(&current,i-1,rs1[i-1]);
7761               if(rs2[i-1]) alloc_reg(&current,i-1,rs2[i-1]);
7762             }
7763             memcpy(&branch_regs[i-1],&current,sizeof(current));
7764             branch_regs[i-1].isconst=0;
7765             branch_regs[i-1].wasconst=0;
7766             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7767             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7768           }
7769           else
7770           if((opcode[i-1]&0x3E)==6) // BLEZ/BGTZ
7771           {
7772             alloc_cc(&current,i-1);
7773             dirty_reg(&current,CCREG);
7774             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
7775               // The delay slot overwrote the branch condition
7776               // Delay slot goes after the test (in order)
7777               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7778               current.u|=1;
7779               delayslot_alloc(&current,i);
7780               current.isconst=0;
7781             }
7782             else
7783             {
7784               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
7785               // Alloc the branch condition register
7786               alloc_reg(&current,i-1,rs1[i-1]);
7787             }
7788             memcpy(&branch_regs[i-1],&current,sizeof(current));
7789             branch_regs[i-1].isconst=0;
7790             branch_regs[i-1].wasconst=0;
7791             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7792             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7793           }
7794           else
7795           // Alloc the delay slot in case the branch is taken
7796           if((opcode[i-1]&0x3E)==0x14) // BEQL/BNEL
7797           {
7798             memcpy(&branch_regs[i-1],&current,sizeof(current));
7799             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7800             alloc_cc(&branch_regs[i-1],i);
7801             dirty_reg(&branch_regs[i-1],CCREG);
7802             delayslot_alloc(&branch_regs[i-1],i);
7803             branch_regs[i-1].isconst=0;
7804             alloc_reg(&current,i,CCREG); // Not taken path
7805             dirty_reg(&current,CCREG);
7806             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7807           }
7808           else
7809           if((opcode[i-1]&0x3E)==0x16) // BLEZL/BGTZL
7810           {
7811             memcpy(&branch_regs[i-1],&current,sizeof(current));
7812             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7813             alloc_cc(&branch_regs[i-1],i);
7814             dirty_reg(&branch_regs[i-1],CCREG);
7815             delayslot_alloc(&branch_regs[i-1],i);
7816             branch_regs[i-1].isconst=0;
7817             alloc_reg(&current,i,CCREG); // Not taken path
7818             dirty_reg(&current,CCREG);
7819             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7820           }
7821           break;
7822         case SJUMP:
7823           //if((opcode2[i-1]&0x1E)==0) // BLTZ/BGEZ
7824           if((opcode2[i-1]&0x0E)==0) // BLTZ/BGEZ
7825           {
7826             alloc_cc(&current,i-1);
7827             dirty_reg(&current,CCREG);
7828             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
7829               // The delay slot overwrote the branch condition
7830               // Delay slot goes after the test (in order)
7831               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7832               current.u|=1;
7833               delayslot_alloc(&current,i);
7834               current.isconst=0;
7835             }
7836             else
7837             {
7838               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
7839               // Alloc the branch condition register
7840               alloc_reg(&current,i-1,rs1[i-1]);
7841             }
7842             memcpy(&branch_regs[i-1],&current,sizeof(current));
7843             branch_regs[i-1].isconst=0;
7844             branch_regs[i-1].wasconst=0;
7845             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7846             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7847           }
7848           else
7849           // Alloc the delay slot in case the branch is taken
7850           if((opcode2[i-1]&0x1E)==2) // BLTZL/BGEZL
7851           {
7852             memcpy(&branch_regs[i-1],&current,sizeof(current));
7853             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
7854             alloc_cc(&branch_regs[i-1],i);
7855             dirty_reg(&branch_regs[i-1],CCREG);
7856             delayslot_alloc(&branch_regs[i-1],i);
7857             branch_regs[i-1].isconst=0;
7858             alloc_reg(&current,i,CCREG); // Not taken path
7859             dirty_reg(&current,CCREG);
7860             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7861           }
7862           // FIXME: BLTZAL/BGEZAL
7863           if(opcode2[i-1]&0x10) { // BxxZAL
7864             alloc_reg(&branch_regs[i-1],i-1,31);
7865             dirty_reg(&branch_regs[i-1],31);
7866           }
7867           break;
7868       }
7869
7870       if(itype[i-1]==UJUMP||itype[i-1]==RJUMP||(source[i-1]>>16)==0x1000)
7871       {
7872         if(rt1[i-1]==31) // JAL/JALR
7873         {
7874           // Subroutine call will return here, don't alloc any registers
7875           current.dirty=0;
7876           clear_all_regs(current.regmap);
7877           alloc_reg(&current,i,CCREG);
7878           dirty_reg(&current,CCREG);
7879         }
7880         else if(i+1<slen)
7881         {
7882           // Internal branch will jump here, match registers to caller
7883           current.dirty=0;
7884           clear_all_regs(current.regmap);
7885           alloc_reg(&current,i,CCREG);
7886           dirty_reg(&current,CCREG);
7887           for(j=i-1;j>=0;j--)
7888           {
7889             if(ba[j]==start+i*4+4) {
7890               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
7891               current.dirty=branch_regs[j].dirty;
7892               break;
7893             }
7894           }
7895           while(j>=0) {
7896             if(ba[j]==start+i*4+4) {
7897               for(hr=0;hr<HOST_REGS;hr++) {
7898                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
7899                   current.regmap[hr]=-1;
7900                 }
7901                 current.dirty&=branch_regs[j].dirty;
7902               }
7903             }
7904             j--;
7905           }
7906         }
7907       }
7908     }
7909
7910     // Count cycles in between branches
7911     ccadj[i]=cc;
7912     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))
7913     {
7914       cc=0;
7915     }
7916 #if !defined(DRC_DBG)
7917     else if(itype[i]==C2OP&&gte_cycletab[source[i]&0x3f]>2)
7918     {
7919       // GTE runs in parallel until accessed, divide by 2 for a rough guess
7920       cc+=gte_cycletab[source[i]&0x3f]/2;
7921     }
7922     else if(/*itype[i]==LOAD||itype[i]==STORE||*/itype[i]==C1LS) // load,store causes weird timing issues
7923     {
7924       cc+=2; // 2 cycle penalty (after CLOCK_DIVIDER)
7925     }
7926     else if(i>1&&itype[i]==STORE&&itype[i-1]==STORE&&itype[i-2]==STORE&&!bt[i])
7927     {
7928       cc+=4;
7929     }
7930     else if(itype[i]==C2LS)
7931     {
7932       cc+=4;
7933     }
7934 #endif
7935     else
7936     {
7937       cc++;
7938     }
7939
7940     if(!is_ds[i]) {
7941       regs[i].dirty=current.dirty;
7942       regs[i].isconst=current.isconst;
7943       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
7944     }
7945     for(hr=0;hr<HOST_REGS;hr++) {
7946       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
7947         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
7948           regs[i].wasconst&=~(1<<hr);
7949         }
7950       }
7951     }
7952     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
7953     regs[i].waswritten=current.waswritten;
7954   }
7955
7956   /* Pass 4 - Cull unused host registers */
7957
7958   uint64_t nr=0;
7959
7960   for (i=slen-1;i>=0;i--)
7961   {
7962     int hr;
7963     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
7964     {
7965       if(ba[i]<start || ba[i]>=(start+slen*4))
7966       {
7967         // Branch out of this block, don't need anything
7968         nr=0;
7969       }
7970       else
7971       {
7972         // Internal branch
7973         // Need whatever matches the target
7974         nr=0;
7975         int t=(ba[i]-start)>>2;
7976         for(hr=0;hr<HOST_REGS;hr++)
7977         {
7978           if(regs[i].regmap_entry[hr]>=0) {
7979             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
7980           }
7981         }
7982       }
7983       // Conditional branch may need registers for following instructions
7984       if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
7985       {
7986         if(i<slen-2) {
7987           nr|=needed_reg[i+2];
7988           for(hr=0;hr<HOST_REGS;hr++)
7989           {
7990             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
7991             //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]);
7992           }
7993         }
7994       }
7995       // Don't need stuff which is overwritten
7996       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7997       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7998       // Merge in delay slot
7999       for(hr=0;hr<HOST_REGS;hr++)
8000       {
8001         if(!likely[i]) {
8002           // These are overwritten unless the branch is "likely"
8003           // and the delay slot is nullified if not taken
8004           if(rt1[i+1]&&rt1[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8005           if(rt2[i+1]&&rt2[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8006         }
8007         if(rs1[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8008         if(rs2[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8009         if(rs1[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8010         if(rs2[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8011         if(itype[i+1]==STORE || itype[i+1]==STORELR || (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) {
8012           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8013           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8014         }
8015       }
8016     }
8017     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
8018     {
8019       // SYSCALL instruction (software interrupt)
8020       nr=0;
8021     }
8022     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
8023     {
8024       // ERET instruction (return from interrupt)
8025       nr=0;
8026     }
8027     else // Non-branch
8028     {
8029       if(i<slen-1) {
8030         for(hr=0;hr<HOST_REGS;hr++) {
8031           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8032           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8033           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8034           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8035         }
8036       }
8037     }
8038     for(hr=0;hr<HOST_REGS;hr++)
8039     {
8040       // Overwritten registers are not needed
8041       if(rt1[i]&&rt1[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8042       if(rt2[i]&&rt2[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8043       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8044       // Source registers are needed
8045       if(rs1[i]==regmap_pre[i][hr]) nr|=1<<hr;
8046       if(rs2[i]==regmap_pre[i][hr]) nr|=1<<hr;
8047       if(rs1[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8048       if(rs2[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8049       if(itype[i]==STORE || itype[i]==STORELR || (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) {
8050         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8051         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8052       }
8053       // Don't store a register immediately after writing it,
8054       // may prevent dual-issue.
8055       // But do so if this is a branch target, otherwise we
8056       // might have to load the register before the branch.
8057       if(i>0&&!bt[i]&&((regs[i].wasdirty>>hr)&1)) {
8058         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8059           if(rt1[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8060           if(rt2[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8061         }
8062         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8063           if(rt1[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8064           if(rt2[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8065         }
8066       }
8067     }
8068     // Cycle count is needed at branches.  Assume it is needed at the target too.
8069     if(i==0||bt[i]||itype[i]==CJUMP||itype[i]==SPAN) {
8070       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8071       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8072     }
8073     // Save it
8074     needed_reg[i]=nr;
8075
8076     // Deallocate unneeded registers
8077     for(hr=0;hr<HOST_REGS;hr++)
8078     {
8079       if(!((nr>>hr)&1)) {
8080         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8081         if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8082            (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8083            (regs[i].regmap[hr]&63)!=PTEMP && (regs[i].regmap[hr]&63)!=CCREG)
8084         {
8085           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
8086           {
8087             if(likely[i]) {
8088               regs[i].regmap[hr]=-1;
8089               regs[i].isconst&=~(1<<hr);
8090               if(i<slen-2) {
8091                 regmap_pre[i+2][hr]=-1;
8092                 regs[i+2].wasconst&=~(1<<hr);
8093               }
8094             }
8095           }
8096         }
8097         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8098         {
8099           int map=0,temp=0;
8100           if(itype[i+1]==STORE || itype[i+1]==STORELR ||
8101              (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8102             map=INVCP;
8103           }
8104           if(itype[i+1]==LOADLR || itype[i+1]==STORELR ||
8105              itype[i+1]==C1LS || itype[i+1]==C2LS)
8106             temp=FTEMP;
8107           if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8108              (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8109              (regs[i].regmap[hr]&63)!=rt1[i+1] && (regs[i].regmap[hr]&63)!=rt2[i+1] &&
8110              regs[i].regmap[hr]!=rs1[i+1] && regs[i].regmap[hr]!=rs2[i+1] &&
8111              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8112              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8113              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8114              regs[i].regmap[hr]!=map )
8115           {
8116             regs[i].regmap[hr]=-1;
8117             regs[i].isconst&=~(1<<hr);
8118             if((branch_regs[i].regmap[hr]&63)!=rs1[i] && (branch_regs[i].regmap[hr]&63)!=rs2[i] &&
8119                (branch_regs[i].regmap[hr]&63)!=rt1[i] && (branch_regs[i].regmap[hr]&63)!=rt2[i] &&
8120                (branch_regs[i].regmap[hr]&63)!=rt1[i+1] && (branch_regs[i].regmap[hr]&63)!=rt2[i+1] &&
8121                branch_regs[i].regmap[hr]!=rs1[i+1] && branch_regs[i].regmap[hr]!=rs2[i+1] &&
8122                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8123                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8124                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8125                branch_regs[i].regmap[hr]!=map)
8126             {
8127               branch_regs[i].regmap[hr]=-1;
8128               branch_regs[i].regmap_entry[hr]=-1;
8129               if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000)
8130               {
8131                 if(!likely[i]&&i<slen-2) {
8132                   regmap_pre[i+2][hr]=-1;
8133                   regs[i+2].wasconst&=~(1<<hr);
8134                 }
8135               }
8136             }
8137           }
8138         }
8139         else
8140         {
8141           // Non-branch
8142           if(i>0)
8143           {
8144             int map=-1,temp=-1;
8145             if(itype[i]==STORE || itype[i]==STORELR ||
8146                       (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8147               map=INVCP;
8148             }
8149             if(itype[i]==LOADLR || itype[i]==STORELR ||
8150                itype[i]==C1LS || itype[i]==C2LS)
8151               temp=FTEMP;
8152             if((regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8153                regs[i].regmap[hr]!=rs1[i] && regs[i].regmap[hr]!=rs2[i] &&
8154                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map &&
8155                (itype[i]!=SPAN||regs[i].regmap[hr]!=CCREG))
8156             {
8157               if(i<slen-1&&!is_ds[i]) {
8158                 assert(regs[i].regmap[hr]<64);
8159                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8160                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8161                 {
8162                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8163                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8164                 }
8165                 regmap_pre[i+1][hr]=-1;
8166                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8167                 regs[i+1].wasconst&=~(1<<hr);
8168               }
8169               regs[i].regmap[hr]=-1;
8170               regs[i].isconst&=~(1<<hr);
8171             }
8172           }
8173         }
8174       } // if needed
8175     } // for hr
8176   }
8177
8178   /* Pass 5 - Pre-allocate registers */
8179
8180   // If a register is allocated during a loop, try to allocate it for the
8181   // entire loop, if possible.  This avoids loading/storing registers
8182   // inside of the loop.
8183
8184   signed char f_regmap[HOST_REGS];
8185   clear_all_regs(f_regmap);
8186   for(i=0;i<slen-1;i++)
8187   {
8188     if(itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8189     {
8190       if(ba[i]>=start && ba[i]<(start+i*4))
8191       if(itype[i+1]==NOP||itype[i+1]==MOV||itype[i+1]==ALU
8192       ||itype[i+1]==SHIFTIMM||itype[i+1]==IMM16||itype[i+1]==LOAD
8193       ||itype[i+1]==STORE||itype[i+1]==STORELR||itype[i+1]==C1LS
8194       ||itype[i+1]==SHIFT||itype[i+1]==COP1
8195       ||itype[i+1]==COP2||itype[i+1]==C2LS||itype[i+1]==C2OP)
8196       {
8197         int t=(ba[i]-start)>>2;
8198         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
8199         if(t<2||(itype[t-2]!=UJUMP&&itype[t-2]!=RJUMP)||rt1[t-2]!=31) // call/ret assumes no registers allocated
8200         for(hr=0;hr<HOST_REGS;hr++)
8201         {
8202           if(regs[i].regmap[hr]>=0) {
8203             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8204               // dealloc old register
8205               int n;
8206               for(n=0;n<HOST_REGS;n++)
8207               {
8208                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8209               }
8210               // and alloc new one
8211               f_regmap[hr]=regs[i].regmap[hr];
8212             }
8213           }
8214           if(branch_regs[i].regmap[hr]>=0) {
8215             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8216               // dealloc old register
8217               int n;
8218               for(n=0;n<HOST_REGS;n++)
8219               {
8220                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8221               }
8222               // and alloc new one
8223               f_regmap[hr]=branch_regs[i].regmap[hr];
8224             }
8225           }
8226           if(ooo[i]) {
8227             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8228               f_regmap[hr]=branch_regs[i].regmap[hr];
8229           }else{
8230             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8231               f_regmap[hr]=branch_regs[i].regmap[hr];
8232           }
8233           // Avoid dirty->clean transition
8234           #ifdef DESTRUCTIVE_WRITEBACK
8235           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;
8236           #endif
8237           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8238           // case above, however it's always a good idea.  We can't hoist the
8239           // load if the register was already allocated, so there's no point
8240           // wasting time analyzing most of these cases.  It only "succeeds"
8241           // when the mapping was different and the load can be replaced with
8242           // a mov, which is of negligible benefit.  So such cases are
8243           // skipped below.
8244           if(f_regmap[hr]>0) {
8245             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8246               int r=f_regmap[hr];
8247               for(j=t;j<=i;j++)
8248               {
8249                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8250                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8251                 assert(r < 64);
8252                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8253                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8254                   int k;
8255                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8256                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8257                     if(r>63) {
8258                       if(get_reg(regs[i].regmap,r&63)<0) break;
8259                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8260                     }
8261                     k=i;
8262                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8263                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8264                         //printf("no free regs for store %x\n",start+(k-1)*4);
8265                         break;
8266                       }
8267                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8268                         //printf("no-match due to different register\n");
8269                         break;
8270                       }
8271                       if(itype[k-2]==UJUMP||itype[k-2]==RJUMP||itype[k-2]==CJUMP||itype[k-2]==SJUMP) {
8272                         //printf("no-match due to branch\n");
8273                         break;
8274                       }
8275                       // call/ret fast path assumes no registers allocated
8276                       if(k>2&&(itype[k-3]==UJUMP||itype[k-3]==RJUMP)&&rt1[k-3]==31) {
8277                         break;
8278                       }
8279                       assert(r < 64);
8280                       k--;
8281                     }
8282                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8283                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8284                       while(k<i) {
8285                         regs[k].regmap_entry[hr]=f_regmap[hr];
8286                         regs[k].regmap[hr]=f_regmap[hr];
8287                         regmap_pre[k+1][hr]=f_regmap[hr];
8288                         regs[k].wasdirty&=~(1<<hr);
8289                         regs[k].dirty&=~(1<<hr);
8290                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8291                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8292                         regs[k].wasconst&=~(1<<hr);
8293                         regs[k].isconst&=~(1<<hr);
8294                         k++;
8295                       }
8296                     }
8297                     else {
8298                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8299                       break;
8300                     }
8301                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8302                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8303                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8304                       regs[i].regmap_entry[hr]=f_regmap[hr];
8305                       regs[i].regmap[hr]=f_regmap[hr];
8306                       regs[i].wasdirty&=~(1<<hr);
8307                       regs[i].dirty&=~(1<<hr);
8308                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8309                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8310                       regs[i].wasconst&=~(1<<hr);
8311                       regs[i].isconst&=~(1<<hr);
8312                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8313                       branch_regs[i].wasdirty&=~(1<<hr);
8314                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8315                       branch_regs[i].regmap[hr]=f_regmap[hr];
8316                       branch_regs[i].dirty&=~(1<<hr);
8317                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8318                       branch_regs[i].wasconst&=~(1<<hr);
8319                       branch_regs[i].isconst&=~(1<<hr);
8320                       if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&(source[i]>>16)!=0x1000) {
8321                         regmap_pre[i+2][hr]=f_regmap[hr];
8322                         regs[i+2].wasdirty&=~(1<<hr);
8323                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8324                       }
8325                     }
8326                   }
8327                   for(k=t;k<j;k++) {
8328                     // Alloc register clean at beginning of loop,
8329                     // but may dirty it in pass 6
8330                     regs[k].regmap_entry[hr]=f_regmap[hr];
8331                     regs[k].regmap[hr]=f_regmap[hr];
8332                     regs[k].dirty&=~(1<<hr);
8333                     regs[k].wasconst&=~(1<<hr);
8334                     regs[k].isconst&=~(1<<hr);
8335                     if(itype[k]==UJUMP||itype[k]==RJUMP||itype[k]==CJUMP||itype[k]==SJUMP) {
8336                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8337                       branch_regs[k].regmap[hr]=f_regmap[hr];
8338                       branch_regs[k].dirty&=~(1<<hr);
8339                       branch_regs[k].wasconst&=~(1<<hr);
8340                       branch_regs[k].isconst&=~(1<<hr);
8341                       if(itype[k]!=RJUMP&&itype[k]!=UJUMP&&(source[k]>>16)!=0x1000) {
8342                         regmap_pre[k+2][hr]=f_regmap[hr];
8343                         regs[k+2].wasdirty&=~(1<<hr);
8344                       }
8345                     }
8346                     else
8347                     {
8348                       regmap_pre[k+1][hr]=f_regmap[hr];
8349                       regs[k+1].wasdirty&=~(1<<hr);
8350                     }
8351                   }
8352                   if(regs[j].regmap[hr]==f_regmap[hr])
8353                     regs[j].regmap_entry[hr]=f_regmap[hr];
8354                   break;
8355                 }
8356                 if(j==i) break;
8357                 if(regs[j].regmap[hr]>=0)
8358                   break;
8359                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8360                   //printf("no-match due to different register\n");
8361                   break;
8362                 }
8363                 if(itype[j]==UJUMP||itype[j]==RJUMP||(source[j]>>16)==0x1000)
8364                 {
8365                   // Stop on unconditional branch
8366                   break;
8367                 }
8368                 if(itype[j]==CJUMP||itype[j]==SJUMP)
8369                 {
8370                   if(ooo[j]) {
8371                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8372                       break;
8373                   }else{
8374                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8375                       break;
8376                   }
8377                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8378                     //printf("no-match due to different register (branch)\n");
8379                     break;
8380                   }
8381                 }
8382                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8383                   //printf("No free regs for store %x\n",start+j*4);
8384                   break;
8385                 }
8386                 assert(f_regmap[hr]<64);
8387               }
8388             }
8389           }
8390         }
8391       }
8392     }else{
8393       // Non branch or undetermined branch target
8394       for(hr=0;hr<HOST_REGS;hr++)
8395       {
8396         if(hr!=EXCLUDE_REG) {
8397           if(regs[i].regmap[hr]>=0) {
8398             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8399               // dealloc old register
8400               int n;
8401               for(n=0;n<HOST_REGS;n++)
8402               {
8403                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8404               }
8405               // and alloc new one
8406               f_regmap[hr]=regs[i].regmap[hr];
8407             }
8408           }
8409         }
8410       }
8411       // Try to restore cycle count at branch targets
8412       if(bt[i]) {
8413         for(j=i;j<slen-1;j++) {
8414           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8415           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8416             //printf("no free regs for store %x\n",start+j*4);
8417             break;
8418           }
8419         }
8420         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8421           int k=i;
8422           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8423           while(k<j) {
8424             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8425             regs[k].regmap[HOST_CCREG]=CCREG;
8426             regmap_pre[k+1][HOST_CCREG]=CCREG;
8427             regs[k+1].wasdirty|=1<<HOST_CCREG;
8428             regs[k].dirty|=1<<HOST_CCREG;
8429             regs[k].wasconst&=~(1<<HOST_CCREG);
8430             regs[k].isconst&=~(1<<HOST_CCREG);
8431             k++;
8432           }
8433           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8434         }
8435         // Work backwards from the branch target
8436         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8437         {
8438           //printf("Extend backwards\n");
8439           int k;
8440           k=i;
8441           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8442             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8443               //printf("no free regs for store %x\n",start+(k-1)*4);
8444               break;
8445             }
8446             k--;
8447           }
8448           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8449             //printf("Extend CC, %x ->\n",start+k*4);
8450             while(k<=i) {
8451               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8452               regs[k].regmap[HOST_CCREG]=CCREG;
8453               regmap_pre[k+1][HOST_CCREG]=CCREG;
8454               regs[k+1].wasdirty|=1<<HOST_CCREG;
8455               regs[k].dirty|=1<<HOST_CCREG;
8456               regs[k].wasconst&=~(1<<HOST_CCREG);
8457               regs[k].isconst&=~(1<<HOST_CCREG);
8458               k++;
8459             }
8460           }
8461           else {
8462             //printf("Fail Extend CC, %x ->\n",start+k*4);
8463           }
8464         }
8465       }
8466       if(itype[i]!=STORE&&itype[i]!=STORELR&&itype[i]!=C1LS&&itype[i]!=SHIFT&&
8467          itype[i]!=NOP&&itype[i]!=MOV&&itype[i]!=ALU&&itype[i]!=SHIFTIMM&&
8468          itype[i]!=IMM16&&itype[i]!=LOAD&&itype[i]!=COP1)
8469       {
8470         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8471       }
8472     }
8473   }
8474
8475   // This allocates registers (if possible) one instruction prior
8476   // to use, which can avoid a load-use penalty on certain CPUs.
8477   for(i=0;i<slen-1;i++)
8478   {
8479     if(!i||(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP))
8480     {
8481       if(!bt[i+1])
8482       {
8483         if(itype[i]==ALU||itype[i]==MOV||itype[i]==LOAD||itype[i]==SHIFTIMM||itype[i]==IMM16
8484            ||((itype[i]==COP1||itype[i]==COP2)&&opcode2[i]<3))
8485         {
8486           if(rs1[i+1]) {
8487             if((hr=get_reg(regs[i+1].regmap,rs1[i+1]))>=0)
8488             {
8489               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8490               {
8491                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8492                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8493                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8494                 regs[i].isconst&=~(1<<hr);
8495                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8496                 constmap[i][hr]=constmap[i+1][hr];
8497                 regs[i+1].wasdirty&=~(1<<hr);
8498                 regs[i].dirty&=~(1<<hr);
8499               }
8500             }
8501           }
8502           if(rs2[i+1]) {
8503             if((hr=get_reg(regs[i+1].regmap,rs2[i+1]))>=0)
8504             {
8505               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8506               {
8507                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8508                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8509                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8510                 regs[i].isconst&=~(1<<hr);
8511                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8512                 constmap[i][hr]=constmap[i+1][hr];
8513                 regs[i+1].wasdirty&=~(1<<hr);
8514                 regs[i].dirty&=~(1<<hr);
8515               }
8516             }
8517           }
8518           // Preload target address for load instruction (non-constant)
8519           if(itype[i+1]==LOAD&&rs1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8520             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8521             {
8522               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8523               {
8524                 regs[i].regmap[hr]=rs1[i+1];
8525                 regmap_pre[i+1][hr]=rs1[i+1];
8526                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8527                 regs[i].isconst&=~(1<<hr);
8528                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8529                 constmap[i][hr]=constmap[i+1][hr];
8530                 regs[i+1].wasdirty&=~(1<<hr);
8531                 regs[i].dirty&=~(1<<hr);
8532               }
8533             }
8534           }
8535           // Load source into target register
8536           if(lt1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8537             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8538             {
8539               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8540               {
8541                 regs[i].regmap[hr]=rs1[i+1];
8542                 regmap_pre[i+1][hr]=rs1[i+1];
8543                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8544                 regs[i].isconst&=~(1<<hr);
8545                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8546                 constmap[i][hr]=constmap[i+1][hr];
8547                 regs[i+1].wasdirty&=~(1<<hr);
8548                 regs[i].dirty&=~(1<<hr);
8549               }
8550             }
8551           }
8552           // Address for store instruction (non-constant)
8553           if(itype[i+1]==STORE||itype[i+1]==STORELR
8554              ||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8555             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8556               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8557               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8558               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8559               assert(hr>=0);
8560               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8561               {
8562                 regs[i].regmap[hr]=rs1[i+1];
8563                 regmap_pre[i+1][hr]=rs1[i+1];
8564                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8565                 regs[i].isconst&=~(1<<hr);
8566                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8567                 constmap[i][hr]=constmap[i+1][hr];
8568                 regs[i+1].wasdirty&=~(1<<hr);
8569                 regs[i].dirty&=~(1<<hr);
8570               }
8571             }
8572           }
8573           if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8574             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8575               int nr;
8576               hr=get_reg(regs[i+1].regmap,FTEMP);
8577               assert(hr>=0);
8578               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8579               {
8580                 regs[i].regmap[hr]=rs1[i+1];
8581                 regmap_pre[i+1][hr]=rs1[i+1];
8582                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8583                 regs[i].isconst&=~(1<<hr);
8584                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8585                 constmap[i][hr]=constmap[i+1][hr];
8586                 regs[i+1].wasdirty&=~(1<<hr);
8587                 regs[i].dirty&=~(1<<hr);
8588               }
8589               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8590               {
8591                 // move it to another register
8592                 regs[i+1].regmap[hr]=-1;
8593                 regmap_pre[i+2][hr]=-1;
8594                 regs[i+1].regmap[nr]=FTEMP;
8595                 regmap_pre[i+2][nr]=FTEMP;
8596                 regs[i].regmap[nr]=rs1[i+1];
8597                 regmap_pre[i+1][nr]=rs1[i+1];
8598                 regs[i+1].regmap_entry[nr]=rs1[i+1];
8599                 regs[i].isconst&=~(1<<nr);
8600                 regs[i+1].isconst&=~(1<<nr);
8601                 regs[i].dirty&=~(1<<nr);
8602                 regs[i+1].wasdirty&=~(1<<nr);
8603                 regs[i+1].dirty&=~(1<<nr);
8604                 regs[i+2].wasdirty&=~(1<<nr);
8605               }
8606             }
8607           }
8608           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*/) {
8609             if(itype[i+1]==LOAD)
8610               hr=get_reg(regs[i+1].regmap,rt1[i+1]);
8611             if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8612               hr=get_reg(regs[i+1].regmap,FTEMP);
8613             if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8614               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8615               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8616             }
8617             if(hr>=0&&regs[i].regmap[hr]<0) {
8618               int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
8619               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8620                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8621                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8622                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8623                 regs[i].isconst&=~(1<<hr);
8624                 regs[i+1].wasdirty&=~(1<<hr);
8625                 regs[i].dirty&=~(1<<hr);
8626               }
8627             }
8628           }
8629         }
8630       }
8631     }
8632   }
8633
8634   /* Pass 6 - Optimize clean/dirty state */
8635   clean_registers(0,slen-1,1);
8636
8637   /* Pass 7 - Identify 32-bit registers */
8638   for (i=slen-1;i>=0;i--)
8639   {
8640     if(itype[i]==CJUMP||itype[i]==SJUMP)
8641     {
8642       // Conditional branch
8643       if((source[i]>>16)!=0x1000&&i<slen-2) {
8644         // Mark this address as a branch target since it may be called
8645         // upon return from interrupt
8646         bt[i+2]=1;
8647       }
8648     }
8649   }
8650
8651   if(itype[slen-1]==SPAN) {
8652     bt[slen-1]=1; // Mark as a branch target so instruction can restart after exception
8653   }
8654
8655 #ifdef DISASM
8656   /* Debug/disassembly */
8657   for(i=0;i<slen;i++)
8658   {
8659     printf("U:");
8660     int r;
8661     for(r=1;r<=CCREG;r++) {
8662       if((unneeded_reg[i]>>r)&1) {
8663         if(r==HIREG) printf(" HI");
8664         else if(r==LOREG) printf(" LO");
8665         else printf(" r%d",r);
8666       }
8667     }
8668     printf("\n");
8669     #if defined(__i386__) || defined(__x86_64__)
8670     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]);
8671     #endif
8672     #ifdef __arm__
8673     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]);
8674     #endif
8675     #if defined(__i386__) || defined(__x86_64__)
8676     printf("needs: ");
8677     if(needed_reg[i]&1) printf("eax ");
8678     if((needed_reg[i]>>1)&1) printf("ecx ");
8679     if((needed_reg[i]>>2)&1) printf("edx ");
8680     if((needed_reg[i]>>3)&1) printf("ebx ");
8681     if((needed_reg[i]>>5)&1) printf("ebp ");
8682     if((needed_reg[i]>>6)&1) printf("esi ");
8683     if((needed_reg[i]>>7)&1) printf("edi ");
8684     printf("\n");
8685     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]);
8686     printf("dirty: ");
8687     if(regs[i].wasdirty&1) printf("eax ");
8688     if((regs[i].wasdirty>>1)&1) printf("ecx ");
8689     if((regs[i].wasdirty>>2)&1) printf("edx ");
8690     if((regs[i].wasdirty>>3)&1) printf("ebx ");
8691     if((regs[i].wasdirty>>5)&1) printf("ebp ");
8692     if((regs[i].wasdirty>>6)&1) printf("esi ");
8693     if((regs[i].wasdirty>>7)&1) printf("edi ");
8694     #endif
8695     #ifdef __arm__
8696     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]);
8697     printf("dirty: ");
8698     if(regs[i].wasdirty&1) printf("r0 ");
8699     if((regs[i].wasdirty>>1)&1) printf("r1 ");
8700     if((regs[i].wasdirty>>2)&1) printf("r2 ");
8701     if((regs[i].wasdirty>>3)&1) printf("r3 ");
8702     if((regs[i].wasdirty>>4)&1) printf("r4 ");
8703     if((regs[i].wasdirty>>5)&1) printf("r5 ");
8704     if((regs[i].wasdirty>>6)&1) printf("r6 ");
8705     if((regs[i].wasdirty>>7)&1) printf("r7 ");
8706     if((regs[i].wasdirty>>8)&1) printf("r8 ");
8707     if((regs[i].wasdirty>>9)&1) printf("r9 ");
8708     if((regs[i].wasdirty>>10)&1) printf("r10 ");
8709     if((regs[i].wasdirty>>12)&1) printf("r12 ");
8710     #endif
8711     printf("\n");
8712     disassemble_inst(i);
8713     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
8714     #if defined(__i386__) || defined(__x86_64__)
8715     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]);
8716     if(regs[i].dirty&1) printf("eax ");
8717     if((regs[i].dirty>>1)&1) printf("ecx ");
8718     if((regs[i].dirty>>2)&1) printf("edx ");
8719     if((regs[i].dirty>>3)&1) printf("ebx ");
8720     if((regs[i].dirty>>5)&1) printf("ebp ");
8721     if((regs[i].dirty>>6)&1) printf("esi ");
8722     if((regs[i].dirty>>7)&1) printf("edi ");
8723     #endif
8724     #ifdef __arm__
8725     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]);
8726     if(regs[i].dirty&1) printf("r0 ");
8727     if((regs[i].dirty>>1)&1) printf("r1 ");
8728     if((regs[i].dirty>>2)&1) printf("r2 ");
8729     if((regs[i].dirty>>3)&1) printf("r3 ");
8730     if((regs[i].dirty>>4)&1) printf("r4 ");
8731     if((regs[i].dirty>>5)&1) printf("r5 ");
8732     if((regs[i].dirty>>6)&1) printf("r6 ");
8733     if((regs[i].dirty>>7)&1) printf("r7 ");
8734     if((regs[i].dirty>>8)&1) printf("r8 ");
8735     if((regs[i].dirty>>9)&1) printf("r9 ");
8736     if((regs[i].dirty>>10)&1) printf("r10 ");
8737     if((regs[i].dirty>>12)&1) printf("r12 ");
8738     #endif
8739     printf("\n");
8740     if(regs[i].isconst) {
8741       printf("constants: ");
8742       #if defined(__i386__) || defined(__x86_64__)
8743       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
8744       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
8745       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
8746       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
8747       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
8748       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
8749       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
8750       #endif
8751       #if defined(__arm__) || defined(__aarch64__)
8752       int r;
8753       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
8754         if ((regs[i].isconst >> r) & 1)
8755           printf(" r%d=%x", r, (u_int)constmap[i][r]);
8756       #endif
8757       printf("\n");
8758     }
8759     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
8760       #if defined(__i386__) || defined(__x86_64__)
8761       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]);
8762       if(branch_regs[i].dirty&1) printf("eax ");
8763       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
8764       if((branch_regs[i].dirty>>2)&1) printf("edx ");
8765       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
8766       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
8767       if((branch_regs[i].dirty>>6)&1) printf("esi ");
8768       if((branch_regs[i].dirty>>7)&1) printf("edi ");
8769       #endif
8770       #ifdef __arm__
8771       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]);
8772       if(branch_regs[i].dirty&1) printf("r0 ");
8773       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
8774       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
8775       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
8776       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
8777       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
8778       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
8779       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
8780       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
8781       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
8782       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
8783       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
8784       #endif
8785     }
8786   }
8787 #endif // DISASM
8788
8789   /* Pass 8 - Assembly */
8790   linkcount=0;stubcount=0;
8791   ds=0;is_delayslot=0;
8792   u_int dirty_pre=0;
8793   void *beginning=start_block();
8794   if((u_int)addr&1) {
8795     ds=1;
8796     pagespan_ds();
8797   }
8798   void *instr_addr0_override = NULL;
8799
8800   if (start == 0x80030000) {
8801     // nasty hack for the fastbios thing
8802     // override block entry to this code
8803     instr_addr0_override = out;
8804     emit_movimm(start,0);
8805     // abuse io address var as a flag that we
8806     // have already returned here once
8807     emit_readword(&address,1);
8808     emit_writeword(0,&pcaddr);
8809     emit_writeword(0,&address);
8810     emit_cmp(0,1);
8811     #ifdef __aarch64__
8812     emit_jeq(out + 4*2);
8813     emit_far_jump(new_dyna_leave);
8814     #else
8815     emit_jne(new_dyna_leave);
8816     #endif
8817   }
8818   for(i=0;i<slen;i++)
8819   {
8820     //if(ds) printf("ds: ");
8821     disassemble_inst(i);
8822     if(ds) {
8823       ds=0; // Skip delay slot
8824       if(bt[i]) assem_debug("OOPS - branch into delay slot\n");
8825       instr_addr[i] = NULL;
8826     } else {
8827       speculate_register_values(i);
8828       #ifndef DESTRUCTIVE_WRITEBACK
8829       if(i<2||(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000))
8830       {
8831         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
8832       }
8833       if((itype[i]==CJUMP||itype[i]==SJUMP)&&!likely[i]) {
8834         dirty_pre=branch_regs[i].dirty;
8835       }else{
8836         dirty_pre=regs[i].dirty;
8837       }
8838       #endif
8839       // write back
8840       if(i<2||(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000))
8841       {
8842         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
8843         loop_preload(regmap_pre[i],regs[i].regmap_entry);
8844       }
8845       // branch target entry point
8846       instr_addr[i] = out;
8847       assem_debug("<->\n");
8848       drc_dbg_emit_do_cmp(i);
8849
8850       // load regs
8851       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
8852         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
8853       load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i],rs2[i]);
8854       address_generation(i,&regs[i],regs[i].regmap_entry);
8855       load_consts(regmap_pre[i],regs[i].regmap,i);
8856       if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8857       {
8858         // Load the delay slot registers if necessary
8859         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i]&&(rs1[i+1]!=rt1[i]||rt1[i]==0))
8860           load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
8861         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))
8862           load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
8863         if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a)
8864           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
8865       }
8866       else if(i+1<slen)
8867       {
8868         // Preload registers for following instruction
8869         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i])
8870           if(rs1[i+1]!=rt1[i]&&rs1[i+1]!=rt2[i])
8871             load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
8872         if(rs2[i+1]!=rs1[i+1]&&rs2[i+1]!=rs1[i]&&rs2[i+1]!=rs2[i])
8873           if(rs2[i+1]!=rt1[i]&&rs2[i+1]!=rt2[i])
8874             load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
8875       }
8876       // TODO: if(is_ooo(i)) address_generation(i+1);
8877       if(itype[i]==CJUMP)
8878         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
8879       if(itype[i]==STORE||itype[i]==STORELR||(opcode[i]&0x3b)==0x39||(opcode[i]&0x3b)==0x3a)
8880         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
8881       // assemble
8882       switch(itype[i]) {
8883         case ALU:
8884           alu_assemble(i,&regs[i]);break;
8885         case IMM16:
8886           imm16_assemble(i,&regs[i]);break;
8887         case SHIFT:
8888           shift_assemble(i,&regs[i]);break;
8889         case SHIFTIMM:
8890           shiftimm_assemble(i,&regs[i]);break;
8891         case LOAD:
8892           load_assemble(i,&regs[i]);break;
8893         case LOADLR:
8894           loadlr_assemble(i,&regs[i]);break;
8895         case STORE:
8896           store_assemble(i,&regs[i]);break;
8897         case STORELR:
8898           storelr_assemble(i,&regs[i]);break;
8899         case COP0:
8900           cop0_assemble(i,&regs[i]);break;
8901         case COP1:
8902           cop1_assemble(i,&regs[i]);break;
8903         case C1LS:
8904           c1ls_assemble(i,&regs[i]);break;
8905         case COP2:
8906           cop2_assemble(i,&regs[i]);break;
8907         case C2LS:
8908           c2ls_assemble(i,&regs[i]);break;
8909         case C2OP:
8910           c2op_assemble(i,&regs[i]);break;
8911         case MULTDIV:
8912           multdiv_assemble(i,&regs[i]);break;
8913         case MOV:
8914           mov_assemble(i,&regs[i]);break;
8915         case SYSCALL:
8916           syscall_assemble(i,&regs[i]);break;
8917         case HLECALL:
8918           hlecall_assemble(i,&regs[i]);break;
8919         case INTCALL:
8920           intcall_assemble(i,&regs[i]);break;
8921         case UJUMP:
8922           ujump_assemble(i,&regs[i]);ds=1;break;
8923         case RJUMP:
8924           rjump_assemble(i,&regs[i]);ds=1;break;
8925         case CJUMP:
8926           cjump_assemble(i,&regs[i]);ds=1;break;
8927         case SJUMP:
8928           sjump_assemble(i,&regs[i]);ds=1;break;
8929         case SPAN:
8930           pagespan_assemble(i,&regs[i]);break;
8931       }
8932       if(itype[i]==UJUMP||itype[i]==RJUMP||(source[i]>>16)==0x1000)
8933         literal_pool(1024);
8934       else
8935         literal_pool_jumpover(256);
8936     }
8937   }
8938   //assert(itype[i-2]==UJUMP||itype[i-2]==RJUMP||(source[i-2]>>16)==0x1000);
8939   // If the block did not end with an unconditional branch,
8940   // add a jump to the next instruction.
8941   if(i>1) {
8942     if(itype[i-2]!=UJUMP&&itype[i-2]!=RJUMP&&(source[i-2]>>16)!=0x1000&&itype[i-1]!=SPAN) {
8943       assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
8944       assert(i==slen);
8945       if(itype[i-2]!=CJUMP&&itype[i-2]!=SJUMP) {
8946         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
8947         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
8948           emit_loadreg(CCREG,HOST_CCREG);
8949         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
8950       }
8951       else if(!likely[i-2])
8952       {
8953         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
8954         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
8955       }
8956       else
8957       {
8958         store_regs_bt(regs[i-2].regmap,regs[i-2].dirty,start+i*4);
8959         assert(regs[i-2].regmap[HOST_CCREG]==CCREG);
8960       }
8961       add_to_linker(out,start+i*4,0);
8962       emit_jmp(0);
8963     }
8964   }
8965   else
8966   {
8967     assert(i>0);
8968     assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
8969     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
8970     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
8971       emit_loadreg(CCREG,HOST_CCREG);
8972     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
8973     add_to_linker(out,start+i*4,0);
8974     emit_jmp(0);
8975   }
8976
8977   // TODO: delay slot stubs?
8978   // Stubs
8979   for(i=0;i<stubcount;i++)
8980   {
8981     switch(stubs[i].type)
8982     {
8983       case LOADB_STUB:
8984       case LOADH_STUB:
8985       case LOADW_STUB:
8986       case LOADD_STUB:
8987       case LOADBU_STUB:
8988       case LOADHU_STUB:
8989         do_readstub(i);break;
8990       case STOREB_STUB:
8991       case STOREH_STUB:
8992       case STOREW_STUB:
8993       case STORED_STUB:
8994         do_writestub(i);break;
8995       case CC_STUB:
8996         do_ccstub(i);break;
8997       case INVCODE_STUB:
8998         do_invstub(i);break;
8999       case FP_STUB:
9000         do_cop1stub(i);break;
9001       case STORELR_STUB:
9002         do_unalignedwritestub(i);break;
9003     }
9004   }
9005
9006   if (instr_addr0_override)
9007     instr_addr[0] = instr_addr0_override;
9008
9009   /* Pass 9 - Linker */
9010   for(i=0;i<linkcount;i++)
9011   {
9012     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9013     literal_pool(64);
9014     if (!link_addr[i].ext)
9015     {
9016       void *stub = out;
9017       void *addr = check_addr(link_addr[i].target);
9018       emit_extjump(link_addr[i].addr, link_addr[i].target);
9019       if (addr) {
9020         set_jump_target(link_addr[i].addr, addr);
9021         add_link(link_addr[i].target,stub);
9022       }
9023       else
9024         set_jump_target(link_addr[i].addr, stub);
9025     }
9026     else
9027     {
9028       // Internal branch
9029       int target=(link_addr[i].target-start)>>2;
9030       assert(target>=0&&target<slen);
9031       assert(instr_addr[target]);
9032       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9033       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9034       //#else
9035       set_jump_target(link_addr[i].addr, instr_addr[target]);
9036       //#endif
9037     }
9038   }
9039   // External Branch Targets (jump_in)
9040   if(copy+slen*4>(void *)shadow+sizeof(shadow)) copy=shadow;
9041   for(i=0;i<slen;i++)
9042   {
9043     if(bt[i]||i==0)
9044     {
9045       if(instr_addr[i]) // TODO - delay slots (=null)
9046       {
9047         u_int vaddr=start+i*4;
9048         u_int page=get_page(vaddr);
9049         u_int vpage=get_vpage(vaddr);
9050         literal_pool(256);
9051         {
9052           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9053           assem_debug("jump_in: %x\n",start+i*4);
9054           ll_add(jump_dirty+vpage,vaddr,out);
9055           void *entry_point = do_dirty_stub(i);
9056           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9057           // If there was an existing entry in the hash table,
9058           // replace it with the new address.
9059           // Don't add new entries.  We'll insert the
9060           // ones that actually get used in check_addr().
9061           struct ht_entry *ht_bin = hash_table_get(vaddr);
9062           if (ht_bin->vaddr[0] == vaddr)
9063             ht_bin->tcaddr[0] = entry_point;
9064           if (ht_bin->vaddr[1] == vaddr)
9065             ht_bin->tcaddr[1] = entry_point;
9066         }
9067       }
9068     }
9069   }
9070   // Write out the literal pool if necessary
9071   literal_pool(0);
9072   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9073   // Align code
9074   if(((u_int)out)&7) emit_addnop(13);
9075   #endif
9076   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9077   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9078   memcpy(copy,source,slen*4);
9079   copy+=slen*4;
9080
9081   end_block(beginning);
9082
9083   // If we're within 256K of the end of the buffer,
9084   // start over from the beginning. (Is 256K enough?)
9085   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9086     out = ndrc->translation_cache;
9087
9088   // Trap writes to any of the pages we compiled
9089   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9090     invalid_code[i]=0;
9091   }
9092   inv_code_start=inv_code_end=~0;
9093
9094   // for PCSX we need to mark all mirrors too
9095   if(get_page(start)<(RAM_SIZE>>12))
9096     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9097       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9098       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9099       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9100
9101   /* Pass 10 - Free memory by expiring oldest blocks */
9102
9103   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9104   while(expirep!=end)
9105   {
9106     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9107     uintptr_t base=(uintptr_t)ndrc->translation_cache+((expirep>>13)<<shift); // Base address of this block
9108     inv_debug("EXP: Phase %d\n",expirep);
9109     switch((expirep>>11)&3)
9110     {
9111       case 0:
9112         // Clear jump_in and jump_dirty
9113         ll_remove_matching_addrs(jump_in+(expirep&2047),base,shift);
9114         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base,shift);
9115         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base,shift);
9116         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base,shift);
9117         break;
9118       case 1:
9119         // Clear pointers
9120         ll_kill_pointers(jump_out[expirep&2047],base,shift);
9121         ll_kill_pointers(jump_out[(expirep&2047)+2048],base,shift);
9122         break;
9123       case 2:
9124         // Clear hash table
9125         for(i=0;i<32;i++) {
9126           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9127           if (((uintptr_t)ht_bin->tcaddr[1]>>shift) == (base>>shift) ||
9128              (((uintptr_t)ht_bin->tcaddr[1]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9129             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9130             ht_bin->vaddr[1] = -1;
9131             ht_bin->tcaddr[1] = NULL;
9132           }
9133           if (((uintptr_t)ht_bin->tcaddr[0]>>shift) == (base>>shift) ||
9134              (((uintptr_t)ht_bin->tcaddr[0]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9135             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9136             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9137             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9138             ht_bin->vaddr[1] = -1;
9139             ht_bin->tcaddr[1] = NULL;
9140           }
9141         }
9142         break;
9143       case 3:
9144         // Clear jump_out
9145         if((expirep&2047)==0)
9146           do_clear_cache();
9147         ll_remove_matching_addrs(jump_out+(expirep&2047),base,shift);
9148         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base,shift);
9149         break;
9150     }
9151     expirep=(expirep+1)&65535;
9152   }
9153   return 0;
9154 }
9155
9156 // vim:shiftwidth=2:expandtab