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