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