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