drc,interpreter: add mul/div stalls
[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 "../gte.h"
41 #include "emu_if.h" // emulator interface
42
43 #define noinline __attribute__((noinline,noclone))
44 #ifndef ARRAY_SIZE
45 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
46 #endif
47 #ifndef min
48 #define min(a, b) ((b) < (a) ? (b) : (a))
49 #endif
50 #ifndef max
51 #define max(a, b) ((b) > (a) ? (b) : (a))
52 #endif
53
54 //#define DISASM
55 //#define ASSEM_PRINT
56
57 #ifdef ASSEM_PRINT
58 #define assem_debug printf
59 #else
60 #define assem_debug(...)
61 #endif
62 //#define inv_debug printf
63 #define inv_debug(...)
64
65 #ifdef __i386__
66 #include "assem_x86.h"
67 #endif
68 #ifdef __x86_64__
69 #include "assem_x64.h"
70 #endif
71 #ifdef __arm__
72 #include "assem_arm.h"
73 #endif
74 #ifdef __aarch64__
75 #include "assem_arm64.h"
76 #endif
77
78 #define RAM_SIZE 0x200000
79 #define MAXBLOCK 4096
80 #define MAX_OUTPUT_BLOCK_SIZE 262144
81
82 struct ndrc_mem
83 {
84   u_char translation_cache[1 << TARGET_SIZE_2];
85   struct
86   {
87     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
88     const void *f[2048 / sizeof(void *)];
89   } tramp;
90 };
91
92 #ifdef BASE_ADDR_DYNAMIC
93 static struct ndrc_mem *ndrc;
94 #else
95 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
96 static struct ndrc_mem *ndrc = &ndrc_;
97 #endif
98
99 // stubs
100 enum stub_type {
101   CC_STUB = 1,
102   FP_STUB = 2,
103   LOADB_STUB = 3,
104   LOADH_STUB = 4,
105   LOADW_STUB = 5,
106   LOADD_STUB = 6,
107   LOADBU_STUB = 7,
108   LOADHU_STUB = 8,
109   STOREB_STUB = 9,
110   STOREH_STUB = 10,
111   STOREW_STUB = 11,
112   STORED_STUB = 12,
113   STORELR_STUB = 13,
114   INVCODE_STUB = 14,
115 };
116
117 struct regstat
118 {
119   signed char regmap_entry[HOST_REGS];
120   signed char regmap[HOST_REGS];
121   uint64_t wasdirty;
122   uint64_t dirty;
123   uint64_t u;
124   u_int wasconst;
125   u_int isconst;
126   u_int loadedconst;             // host regs that have constants loaded
127   u_int waswritten;              // MIPS regs that were used as store base before
128 };
129
130 // note: asm depends on this layout
131 struct ll_entry
132 {
133   u_int vaddr;
134   u_int reg_sv_flags;
135   void *addr;
136   struct ll_entry *next;
137 };
138
139 struct ht_entry
140 {
141   u_int vaddr[2];
142   void *tcaddr[2];
143 };
144
145 struct code_stub
146 {
147   enum stub_type type;
148   void *addr;
149   void *retaddr;
150   u_int a;
151   uintptr_t b;
152   uintptr_t c;
153   u_int d;
154   u_int e;
155 };
156
157 struct link_entry
158 {
159   void *addr;
160   u_int target;
161   u_int ext;
162 };
163
164   // used by asm:
165   u_char *out;
166   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
167   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
168   struct ll_entry *jump_dirty[4096];
169
170   static struct ll_entry *jump_out[4096];
171   static u_int start;
172   static u_int *source;
173   static char insn[MAXBLOCK][10];
174   static u_char itype[MAXBLOCK];
175   static u_char opcode[MAXBLOCK];
176   static u_char opcode2[MAXBLOCK];
177   static u_char bt[MAXBLOCK];
178   static u_char rs1[MAXBLOCK];
179   static u_char rs2[MAXBLOCK];
180   static u_char rt1[MAXBLOCK];
181   static u_char rt2[MAXBLOCK];
182   static u_char dep1[MAXBLOCK];
183   static u_char dep2[MAXBLOCK];
184   static u_char lt1[MAXBLOCK];
185   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
186   static uint64_t gte_rt[MAXBLOCK];
187   static uint64_t gte_unneeded[MAXBLOCK];
188   static u_int smrv[32]; // speculated MIPS register values
189   static u_int smrv_strong; // mask or regs that are likely to have correct values
190   static u_int smrv_weak; // same, but somewhat less likely
191   static u_int smrv_strong_next; // same, but after current insn executes
192   static u_int smrv_weak_next;
193   static int imm[MAXBLOCK];
194   static u_int ba[MAXBLOCK];
195   static char likely[MAXBLOCK];
196   static char is_ds[MAXBLOCK];
197   static char ooo[MAXBLOCK];
198   static uint64_t unneeded_reg[MAXBLOCK];
199   static uint64_t branch_unneeded_reg[MAXBLOCK];
200   static signed char regmap_pre[MAXBLOCK][HOST_REGS]; // pre-instruction i?
201   // contains 'real' consts at [i] insn, but may differ from what's actually
202   // loaded in host reg as 'final' value is always loaded, see get_final_value()
203   static uint32_t current_constmap[HOST_REGS];
204   static uint32_t constmap[MAXBLOCK][HOST_REGS];
205   static struct regstat regs[MAXBLOCK];
206   static struct regstat branch_regs[MAXBLOCK];
207   static signed char minimum_free_regs[MAXBLOCK];
208   static u_int needed_reg[MAXBLOCK];
209   static u_int wont_dirty[MAXBLOCK];
210   static u_int will_dirty[MAXBLOCK];
211   static int ccadj[MAXBLOCK];
212   static int slen;
213   static void *instr_addr[MAXBLOCK];
214   static struct link_entry link_addr[MAXBLOCK];
215   static int linkcount;
216   static struct code_stub stubs[MAXBLOCK*3];
217   static int stubcount;
218   static u_int literals[1024][2];
219   static int literalcount;
220   static int is_delayslot;
221   static char shadow[1048576]  __attribute__((aligned(16)));
222   static void *copy;
223   static int expirep;
224   static u_int stop_after_jal;
225 #ifndef RAM_FIXED
226   static uintptr_t ram_offset;
227 #else
228   static const uintptr_t ram_offset=0;
229 #endif
230
231   int new_dynarec_hacks;
232   int new_dynarec_hacks_pergame;
233   int new_dynarec_hacks_old;
234   int new_dynarec_did_compile;
235
236   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
237
238   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
239   extern int last_count;  // last absolute target, often = next_interupt
240   extern int pcaddr;
241   extern int pending_exception;
242   extern int branch_target;
243   extern uintptr_t mini_ht[32][2];
244   extern u_char restore_candidate[512];
245
246   /* registers that may be allocated */
247   /* 1-31 gpr */
248 #define LOREG 32 // lo
249 #define HIREG 33 // hi
250 //#define FSREG 34 // FPU status (FCSR)
251 #define CSREG 35 // Coprocessor status
252 #define CCREG 36 // Cycle count
253 #define INVCP 37 // Pointer to invalid_code
254 //#define MMREG 38 // Pointer to memory_map
255 //#define ROREG 39 // ram offset (if rdram!=0x80000000)
256 #define TEMPREG 40
257 #define FTEMP 40 // FPU temporary register
258 #define PTEMP 41 // Prefetch temporary register
259 //#define TLREG 42 // TLB mapping offset
260 #define RHASH 43 // Return address hash
261 #define RHTBL 44 // Return address hash table address
262 #define RTEMP 45 // JR/JALR address register
263 #define MAXREG 45
264 #define AGEN1 46 // Address generation temporary register
265 //#define AGEN2 47 // Address generation temporary register
266 //#define MGEN1 48 // Maptable address generation temporary register
267 //#define MGEN2 49 // Maptable address generation temporary register
268 #define BTREG 50 // Branch target temporary register
269
270   /* instruction types */
271 #define NOP 0     // No operation
272 #define LOAD 1    // Load
273 #define STORE 2   // Store
274 #define LOADLR 3  // Unaligned load
275 #define STORELR 4 // Unaligned store
276 #define MOV 5     // Move
277 #define ALU 6     // Arithmetic/logic
278 #define MULTDIV 7 // Multiply/divide
279 #define SHIFT 8   // Shift by register
280 #define SHIFTIMM 9// Shift by immediate
281 #define IMM16 10  // 16-bit immediate
282 #define RJUMP 11  // Unconditional jump to register
283 #define UJUMP 12  // Unconditional jump
284 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
285 #define SJUMP 14  // Conditional branch (regimm format)
286 #define COP0 15   // Coprocessor 0
287 #define COP1 16   // Coprocessor 1
288 #define C1LS 17   // Coprocessor 1 load/store
289 //#define FJUMP 18  // Conditional branch (floating point)
290 //#define FLOAT 19  // Floating point unit
291 //#define FCONV 20  // Convert integer to float
292 //#define FCOMP 21  // Floating point compare (sets FSREG)
293 #define SYSCALL 22// SYSCALL
294 #define OTHER 23  // Other
295 #define SPAN 24   // Branch/delay slot spans 2 pages
296 #define NI 25     // Not implemented
297 #define HLECALL 26// PCSX fake opcodes for HLE
298 #define COP2 27   // Coprocessor 2 move
299 #define C2LS 28   // Coprocessor 2 load/store
300 #define C2OP 29   // Coprocessor 2 operation
301 #define INTCALL 30// Call interpreter to handle rare corner cases
302
303   /* branch codes */
304 #define TAKEN 1
305 #define NOTTAKEN 2
306 #define NULLDS 3
307
308 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
309 #define DJT_2 (void *)2l
310
311 // asm linkage
312 int new_recompile_block(u_int addr);
313 void *get_addr_ht(u_int vaddr);
314 void invalidate_block(u_int block);
315 void invalidate_addr(u_int addr);
316 void remove_hash(int vaddr);
317 void dyna_linker();
318 void dyna_linker_ds();
319 void verify_code();
320 void verify_code_ds();
321 void cc_interrupt();
322 void fp_exception();
323 void fp_exception_ds();
324 void jump_to_new_pc();
325 void call_gteStall();
326 void new_dyna_leave();
327
328 // Needed by assembler
329 static void wb_register(signed char r,signed char regmap[],uint64_t dirty);
330 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty);
331 static void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr);
332 static void load_all_regs(signed char i_regmap[]);
333 static void load_needed_regs(signed char i_regmap[],signed char next_regmap[]);
334 static void load_regs_entry(int t);
335 static void load_all_consts(signed char regmap[],u_int dirty,int i);
336 static u_int get_host_reglist(const signed char *regmap);
337
338 static int verify_dirty(const u_int *ptr);
339 static int get_final_value(int hr, int i, int *value);
340 static void add_stub(enum stub_type type, void *addr, void *retaddr,
341   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
342 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
343   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
344 static void add_to_linker(void *addr, u_int target, int ext);
345 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override);
346 static void *get_direct_memhandler(void *table, u_int addr,
347   enum stub_type type, uintptr_t *addr_host);
348 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
349 static void pass_args(int a0, int a1);
350 static void emit_far_jump(const void *f);
351 static void emit_far_call(const void *f);
352
353 static void mprotect_w_x(void *start, void *end, int is_x)
354 {
355 #ifdef NO_WRITE_EXEC
356   #if defined(VITA)
357   // *Open* enables write on all memory that was
358   // allocated by sceKernelAllocMemBlockForVM()?
359   if (is_x)
360     sceKernelCloseVMDomain();
361   else
362     sceKernelOpenVMDomain();
363   #else
364   u_long mstart = (u_long)start & ~4095ul;
365   u_long mend = (u_long)end;
366   if (mprotect((void *)mstart, mend - mstart,
367                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
368     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
369   #endif
370 #endif
371 }
372
373 static void start_tcache_write(void *start, void *end)
374 {
375   mprotect_w_x(start, end, 0);
376 }
377
378 static void end_tcache_write(void *start, void *end)
379 {
380 #if defined(__arm__) || defined(__aarch64__)
381   size_t len = (char *)end - (char *)start;
382   #if   defined(__BLACKBERRY_QNX__)
383   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
384   #elif defined(__MACH__)
385   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
386   #elif defined(VITA)
387   sceKernelSyncVMDomain(sceBlock, start, len);
388   #elif defined(_3DS)
389   ctr_flush_invalidate_cache();
390   #elif defined(__aarch64__)
391   // as of 2021, __clear_cache() is still broken on arm64
392   // so here is a custom one :(
393   clear_cache_arm64(start, end);
394   #else
395   __clear_cache(start, end);
396   #endif
397   (void)len;
398 #endif
399
400   mprotect_w_x(start, end, 1);
401 }
402
403 static void *start_block(void)
404 {
405   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
406   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
407     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
408   start_tcache_write(out, end);
409   return out;
410 }
411
412 static void end_block(void *start)
413 {
414   end_tcache_write(start, out);
415 }
416
417 // also takes care of w^x mappings when patching code
418 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
419
420 static void mark_clear_cache(void *target)
421 {
422   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
423   u_int mask = 1u << ((offset >> 12) & 31);
424   if (!(needs_clear_cache[offset >> 17] & mask)) {
425     char *start = (char *)((uintptr_t)target & ~4095l);
426     start_tcache_write(start, start + 4095);
427     needs_clear_cache[offset >> 17] |= mask;
428   }
429 }
430
431 // Clearing the cache is rather slow on ARM Linux, so mark the areas
432 // that need to be cleared, and then only clear these areas once.
433 static void do_clear_cache(void)
434 {
435   int i, j;
436   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
437   {
438     u_int bitmap = needs_clear_cache[i];
439     if (!bitmap)
440       continue;
441     for (j = 0; j < 32; j++)
442     {
443       u_char *start, *end;
444       if (!(bitmap & (1<<j)))
445         continue;
446
447       start = ndrc->translation_cache + i*131072 + j*4096;
448       end = start + 4095;
449       for (j++; j < 32; j++) {
450         if (!(bitmap & (1<<j)))
451           break;
452         end += 4096;
453       }
454       end_tcache_write(start, end);
455     }
456     needs_clear_cache[i] = 0;
457   }
458 }
459
460 //#define DEBUG_CYCLE_COUNT 1
461
462 #define NO_CYCLE_PENALTY_THR 12
463
464 int cycle_multiplier; // 100 for 1.0
465 int cycle_multiplier_override;
466 int cycle_multiplier_old;
467
468 static int CLOCK_ADJUST(int x)
469 {
470   int m = cycle_multiplier_override
471         ? cycle_multiplier_override : cycle_multiplier;
472   int s=(x>>31)|1;
473   return (x * m + s * 50) / 100;
474 }
475
476 // is the op an unconditional jump?
477 static int is_ujump(int i)
478 {
479   return itype[i] == UJUMP || itype[i] == RJUMP
480     || (source[i] >> 16) == 0x1000; // beq r0, r0, offset // b offset
481 }
482
483 static int is_jump(int i)
484 {
485   return itype[i] == RJUMP || itype[i] == UJUMP || itype[i] == CJUMP || itype[i] == SJUMP;
486 }
487
488 static u_int get_page(u_int vaddr)
489 {
490   u_int page=vaddr&~0xe0000000;
491   if (page < 0x1000000)
492     page &= ~0x0e00000; // RAM mirrors
493   page>>=12;
494   if(page>2048) page=2048+(page&2047);
495   return page;
496 }
497
498 // no virtual mem in PCSX
499 static u_int get_vpage(u_int vaddr)
500 {
501   return get_page(vaddr);
502 }
503
504 static struct ht_entry *hash_table_get(u_int vaddr)
505 {
506   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
507 }
508
509 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
510 {
511   ht_bin->vaddr[1] = ht_bin->vaddr[0];
512   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
513   ht_bin->vaddr[0] = vaddr;
514   ht_bin->tcaddr[0] = tcaddr;
515 }
516
517 // some messy ari64's code, seems to rely on unsigned 32bit overflow
518 static int doesnt_expire_soon(void *tcaddr)
519 {
520   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
521   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
522 }
523
524 // Get address from virtual address
525 // This is called from the recompiled JR/JALR instructions
526 void noinline *get_addr(u_int vaddr)
527 {
528   u_int page=get_page(vaddr);
529   u_int vpage=get_vpage(vaddr);
530   struct ll_entry *head;
531   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
532   head=jump_in[page];
533   while(head!=NULL) {
534     if(head->vaddr==vaddr) {
535   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
536       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
537       return head->addr;
538     }
539     head=head->next;
540   }
541   head=jump_dirty[vpage];
542   while(head!=NULL) {
543     if(head->vaddr==vaddr) {
544       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
545       // Don't restore blocks which are about to expire from the cache
546       if (doesnt_expire_soon(head->addr))
547       if (verify_dirty(head->addr)) {
548         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
549         invalid_code[vaddr>>12]=0;
550         inv_code_start=inv_code_end=~0;
551         if(vpage<2048) {
552           restore_candidate[vpage>>3]|=1<<(vpage&7);
553         }
554         else restore_candidate[page>>3]|=1<<(page&7);
555         struct ht_entry *ht_bin = hash_table_get(vaddr);
556         if (ht_bin->vaddr[0] == vaddr)
557           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
558         else
559           hash_table_add(ht_bin, vaddr, head->addr);
560
561         return head->addr;
562       }
563     }
564     head=head->next;
565   }
566   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
567   int r=new_recompile_block(vaddr);
568   if(r==0) return get_addr(vaddr);
569   // Execute in unmapped page, generate pagefault execption
570   Status|=2;
571   Cause=(vaddr<<31)|0x8;
572   EPC=(vaddr&1)?vaddr-5:vaddr;
573   BadVAddr=(vaddr&~1);
574   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
575   EntryHi=BadVAddr&0xFFFFE000;
576   return get_addr_ht(0x80000000);
577 }
578 // Look up address in hash table first
579 void *get_addr_ht(u_int vaddr)
580 {
581   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
582   const struct ht_entry *ht_bin = hash_table_get(vaddr);
583   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
584   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
585   return get_addr(vaddr);
586 }
587
588 void clear_all_regs(signed char regmap[])
589 {
590   int hr;
591   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
592 }
593
594 static signed char get_reg(const signed char regmap[],int r)
595 {
596   int hr;
597   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
598   return -1;
599 }
600
601 // Find a register that is available for two consecutive cycles
602 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
603 {
604   int hr;
605   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
606   return -1;
607 }
608
609 int count_free_regs(signed char regmap[])
610 {
611   int count=0;
612   int hr;
613   for(hr=0;hr<HOST_REGS;hr++)
614   {
615     if(hr!=EXCLUDE_REG) {
616       if(regmap[hr]<0) count++;
617     }
618   }
619   return count;
620 }
621
622 void dirty_reg(struct regstat *cur,signed char reg)
623 {
624   int hr;
625   if(!reg) return;
626   for (hr=0;hr<HOST_REGS;hr++) {
627     if((cur->regmap[hr]&63)==reg) {
628       cur->dirty|=1<<hr;
629     }
630   }
631 }
632
633 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
634 {
635   int hr;
636   if(!reg) return;
637   for (hr=0;hr<HOST_REGS;hr++) {
638     if(cur->regmap[hr]==reg) {
639       cur->isconst|=1<<hr;
640       current_constmap[hr]=value;
641     }
642   }
643 }
644
645 static void clear_const(struct regstat *cur, signed char reg)
646 {
647   int hr;
648   if(!reg) return;
649   for (hr=0;hr<HOST_REGS;hr++) {
650     if((cur->regmap[hr]&63)==reg) {
651       cur->isconst&=~(1<<hr);
652     }
653   }
654 }
655
656 static int is_const(struct regstat *cur, signed char reg)
657 {
658   int hr;
659   if(reg<0) return 0;
660   if(!reg) return 1;
661   for (hr=0;hr<HOST_REGS;hr++) {
662     if((cur->regmap[hr]&63)==reg) {
663       return (cur->isconst>>hr)&1;
664     }
665   }
666   return 0;
667 }
668
669 static uint32_t get_const(struct regstat *cur, signed char reg)
670 {
671   int hr;
672   if(!reg) return 0;
673   for (hr=0;hr<HOST_REGS;hr++) {
674     if(cur->regmap[hr]==reg) {
675       return current_constmap[hr];
676     }
677   }
678   SysPrintf("Unknown constant in r%d\n",reg);
679   abort();
680 }
681
682 // Least soon needed registers
683 // Look at the next ten instructions and see which registers
684 // will be used.  Try not to reallocate these.
685 void lsn(u_char hsn[], int i, int *preferred_reg)
686 {
687   int j;
688   int b=-1;
689   for(j=0;j<9;j++)
690   {
691     if(i+j>=slen) {
692       j=slen-i-1;
693       break;
694     }
695     if (is_ujump(i+j))
696     {
697       // Don't go past an unconditonal jump
698       j++;
699       break;
700     }
701   }
702   for(;j>=0;j--)
703   {
704     if(rs1[i+j]) hsn[rs1[i+j]]=j;
705     if(rs2[i+j]) hsn[rs2[i+j]]=j;
706     if(rt1[i+j]) hsn[rt1[i+j]]=j;
707     if(rt2[i+j]) hsn[rt2[i+j]]=j;
708     if(itype[i+j]==STORE || itype[i+j]==STORELR) {
709       // Stores can allocate zero
710       hsn[rs1[i+j]]=j;
711       hsn[rs2[i+j]]=j;
712     }
713     // On some architectures stores need invc_ptr
714     #if defined(HOST_IMM8)
715     if(itype[i+j]==STORE || itype[i+j]==STORELR || (opcode[i+j]&0x3b)==0x39 || (opcode[i+j]&0x3b)==0x3a) {
716       hsn[INVCP]=j;
717     }
718     #endif
719     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
720     {
721       hsn[CCREG]=j;
722       b=j;
723     }
724   }
725   if(b>=0)
726   {
727     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
728     {
729       // Follow first branch
730       int t=(ba[i+b]-start)>>2;
731       j=7-b;if(t+j>=slen) j=slen-t-1;
732       for(;j>=0;j--)
733       {
734         if(rs1[t+j]) if(hsn[rs1[t+j]]>j+b+2) hsn[rs1[t+j]]=j+b+2;
735         if(rs2[t+j]) if(hsn[rs2[t+j]]>j+b+2) hsn[rs2[t+j]]=j+b+2;
736         //if(rt1[t+j]) if(hsn[rt1[t+j]]>j+b+2) hsn[rt1[t+j]]=j+b+2;
737         //if(rt2[t+j]) if(hsn[rt2[t+j]]>j+b+2) hsn[rt2[t+j]]=j+b+2;
738       }
739     }
740     // TODO: preferred register based on backward branch
741   }
742   // Delay slot should preferably not overwrite branch conditions or cycle count
743   if (i > 0 && is_jump(i-1)) {
744     if(rs1[i-1]) if(hsn[rs1[i-1]]>1) hsn[rs1[i-1]]=1;
745     if(rs2[i-1]) if(hsn[rs2[i-1]]>1) hsn[rs2[i-1]]=1;
746     hsn[CCREG]=1;
747     // ...or hash tables
748     hsn[RHASH]=1;
749     hsn[RHTBL]=1;
750   }
751   // Coprocessor load/store needs FTEMP, even if not declared
752   if(itype[i]==C1LS||itype[i]==C2LS) {
753     hsn[FTEMP]=0;
754   }
755   // Load L/R also uses FTEMP as a temporary register
756   if(itype[i]==LOADLR) {
757     hsn[FTEMP]=0;
758   }
759   // Also SWL/SWR/SDL/SDR
760   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) {
761     hsn[FTEMP]=0;
762   }
763   // Don't remove the miniht registers
764   if(itype[i]==UJUMP||itype[i]==RJUMP)
765   {
766     hsn[RHASH]=0;
767     hsn[RHTBL]=0;
768   }
769 }
770
771 // We only want to allocate registers if we're going to use them again soon
772 int needed_again(int r, int i)
773 {
774   int j;
775   int b=-1;
776   int rn=10;
777
778   if (i > 0 && is_ujump(i-1))
779   {
780     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
781       return 0; // Don't need any registers if exiting the block
782   }
783   for(j=0;j<9;j++)
784   {
785     if(i+j>=slen) {
786       j=slen-i-1;
787       break;
788     }
789     if (is_ujump(i+j))
790     {
791       // Don't go past an unconditonal jump
792       j++;
793       break;
794     }
795     if(itype[i+j]==SYSCALL||itype[i+j]==HLECALL||itype[i+j]==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
796     {
797       break;
798     }
799   }
800   for(;j>=1;j--)
801   {
802     if(rs1[i+j]==r) rn=j;
803     if(rs2[i+j]==r) rn=j;
804     if((unneeded_reg[i+j]>>r)&1) rn=10;
805     if(i+j>=0&&(itype[i+j]==UJUMP||itype[i+j]==CJUMP||itype[i+j]==SJUMP))
806     {
807       b=j;
808     }
809   }
810   /*
811   if(b>=0)
812   {
813     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
814     {
815       // Follow first branch
816       int o=rn;
817       int t=(ba[i+b]-start)>>2;
818       j=7-b;if(t+j>=slen) j=slen-t-1;
819       for(;j>=0;j--)
820       {
821         if(!((unneeded_reg[t+j]>>r)&1)) {
822           if(rs1[t+j]==r) if(rn>j+b+2) rn=j+b+2;
823           if(rs2[t+j]==r) if(rn>j+b+2) rn=j+b+2;
824         }
825         else rn=o;
826       }
827     }
828   }*/
829   if(rn<10) return 1;
830   (void)b;
831   return 0;
832 }
833
834 // Try to match register allocations at the end of a loop with those
835 // at the beginning
836 int loop_reg(int i, int r, int hr)
837 {
838   int j,k;
839   for(j=0;j<9;j++)
840   {
841     if(i+j>=slen) {
842       j=slen-i-1;
843       break;
844     }
845     if (is_ujump(i+j))
846     {
847       // Don't go past an unconditonal jump
848       j++;
849       break;
850     }
851   }
852   k=0;
853   if(i>0){
854     if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP)
855       k--;
856   }
857   for(;k<j;k++)
858   {
859     assert(r < 64);
860     if((unneeded_reg[i+k]>>r)&1) return hr;
861     if(i+k>=0&&(itype[i+k]==UJUMP||itype[i+k]==CJUMP||itype[i+k]==SJUMP))
862     {
863       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
864       {
865         int t=(ba[i+k]-start)>>2;
866         int reg=get_reg(regs[t].regmap_entry,r);
867         if(reg>=0) return reg;
868         //reg=get_reg(regs[t+1].regmap_entry,r);
869         //if(reg>=0) return reg;
870       }
871     }
872   }
873   return hr;
874 }
875
876
877 // Allocate every register, preserving source/target regs
878 void alloc_all(struct regstat *cur,int i)
879 {
880   int hr;
881
882   for(hr=0;hr<HOST_REGS;hr++) {
883     if(hr!=EXCLUDE_REG) {
884       if(((cur->regmap[hr]&63)!=rs1[i])&&((cur->regmap[hr]&63)!=rs2[i])&&
885          ((cur->regmap[hr]&63)!=rt1[i])&&((cur->regmap[hr]&63)!=rt2[i]))
886       {
887         cur->regmap[hr]=-1;
888         cur->dirty&=~(1<<hr);
889       }
890       // Don't need zeros
891       if((cur->regmap[hr]&63)==0)
892       {
893         cur->regmap[hr]=-1;
894         cur->dirty&=~(1<<hr);
895       }
896     }
897   }
898 }
899
900 #ifndef NDEBUG
901 static int host_tempreg_in_use;
902
903 static void host_tempreg_acquire(void)
904 {
905   assert(!host_tempreg_in_use);
906   host_tempreg_in_use = 1;
907 }
908
909 static void host_tempreg_release(void)
910 {
911   host_tempreg_in_use = 0;
912 }
913 #else
914 static void host_tempreg_acquire(void) {}
915 static void host_tempreg_release(void) {}
916 #endif
917
918 #ifdef ASSEM_PRINT
919 extern void gen_interupt();
920 extern void do_insn_cmp();
921 #define FUNCNAME(f) { f, " " #f }
922 static const struct {
923   void *addr;
924   const char *name;
925 } function_names[] = {
926   FUNCNAME(cc_interrupt),
927   FUNCNAME(gen_interupt),
928   FUNCNAME(get_addr_ht),
929   FUNCNAME(get_addr),
930   FUNCNAME(jump_handler_read8),
931   FUNCNAME(jump_handler_read16),
932   FUNCNAME(jump_handler_read32),
933   FUNCNAME(jump_handler_write8),
934   FUNCNAME(jump_handler_write16),
935   FUNCNAME(jump_handler_write32),
936   FUNCNAME(invalidate_addr),
937   FUNCNAME(jump_to_new_pc),
938   FUNCNAME(call_gteStall),
939   FUNCNAME(new_dyna_leave),
940   FUNCNAME(pcsx_mtc0),
941   FUNCNAME(pcsx_mtc0_ds),
942 #ifdef DRC_DBG
943   FUNCNAME(do_insn_cmp),
944 #endif
945 #ifdef __arm__
946   FUNCNAME(verify_code),
947 #endif
948 };
949
950 static const char *func_name(const void *a)
951 {
952   int i;
953   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
954     if (function_names[i].addr == a)
955       return function_names[i].name;
956   return "";
957 }
958 #else
959 #define func_name(x) ""
960 #endif
961
962 #ifdef __i386__
963 #include "assem_x86.c"
964 #endif
965 #ifdef __x86_64__
966 #include "assem_x64.c"
967 #endif
968 #ifdef __arm__
969 #include "assem_arm.c"
970 #endif
971 #ifdef __aarch64__
972 #include "assem_arm64.c"
973 #endif
974
975 static void *get_trampoline(const void *f)
976 {
977   size_t i;
978
979   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
980     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
981       break;
982   }
983   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
984     SysPrintf("trampoline table is full, last func %p\n", f);
985     abort();
986   }
987   if (ndrc->tramp.f[i] == NULL) {
988     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
989     ndrc->tramp.f[i] = f;
990     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
991   }
992   return &ndrc->tramp.ops[i];
993 }
994
995 static void emit_far_jump(const void *f)
996 {
997   if (can_jump_or_call(f)) {
998     emit_jmp(f);
999     return;
1000   }
1001
1002   f = get_trampoline(f);
1003   emit_jmp(f);
1004 }
1005
1006 static void emit_far_call(const void *f)
1007 {
1008   if (can_jump_or_call(f)) {
1009     emit_call(f);
1010     return;
1011   }
1012
1013   f = get_trampoline(f);
1014   emit_call(f);
1015 }
1016
1017 // Add virtual address mapping to linked list
1018 void ll_add(struct ll_entry **head,int vaddr,void *addr)
1019 {
1020   struct ll_entry *new_entry;
1021   new_entry=malloc(sizeof(struct ll_entry));
1022   assert(new_entry!=NULL);
1023   new_entry->vaddr=vaddr;
1024   new_entry->reg_sv_flags=0;
1025   new_entry->addr=addr;
1026   new_entry->next=*head;
1027   *head=new_entry;
1028 }
1029
1030 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1031 {
1032   ll_add(head,vaddr,addr);
1033   (*head)->reg_sv_flags=reg_sv_flags;
1034 }
1035
1036 // Check if an address is already compiled
1037 // but don't return addresses which are about to expire from the cache
1038 void *check_addr(u_int vaddr)
1039 {
1040   struct ht_entry *ht_bin = hash_table_get(vaddr);
1041   size_t i;
1042   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1043     if (ht_bin->vaddr[i] == vaddr)
1044       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1045         if (isclean(ht_bin->tcaddr[i]))
1046           return ht_bin->tcaddr[i];
1047   }
1048   u_int page=get_page(vaddr);
1049   struct ll_entry *head;
1050   head=jump_in[page];
1051   while (head != NULL) {
1052     if (head->vaddr == vaddr) {
1053       if (doesnt_expire_soon(head->addr)) {
1054         // Update existing entry with current address
1055         if (ht_bin->vaddr[0] == vaddr) {
1056           ht_bin->tcaddr[0] = head->addr;
1057           return head->addr;
1058         }
1059         if (ht_bin->vaddr[1] == vaddr) {
1060           ht_bin->tcaddr[1] = head->addr;
1061           return head->addr;
1062         }
1063         // Insert into hash table with low priority.
1064         // Don't evict existing entries, as they are probably
1065         // addresses that are being accessed frequently.
1066         if (ht_bin->vaddr[0] == -1) {
1067           ht_bin->vaddr[0] = vaddr;
1068           ht_bin->tcaddr[0] = head->addr;
1069         }
1070         else if (ht_bin->vaddr[1] == -1) {
1071           ht_bin->vaddr[1] = vaddr;
1072           ht_bin->tcaddr[1] = head->addr;
1073         }
1074         return head->addr;
1075       }
1076     }
1077     head=head->next;
1078   }
1079   return 0;
1080 }
1081
1082 void remove_hash(int vaddr)
1083 {
1084   //printf("remove hash: %x\n",vaddr);
1085   struct ht_entry *ht_bin = hash_table_get(vaddr);
1086   if (ht_bin->vaddr[1] == vaddr) {
1087     ht_bin->vaddr[1] = -1;
1088     ht_bin->tcaddr[1] = NULL;
1089   }
1090   if (ht_bin->vaddr[0] == vaddr) {
1091     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1092     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1093     ht_bin->vaddr[1] = -1;
1094     ht_bin->tcaddr[1] = NULL;
1095   }
1096 }
1097
1098 void ll_remove_matching_addrs(struct ll_entry **head,uintptr_t addr,int shift)
1099 {
1100   struct ll_entry *next;
1101   while(*head) {
1102     if(((uintptr_t)((*head)->addr)>>shift)==(addr>>shift) ||
1103        ((uintptr_t)((*head)->addr-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(addr>>shift))
1104     {
1105       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1106       remove_hash((*head)->vaddr);
1107       next=(*head)->next;
1108       free(*head);
1109       *head=next;
1110     }
1111     else
1112     {
1113       head=&((*head)->next);
1114     }
1115   }
1116 }
1117
1118 // Remove all entries from linked list
1119 void ll_clear(struct ll_entry **head)
1120 {
1121   struct ll_entry *cur;
1122   struct ll_entry *next;
1123   if((cur=*head)) {
1124     *head=0;
1125     while(cur) {
1126       next=cur->next;
1127       free(cur);
1128       cur=next;
1129     }
1130   }
1131 }
1132
1133 // Dereference the pointers and remove if it matches
1134 static void ll_kill_pointers(struct ll_entry *head,uintptr_t addr,int shift)
1135 {
1136   while(head) {
1137     uintptr_t ptr = (uintptr_t)get_pointer(head->addr);
1138     inv_debug("EXP: Lookup pointer to %lx at %p (%x)\n",(long)ptr,head->addr,head->vaddr);
1139     if(((ptr>>shift)==(addr>>shift)) ||
1140        (((ptr-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(addr>>shift)))
1141     {
1142       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1143       void *host_addr=find_extjump_insn(head->addr);
1144       mark_clear_cache(host_addr);
1145       set_jump_target(host_addr, head->addr);
1146     }
1147     head=head->next;
1148   }
1149 }
1150
1151 // This is called when we write to a compiled block (see do_invstub)
1152 static void invalidate_page(u_int page)
1153 {
1154   struct ll_entry *head;
1155   struct ll_entry *next;
1156   head=jump_in[page];
1157   jump_in[page]=0;
1158   while(head!=NULL) {
1159     inv_debug("INVALIDATE: %x\n",head->vaddr);
1160     remove_hash(head->vaddr);
1161     next=head->next;
1162     free(head);
1163     head=next;
1164   }
1165   head=jump_out[page];
1166   jump_out[page]=0;
1167   while(head!=NULL) {
1168     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1169     void *host_addr=find_extjump_insn(head->addr);
1170     mark_clear_cache(host_addr);
1171     set_jump_target(host_addr, head->addr);
1172     next=head->next;
1173     free(head);
1174     head=next;
1175   }
1176 }
1177
1178 static void invalidate_block_range(u_int block, u_int first, u_int last)
1179 {
1180   u_int page=get_page(block<<12);
1181   //printf("first=%d last=%d\n",first,last);
1182   invalidate_page(page);
1183   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1184   assert(last<page+5);
1185   // Invalidate the adjacent pages if a block crosses a 4K boundary
1186   while(first<page) {
1187     invalidate_page(first);
1188     first++;
1189   }
1190   for(first=page+1;first<last;first++) {
1191     invalidate_page(first);
1192   }
1193   do_clear_cache();
1194
1195   // Don't trap writes
1196   invalid_code[block]=1;
1197
1198   #ifdef USE_MINI_HT
1199   memset(mini_ht,-1,sizeof(mini_ht));
1200   #endif
1201 }
1202
1203 void invalidate_block(u_int block)
1204 {
1205   u_int page=get_page(block<<12);
1206   u_int vpage=get_vpage(block<<12);
1207   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1208   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1209   u_int first,last;
1210   first=last=page;
1211   struct ll_entry *head;
1212   head=jump_dirty[vpage];
1213   //printf("page=%d vpage=%d\n",page,vpage);
1214   while(head!=NULL) {
1215     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1216       u_char *start, *end;
1217       get_bounds(head->addr, &start, &end);
1218       //printf("start: %p end: %p\n", start, end);
1219       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1220         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1221           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1222           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1223         }
1224       }
1225     }
1226     head=head->next;
1227   }
1228   invalidate_block_range(block,first,last);
1229 }
1230
1231 void invalidate_addr(u_int addr)
1232 {
1233   //static int rhits;
1234   // this check is done by the caller
1235   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1236   u_int page=get_vpage(addr);
1237   if(page<2048) { // RAM
1238     struct ll_entry *head;
1239     u_int addr_min=~0, addr_max=0;
1240     u_int mask=RAM_SIZE-1;
1241     u_int addr_main=0x80000000|(addr&mask);
1242     int pg1;
1243     inv_code_start=addr_main&~0xfff;
1244     inv_code_end=addr_main|0xfff;
1245     pg1=page;
1246     if (pg1>0) {
1247       // must check previous page too because of spans..
1248       pg1--;
1249       inv_code_start-=0x1000;
1250     }
1251     for(;pg1<=page;pg1++) {
1252       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1253         u_char *start_h, *end_h;
1254         u_int start, end;
1255         get_bounds(head->addr, &start_h, &end_h);
1256         start = (uintptr_t)start_h - ram_offset;
1257         end = (uintptr_t)end_h - ram_offset;
1258         if(start<=addr_main&&addr_main<end) {
1259           if(start<addr_min) addr_min=start;
1260           if(end>addr_max) addr_max=end;
1261         }
1262         else if(addr_main<start) {
1263           if(start<inv_code_end)
1264             inv_code_end=start-1;
1265         }
1266         else {
1267           if(end>inv_code_start)
1268             inv_code_start=end;
1269         }
1270       }
1271     }
1272     if (addr_min!=~0) {
1273       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1274       inv_code_start=inv_code_end=~0;
1275       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1276       return;
1277     }
1278     else {
1279       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1280       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1281       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1282       return;
1283     }
1284   }
1285   invalidate_block(addr>>12);
1286 }
1287
1288 // This is called when loading a save state.
1289 // Anything could have changed, so invalidate everything.
1290 void invalidate_all_pages(void)
1291 {
1292   u_int page;
1293   for(page=0;page<4096;page++)
1294     invalidate_page(page);
1295   for(page=0;page<1048576;page++)
1296     if(!invalid_code[page]) {
1297       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1298       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1299     }
1300   #ifdef USE_MINI_HT
1301   memset(mini_ht,-1,sizeof(mini_ht));
1302   #endif
1303   do_clear_cache();
1304 }
1305
1306 static void do_invstub(int n)
1307 {
1308   literal_pool(20);
1309   u_int reglist=stubs[n].a;
1310   set_jump_target(stubs[n].addr, out);
1311   save_regs(reglist);
1312   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1313   emit_far_call(invalidate_addr);
1314   restore_regs(reglist);
1315   emit_jmp(stubs[n].retaddr); // return address
1316 }
1317
1318 // Add an entry to jump_out after making a link
1319 // src should point to code by emit_extjump2()
1320 void add_link(u_int vaddr,void *src)
1321 {
1322   u_int page=get_page(vaddr);
1323   inv_debug("add_link: %p -> %x (%d)\n",src,vaddr,page);
1324   check_extjump2(src);
1325   ll_add(jump_out+page,vaddr,src);
1326   //void *ptr=get_pointer(src);
1327   //inv_debug("add_link: Pointer is to %p\n",ptr);
1328 }
1329
1330 // If a code block was found to be unmodified (bit was set in
1331 // restore_candidate) and it remains unmodified (bit is clear
1332 // in invalid_code) then move the entries for that 4K page from
1333 // the dirty list to the clean list.
1334 void clean_blocks(u_int page)
1335 {
1336   struct ll_entry *head;
1337   inv_debug("INV: clean_blocks page=%d\n",page);
1338   head=jump_dirty[page];
1339   while(head!=NULL) {
1340     if(!invalid_code[head->vaddr>>12]) {
1341       // Don't restore blocks which are about to expire from the cache
1342       if (doesnt_expire_soon(head->addr)) {
1343         if(verify_dirty(head->addr)) {
1344           u_char *start, *end;
1345           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1346           u_int i;
1347           u_int inv=0;
1348           get_bounds(head->addr, &start, &end);
1349           if (start - rdram < RAM_SIZE) {
1350             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1351               inv|=invalid_code[i];
1352             }
1353           }
1354           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1355             inv=1;
1356           }
1357           if(!inv) {
1358             void *clean_addr = get_clean_addr(head->addr);
1359             if (doesnt_expire_soon(clean_addr)) {
1360               u_int ppage=page;
1361               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1362               //printf("page=%x, addr=%x\n",page,head->vaddr);
1363               //assert(head->vaddr>>12==(page|0x80000));
1364               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1365               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1366               if (ht_bin->vaddr[0] == head->vaddr)
1367                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1368               if (ht_bin->vaddr[1] == head->vaddr)
1369                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1370             }
1371           }
1372         }
1373       }
1374     }
1375     head=head->next;
1376   }
1377 }
1378
1379 /* Register allocation */
1380
1381 // Note: registers are allocated clean (unmodified state)
1382 // if you intend to modify the register, you must call dirty_reg().
1383 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1384 {
1385   int r,hr;
1386   int preferred_reg = (reg&7);
1387   if(reg==CCREG) preferred_reg=HOST_CCREG;
1388   if(reg==PTEMP||reg==FTEMP) preferred_reg=12;
1389
1390   // Don't allocate unused registers
1391   if((cur->u>>reg)&1) return;
1392
1393   // see if it's already allocated
1394   for(hr=0;hr<HOST_REGS;hr++)
1395   {
1396     if(cur->regmap[hr]==reg) return;
1397   }
1398
1399   // Keep the same mapping if the register was already allocated in a loop
1400   preferred_reg = loop_reg(i,reg,preferred_reg);
1401
1402   // Try to allocate the preferred register
1403   if(cur->regmap[preferred_reg]==-1) {
1404     cur->regmap[preferred_reg]=reg;
1405     cur->dirty&=~(1<<preferred_reg);
1406     cur->isconst&=~(1<<preferred_reg);
1407     return;
1408   }
1409   r=cur->regmap[preferred_reg];
1410   assert(r < 64);
1411   if((cur->u>>r)&1) {
1412     cur->regmap[preferred_reg]=reg;
1413     cur->dirty&=~(1<<preferred_reg);
1414     cur->isconst&=~(1<<preferred_reg);
1415     return;
1416   }
1417
1418   // Clear any unneeded registers
1419   // We try to keep the mapping consistent, if possible, because it
1420   // makes branches easier (especially loops).  So we try to allocate
1421   // first (see above) before removing old mappings.  If this is not
1422   // possible then go ahead and clear out the registers that are no
1423   // longer needed.
1424   for(hr=0;hr<HOST_REGS;hr++)
1425   {
1426     r=cur->regmap[hr];
1427     if(r>=0) {
1428       assert(r < 64);
1429       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1430     }
1431   }
1432   // Try to allocate any available register, but prefer
1433   // registers that have not been used recently.
1434   if(i>0) {
1435     for(hr=0;hr<HOST_REGS;hr++) {
1436       if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1437         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]) {
1438           cur->regmap[hr]=reg;
1439           cur->dirty&=~(1<<hr);
1440           cur->isconst&=~(1<<hr);
1441           return;
1442         }
1443       }
1444     }
1445   }
1446   // Try to allocate any available register
1447   for(hr=0;hr<HOST_REGS;hr++) {
1448     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1449       cur->regmap[hr]=reg;
1450       cur->dirty&=~(1<<hr);
1451       cur->isconst&=~(1<<hr);
1452       return;
1453     }
1454   }
1455
1456   // Ok, now we have to evict someone
1457   // Pick a register we hopefully won't need soon
1458   u_char hsn[MAXREG+1];
1459   memset(hsn,10,sizeof(hsn));
1460   int j;
1461   lsn(hsn,i,&preferred_reg);
1462   //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]);
1463   //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]);
1464   if(i>0) {
1465     // Don't evict the cycle count at entry points, otherwise the entry
1466     // stub will have to write it.
1467     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1468     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;
1469     for(j=10;j>=3;j--)
1470     {
1471       // Alloc preferred register if available
1472       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1473         for(hr=0;hr<HOST_REGS;hr++) {
1474           // Evict both parts of a 64-bit register
1475           if((cur->regmap[hr]&63)==r) {
1476             cur->regmap[hr]=-1;
1477             cur->dirty&=~(1<<hr);
1478             cur->isconst&=~(1<<hr);
1479           }
1480         }
1481         cur->regmap[preferred_reg]=reg;
1482         return;
1483       }
1484       for(r=1;r<=MAXREG;r++)
1485       {
1486         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1487           for(hr=0;hr<HOST_REGS;hr++) {
1488             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1489               if(cur->regmap[hr]==r) {
1490                 cur->regmap[hr]=reg;
1491                 cur->dirty&=~(1<<hr);
1492                 cur->isconst&=~(1<<hr);
1493                 return;
1494               }
1495             }
1496           }
1497         }
1498       }
1499     }
1500   }
1501   for(j=10;j>=0;j--)
1502   {
1503     for(r=1;r<=MAXREG;r++)
1504     {
1505       if(hsn[r]==j) {
1506         for(hr=0;hr<HOST_REGS;hr++) {
1507           if(cur->regmap[hr]==r) {
1508             cur->regmap[hr]=reg;
1509             cur->dirty&=~(1<<hr);
1510             cur->isconst&=~(1<<hr);
1511             return;
1512           }
1513         }
1514       }
1515     }
1516   }
1517   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1518 }
1519
1520 // Allocate a temporary register.  This is done without regard to
1521 // dirty status or whether the register we request is on the unneeded list
1522 // Note: This will only allocate one register, even if called multiple times
1523 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1524 {
1525   int r,hr;
1526   int preferred_reg = -1;
1527
1528   // see if it's already allocated
1529   for(hr=0;hr<HOST_REGS;hr++)
1530   {
1531     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1532   }
1533
1534   // Try to allocate any available register
1535   for(hr=HOST_REGS-1;hr>=0;hr--) {
1536     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1537       cur->regmap[hr]=reg;
1538       cur->dirty&=~(1<<hr);
1539       cur->isconst&=~(1<<hr);
1540       return;
1541     }
1542   }
1543
1544   // Find an unneeded register
1545   for(hr=HOST_REGS-1;hr>=0;hr--)
1546   {
1547     r=cur->regmap[hr];
1548     if(r>=0) {
1549       assert(r < 64);
1550       if((cur->u>>r)&1) {
1551         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1552           cur->regmap[hr]=reg;
1553           cur->dirty&=~(1<<hr);
1554           cur->isconst&=~(1<<hr);
1555           return;
1556         }
1557       }
1558     }
1559   }
1560
1561   // Ok, now we have to evict someone
1562   // Pick a register we hopefully won't need soon
1563   // TODO: we might want to follow unconditional jumps here
1564   // TODO: get rid of dupe code and make this into a function
1565   u_char hsn[MAXREG+1];
1566   memset(hsn,10,sizeof(hsn));
1567   int j;
1568   lsn(hsn,i,&preferred_reg);
1569   //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]);
1570   if(i>0) {
1571     // Don't evict the cycle count at entry points, otherwise the entry
1572     // stub will have to write it.
1573     if(bt[i]&&hsn[CCREG]>2) hsn[CCREG]=2;
1574     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;
1575     for(j=10;j>=3;j--)
1576     {
1577       for(r=1;r<=MAXREG;r++)
1578       {
1579         if(hsn[r]==j&&r!=rs1[i-1]&&r!=rs2[i-1]&&r!=rt1[i-1]&&r!=rt2[i-1]) {
1580           for(hr=0;hr<HOST_REGS;hr++) {
1581             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1582               if(cur->regmap[hr]==r) {
1583                 cur->regmap[hr]=reg;
1584                 cur->dirty&=~(1<<hr);
1585                 cur->isconst&=~(1<<hr);
1586                 return;
1587               }
1588             }
1589           }
1590         }
1591       }
1592     }
1593   }
1594   for(j=10;j>=0;j--)
1595   {
1596     for(r=1;r<=MAXREG;r++)
1597     {
1598       if(hsn[r]==j) {
1599         for(hr=0;hr<HOST_REGS;hr++) {
1600           if(cur->regmap[hr]==r) {
1601             cur->regmap[hr]=reg;
1602             cur->dirty&=~(1<<hr);
1603             cur->isconst&=~(1<<hr);
1604             return;
1605           }
1606         }
1607       }
1608     }
1609   }
1610   SysPrintf("This shouldn't happen");abort();
1611 }
1612
1613 static void mov_alloc(struct regstat *current,int i)
1614 {
1615   if (rs1[i] == HIREG || rs1[i] == LOREG) {
1616     // logically this is needed but just won't work, no idea why
1617     //alloc_cc(current,i); // for stalls
1618     //dirty_reg(current,CCREG);
1619   }
1620
1621   // Note: Don't need to actually alloc the source registers
1622   //alloc_reg(current,i,rs1[i]);
1623   alloc_reg(current,i,rt1[i]);
1624
1625   clear_const(current,rs1[i]);
1626   clear_const(current,rt1[i]);
1627   dirty_reg(current,rt1[i]);
1628 }
1629
1630 static void shiftimm_alloc(struct regstat *current,int i)
1631 {
1632   if(opcode2[i]<=0x3) // SLL/SRL/SRA
1633   {
1634     if(rt1[i]) {
1635       if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1636       else lt1[i]=rs1[i];
1637       alloc_reg(current,i,rt1[i]);
1638       dirty_reg(current,rt1[i]);
1639       if(is_const(current,rs1[i])) {
1640         int v=get_const(current,rs1[i]);
1641         if(opcode2[i]==0x00) set_const(current,rt1[i],v<<imm[i]);
1642         if(opcode2[i]==0x02) set_const(current,rt1[i],(u_int)v>>imm[i]);
1643         if(opcode2[i]==0x03) set_const(current,rt1[i],v>>imm[i]);
1644       }
1645       else clear_const(current,rt1[i]);
1646     }
1647   }
1648   else
1649   {
1650     clear_const(current,rs1[i]);
1651     clear_const(current,rt1[i]);
1652   }
1653
1654   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
1655   {
1656     assert(0);
1657   }
1658   if(opcode2[i]==0x3c) // DSLL32
1659   {
1660     assert(0);
1661   }
1662   if(opcode2[i]==0x3e) // DSRL32
1663   {
1664     assert(0);
1665   }
1666   if(opcode2[i]==0x3f) // DSRA32
1667   {
1668     assert(0);
1669   }
1670 }
1671
1672 static void shift_alloc(struct regstat *current,int i)
1673 {
1674   if(rt1[i]) {
1675     if(opcode2[i]<=0x07) // SLLV/SRLV/SRAV
1676     {
1677       if(rs1[i]) alloc_reg(current,i,rs1[i]);
1678       if(rs2[i]) alloc_reg(current,i,rs2[i]);
1679       alloc_reg(current,i,rt1[i]);
1680       if(rt1[i]==rs2[i]) {
1681         alloc_reg_temp(current,i,-1);
1682         minimum_free_regs[i]=1;
1683       }
1684     } else { // DSLLV/DSRLV/DSRAV
1685       assert(0);
1686     }
1687     clear_const(current,rs1[i]);
1688     clear_const(current,rs2[i]);
1689     clear_const(current,rt1[i]);
1690     dirty_reg(current,rt1[i]);
1691   }
1692 }
1693
1694 static void alu_alloc(struct regstat *current,int i)
1695 {
1696   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
1697     if(rt1[i]) {
1698       if(rs1[i]&&rs2[i]) {
1699         alloc_reg(current,i,rs1[i]);
1700         alloc_reg(current,i,rs2[i]);
1701       }
1702       else {
1703         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1704         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1705       }
1706       alloc_reg(current,i,rt1[i]);
1707     }
1708   }
1709   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
1710     if(rt1[i]) {
1711       alloc_reg(current,i,rs1[i]);
1712       alloc_reg(current,i,rs2[i]);
1713       alloc_reg(current,i,rt1[i]);
1714     }
1715   }
1716   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
1717     if(rt1[i]) {
1718       if(rs1[i]&&rs2[i]) {
1719         alloc_reg(current,i,rs1[i]);
1720         alloc_reg(current,i,rs2[i]);
1721       }
1722       else
1723       {
1724         if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1725         if(rs2[i]&&needed_again(rs2[i],i)) alloc_reg(current,i,rs2[i]);
1726       }
1727       alloc_reg(current,i,rt1[i]);
1728     }
1729   }
1730   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1731     assert(0);
1732   }
1733   clear_const(current,rs1[i]);
1734   clear_const(current,rs2[i]);
1735   clear_const(current,rt1[i]);
1736   dirty_reg(current,rt1[i]);
1737 }
1738
1739 static void imm16_alloc(struct regstat *current,int i)
1740 {
1741   if(rs1[i]&&needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1742   else lt1[i]=rs1[i];
1743   if(rt1[i]) alloc_reg(current,i,rt1[i]);
1744   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
1745     assert(0);
1746   }
1747   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
1748     clear_const(current,rs1[i]);
1749     clear_const(current,rt1[i]);
1750   }
1751   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
1752     if(is_const(current,rs1[i])) {
1753       int v=get_const(current,rs1[i]);
1754       if(opcode[i]==0x0c) set_const(current,rt1[i],v&imm[i]);
1755       if(opcode[i]==0x0d) set_const(current,rt1[i],v|imm[i]);
1756       if(opcode[i]==0x0e) set_const(current,rt1[i],v^imm[i]);
1757     }
1758     else clear_const(current,rt1[i]);
1759   }
1760   else if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
1761     if(is_const(current,rs1[i])) {
1762       int v=get_const(current,rs1[i]);
1763       set_const(current,rt1[i],v+imm[i]);
1764     }
1765     else clear_const(current,rt1[i]);
1766   }
1767   else {
1768     set_const(current,rt1[i],imm[i]<<16); // LUI
1769   }
1770   dirty_reg(current,rt1[i]);
1771 }
1772
1773 static void load_alloc(struct regstat *current,int i)
1774 {
1775   clear_const(current,rt1[i]);
1776   //if(rs1[i]!=rt1[i]&&needed_again(rs1[i],i)) clear_const(current,rs1[i]); // Does this help or hurt?
1777   if(!rs1[i]) current->u&=~1LL; // Allow allocating r0 if it's the source register
1778   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1779   if(rt1[i]&&!((current->u>>rt1[i])&1)) {
1780     alloc_reg(current,i,rt1[i]);
1781     assert(get_reg(current->regmap,rt1[i])>=0);
1782     if(opcode[i]==0x27||opcode[i]==0x37) // LWU/LD
1783     {
1784       assert(0);
1785     }
1786     else if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1787     {
1788       assert(0);
1789     }
1790     dirty_reg(current,rt1[i]);
1791     // LWL/LWR need a temporary register for the old value
1792     if(opcode[i]==0x22||opcode[i]==0x26)
1793     {
1794       alloc_reg(current,i,FTEMP);
1795       alloc_reg_temp(current,i,-1);
1796       minimum_free_regs[i]=1;
1797     }
1798   }
1799   else
1800   {
1801     // Load to r0 or unneeded register (dummy load)
1802     // but we still need a register to calculate the address
1803     if(opcode[i]==0x22||opcode[i]==0x26)
1804     {
1805       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1806     }
1807     alloc_reg_temp(current,i,-1);
1808     minimum_free_regs[i]=1;
1809     if(opcode[i]==0x1A||opcode[i]==0x1B) // LDL/LDR
1810     {
1811       assert(0);
1812     }
1813   }
1814 }
1815
1816 void store_alloc(struct regstat *current,int i)
1817 {
1818   clear_const(current,rs2[i]);
1819   if(!(rs2[i])) current->u&=~1LL; // Allow allocating r0 if necessary
1820   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1821   alloc_reg(current,i,rs2[i]);
1822   if(opcode[i]==0x2c||opcode[i]==0x2d||opcode[i]==0x3f) { // 64-bit SDL/SDR/SD
1823     assert(0);
1824   }
1825   #if defined(HOST_IMM8)
1826   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1827   else alloc_reg(current,i,INVCP);
1828   #endif
1829   if(opcode[i]==0x2a||opcode[i]==0x2e||opcode[i]==0x2c||opcode[i]==0x2d) { // SWL/SWL/SDL/SDR
1830     alloc_reg(current,i,FTEMP);
1831   }
1832   // We need a temporary register for address generation
1833   alloc_reg_temp(current,i,-1);
1834   minimum_free_regs[i]=1;
1835 }
1836
1837 void c1ls_alloc(struct regstat *current,int i)
1838 {
1839   //clear_const(current,rs1[i]); // FIXME
1840   clear_const(current,rt1[i]);
1841   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1842   alloc_reg(current,i,CSREG); // Status
1843   alloc_reg(current,i,FTEMP);
1844   if(opcode[i]==0x35||opcode[i]==0x3d) { // 64-bit LDC1/SDC1
1845     assert(0);
1846   }
1847   #if defined(HOST_IMM8)
1848   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1849   else if((opcode[i]&0x3b)==0x39) // SWC1/SDC1
1850     alloc_reg(current,i,INVCP);
1851   #endif
1852   // We need a temporary register for address generation
1853   alloc_reg_temp(current,i,-1);
1854 }
1855
1856 void c2ls_alloc(struct regstat *current,int i)
1857 {
1858   clear_const(current,rt1[i]);
1859   if(needed_again(rs1[i],i)) alloc_reg(current,i,rs1[i]);
1860   alloc_reg(current,i,FTEMP);
1861   #if defined(HOST_IMM8)
1862   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1863   if((opcode[i]&0x3b)==0x3a) // SWC2/SDC2
1864     alloc_reg(current,i,INVCP);
1865   #endif
1866   // We need a temporary register for address generation
1867   alloc_reg_temp(current,i,-1);
1868   minimum_free_regs[i]=1;
1869 }
1870
1871 #ifndef multdiv_alloc
1872 void multdiv_alloc(struct regstat *current,int i)
1873 {
1874   //  case 0x18: MULT
1875   //  case 0x19: MULTU
1876   //  case 0x1A: DIV
1877   //  case 0x1B: DIVU
1878   //  case 0x1C: DMULT
1879   //  case 0x1D: DMULTU
1880   //  case 0x1E: DDIV
1881   //  case 0x1F: DDIVU
1882   clear_const(current,rs1[i]);
1883   clear_const(current,rs2[i]);
1884   alloc_cc(current,i); // for stalls
1885   if(rs1[i]&&rs2[i])
1886   {
1887     if((opcode2[i]&4)==0) // 32-bit
1888     {
1889       current->u&=~(1LL<<HIREG);
1890       current->u&=~(1LL<<LOREG);
1891       alloc_reg(current,i,HIREG);
1892       alloc_reg(current,i,LOREG);
1893       alloc_reg(current,i,rs1[i]);
1894       alloc_reg(current,i,rs2[i]);
1895       dirty_reg(current,HIREG);
1896       dirty_reg(current,LOREG);
1897     }
1898     else // 64-bit
1899     {
1900       assert(0);
1901     }
1902   }
1903   else
1904   {
1905     // Multiply by zero is zero.
1906     // MIPS does not have a divide by zero exception.
1907     // The result is undefined, we return zero.
1908     alloc_reg(current,i,HIREG);
1909     alloc_reg(current,i,LOREG);
1910     dirty_reg(current,HIREG);
1911     dirty_reg(current,LOREG);
1912   }
1913 }
1914 #endif
1915
1916 void cop0_alloc(struct regstat *current,int i)
1917 {
1918   if(opcode2[i]==0) // MFC0
1919   {
1920     if(rt1[i]) {
1921       clear_const(current,rt1[i]);
1922       alloc_all(current,i);
1923       alloc_reg(current,i,rt1[i]);
1924       dirty_reg(current,rt1[i]);
1925     }
1926   }
1927   else if(opcode2[i]==4) // MTC0
1928   {
1929     if(rs1[i]){
1930       clear_const(current,rs1[i]);
1931       alloc_reg(current,i,rs1[i]);
1932       alloc_all(current,i);
1933     }
1934     else {
1935       alloc_all(current,i); // FIXME: Keep r0
1936       current->u&=~1LL;
1937       alloc_reg(current,i,0);
1938     }
1939   }
1940   else
1941   {
1942     // TLBR/TLBWI/TLBWR/TLBP/ERET
1943     assert(opcode2[i]==0x10);
1944     alloc_all(current,i);
1945   }
1946   minimum_free_regs[i]=HOST_REGS;
1947 }
1948
1949 static void cop2_alloc(struct regstat *current,int i)
1950 {
1951   if (opcode2[i] < 3) // MFC2/CFC2
1952   {
1953     alloc_cc(current,i); // for stalls
1954     dirty_reg(current,CCREG);
1955     if(rt1[i]){
1956       clear_const(current,rt1[i]);
1957       alloc_reg(current,i,rt1[i]);
1958       dirty_reg(current,rt1[i]);
1959     }
1960   }
1961   else if (opcode2[i] > 3) // MTC2/CTC2
1962   {
1963     if(rs1[i]){
1964       clear_const(current,rs1[i]);
1965       alloc_reg(current,i,rs1[i]);
1966     }
1967     else {
1968       current->u&=~1LL;
1969       alloc_reg(current,i,0);
1970     }
1971   }
1972   alloc_reg_temp(current,i,-1);
1973   minimum_free_regs[i]=1;
1974 }
1975
1976 void c2op_alloc(struct regstat *current,int i)
1977 {
1978   alloc_cc(current,i); // for stalls
1979   dirty_reg(current,CCREG);
1980   alloc_reg_temp(current,i,-1);
1981 }
1982
1983 void syscall_alloc(struct regstat *current,int i)
1984 {
1985   alloc_cc(current,i);
1986   dirty_reg(current,CCREG);
1987   alloc_all(current,i);
1988   minimum_free_regs[i]=HOST_REGS;
1989   current->isconst=0;
1990 }
1991
1992 void delayslot_alloc(struct regstat *current,int i)
1993 {
1994   switch(itype[i]) {
1995     case UJUMP:
1996     case CJUMP:
1997     case SJUMP:
1998     case RJUMP:
1999     case SYSCALL:
2000     case HLECALL:
2001     case SPAN:
2002       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
2003       SysPrintf("Disabled speculative precompilation\n");
2004       stop_after_jal=1;
2005       break;
2006     case IMM16:
2007       imm16_alloc(current,i);
2008       break;
2009     case LOAD:
2010     case LOADLR:
2011       load_alloc(current,i);
2012       break;
2013     case STORE:
2014     case STORELR:
2015       store_alloc(current,i);
2016       break;
2017     case ALU:
2018       alu_alloc(current,i);
2019       break;
2020     case SHIFT:
2021       shift_alloc(current,i);
2022       break;
2023     case MULTDIV:
2024       multdiv_alloc(current,i);
2025       break;
2026     case SHIFTIMM:
2027       shiftimm_alloc(current,i);
2028       break;
2029     case MOV:
2030       mov_alloc(current,i);
2031       break;
2032     case COP0:
2033       cop0_alloc(current,i);
2034       break;
2035     case COP1:
2036       break;
2037     case COP2:
2038       cop2_alloc(current,i);
2039       break;
2040     case C1LS:
2041       c1ls_alloc(current,i);
2042       break;
2043     case C2LS:
2044       c2ls_alloc(current,i);
2045       break;
2046     case C2OP:
2047       c2op_alloc(current,i);
2048       break;
2049   }
2050 }
2051
2052 // Special case where a branch and delay slot span two pages in virtual memory
2053 static void pagespan_alloc(struct regstat *current,int i)
2054 {
2055   current->isconst=0;
2056   current->wasconst=0;
2057   regs[i].wasconst=0;
2058   minimum_free_regs[i]=HOST_REGS;
2059   alloc_all(current,i);
2060   alloc_cc(current,i);
2061   dirty_reg(current,CCREG);
2062   if(opcode[i]==3) // JAL
2063   {
2064     alloc_reg(current,i,31);
2065     dirty_reg(current,31);
2066   }
2067   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
2068   {
2069     alloc_reg(current,i,rs1[i]);
2070     if (rt1[i]!=0) {
2071       alloc_reg(current,i,rt1[i]);
2072       dirty_reg(current,rt1[i]);
2073     }
2074   }
2075   if((opcode[i]&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2076   {
2077     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2078     if(rs2[i]) alloc_reg(current,i,rs2[i]);
2079   }
2080   else
2081   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2082   {
2083     if(rs1[i]) alloc_reg(current,i,rs1[i]);
2084   }
2085   //else ...
2086 }
2087
2088 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2089   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2090 {
2091   assert(stubcount < ARRAY_SIZE(stubs));
2092   stubs[stubcount].type = type;
2093   stubs[stubcount].addr = addr;
2094   stubs[stubcount].retaddr = retaddr;
2095   stubs[stubcount].a = a;
2096   stubs[stubcount].b = b;
2097   stubs[stubcount].c = c;
2098   stubs[stubcount].d = d;
2099   stubs[stubcount].e = e;
2100   stubcount++;
2101 }
2102
2103 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2104   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2105 {
2106   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2107 }
2108
2109 // Write out a single register
2110 static void wb_register(signed char r,signed char regmap[],uint64_t dirty)
2111 {
2112   int hr;
2113   for(hr=0;hr<HOST_REGS;hr++) {
2114     if(hr!=EXCLUDE_REG) {
2115       if((regmap[hr]&63)==r) {
2116         if((dirty>>hr)&1) {
2117           assert(regmap[hr]<64);
2118           emit_storereg(r,hr);
2119         }
2120       }
2121     }
2122   }
2123 }
2124
2125 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2126 {
2127   //if(dirty_pre==dirty) return;
2128   int hr,reg;
2129   for(hr=0;hr<HOST_REGS;hr++) {
2130     if(hr!=EXCLUDE_REG) {
2131       reg=pre[hr];
2132       if(((~u)>>(reg&63))&1) {
2133         if(reg>0) {
2134           if(((dirty_pre&~dirty)>>hr)&1) {
2135             if(reg>0&&reg<34) {
2136               emit_storereg(reg,hr);
2137             }
2138             else if(reg>=64) {
2139               assert(0);
2140             }
2141           }
2142         }
2143       }
2144     }
2145   }
2146 }
2147
2148 // trashes r2
2149 static void pass_args(int a0, int a1)
2150 {
2151   if(a0==1&&a1==0) {
2152     // must swap
2153     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2154   }
2155   else if(a0!=0&&a1==0) {
2156     emit_mov(a1,1);
2157     if (a0>=0) emit_mov(a0,0);
2158   }
2159   else {
2160     if(a0>=0&&a0!=0) emit_mov(a0,0);
2161     if(a1>=0&&a1!=1) emit_mov(a1,1);
2162   }
2163 }
2164
2165 static void alu_assemble(int i,struct regstat *i_regs)
2166 {
2167   if(opcode2[i]>=0x20&&opcode2[i]<=0x23) { // ADD/ADDU/SUB/SUBU
2168     if(rt1[i]) {
2169       signed char s1,s2,t;
2170       t=get_reg(i_regs->regmap,rt1[i]);
2171       if(t>=0) {
2172         s1=get_reg(i_regs->regmap,rs1[i]);
2173         s2=get_reg(i_regs->regmap,rs2[i]);
2174         if(rs1[i]&&rs2[i]) {
2175           assert(s1>=0);
2176           assert(s2>=0);
2177           if(opcode2[i]&2) emit_sub(s1,s2,t);
2178           else emit_add(s1,s2,t);
2179         }
2180         else if(rs1[i]) {
2181           if(s1>=0) emit_mov(s1,t);
2182           else emit_loadreg(rs1[i],t);
2183         }
2184         else if(rs2[i]) {
2185           if(s2>=0) {
2186             if(opcode2[i]&2) emit_neg(s2,t);
2187             else emit_mov(s2,t);
2188           }
2189           else {
2190             emit_loadreg(rs2[i],t);
2191             if(opcode2[i]&2) emit_neg(t,t);
2192           }
2193         }
2194         else emit_zeroreg(t);
2195       }
2196     }
2197   }
2198   if(opcode2[i]>=0x2c&&opcode2[i]<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2199     assert(0);
2200   }
2201   if(opcode2[i]==0x2a||opcode2[i]==0x2b) { // SLT/SLTU
2202     if(rt1[i]) {
2203       signed char s1l,s2l,t;
2204       {
2205         t=get_reg(i_regs->regmap,rt1[i]);
2206         //assert(t>=0);
2207         if(t>=0) {
2208           s1l=get_reg(i_regs->regmap,rs1[i]);
2209           s2l=get_reg(i_regs->regmap,rs2[i]);
2210           if(rs2[i]==0) // rx<r0
2211           {
2212             if(opcode2[i]==0x2a&&rs1[i]!=0) { // SLT
2213               assert(s1l>=0);
2214               emit_shrimm(s1l,31,t);
2215             }
2216             else // SLTU (unsigned can not be less than zero, 0<0)
2217               emit_zeroreg(t);
2218           }
2219           else if(rs1[i]==0) // r0<rx
2220           {
2221             assert(s2l>=0);
2222             if(opcode2[i]==0x2a) // SLT
2223               emit_set_gz32(s2l,t);
2224             else // SLTU (set if not zero)
2225               emit_set_nz32(s2l,t);
2226           }
2227           else{
2228             assert(s1l>=0);assert(s2l>=0);
2229             if(opcode2[i]==0x2a) // SLT
2230               emit_set_if_less32(s1l,s2l,t);
2231             else // SLTU
2232               emit_set_if_carry32(s1l,s2l,t);
2233           }
2234         }
2235       }
2236     }
2237   }
2238   if(opcode2[i]>=0x24&&opcode2[i]<=0x27) { // AND/OR/XOR/NOR
2239     if(rt1[i]) {
2240       signed char s1l,s2l,tl;
2241       tl=get_reg(i_regs->regmap,rt1[i]);
2242       {
2243         if(tl>=0) {
2244           s1l=get_reg(i_regs->regmap,rs1[i]);
2245           s2l=get_reg(i_regs->regmap,rs2[i]);
2246           if(rs1[i]&&rs2[i]) {
2247             assert(s1l>=0);
2248             assert(s2l>=0);
2249             if(opcode2[i]==0x24) { // AND
2250               emit_and(s1l,s2l,tl);
2251             } else
2252             if(opcode2[i]==0x25) { // OR
2253               emit_or(s1l,s2l,tl);
2254             } else
2255             if(opcode2[i]==0x26) { // XOR
2256               emit_xor(s1l,s2l,tl);
2257             } else
2258             if(opcode2[i]==0x27) { // NOR
2259               emit_or(s1l,s2l,tl);
2260               emit_not(tl,tl);
2261             }
2262           }
2263           else
2264           {
2265             if(opcode2[i]==0x24) { // AND
2266               emit_zeroreg(tl);
2267             } else
2268             if(opcode2[i]==0x25||opcode2[i]==0x26) { // OR/XOR
2269               if(rs1[i]){
2270                 if(s1l>=0) emit_mov(s1l,tl);
2271                 else emit_loadreg(rs1[i],tl); // CHECK: regmap_entry?
2272               }
2273               else
2274               if(rs2[i]){
2275                 if(s2l>=0) emit_mov(s2l,tl);
2276                 else emit_loadreg(rs2[i],tl); // CHECK: regmap_entry?
2277               }
2278               else emit_zeroreg(tl);
2279             } else
2280             if(opcode2[i]==0x27) { // NOR
2281               if(rs1[i]){
2282                 if(s1l>=0) emit_not(s1l,tl);
2283                 else {
2284                   emit_loadreg(rs1[i],tl);
2285                   emit_not(tl,tl);
2286                 }
2287               }
2288               else
2289               if(rs2[i]){
2290                 if(s2l>=0) emit_not(s2l,tl);
2291                 else {
2292                   emit_loadreg(rs2[i],tl);
2293                   emit_not(tl,tl);
2294                 }
2295               }
2296               else emit_movimm(-1,tl);
2297             }
2298           }
2299         }
2300       }
2301     }
2302   }
2303 }
2304
2305 void imm16_assemble(int i,struct regstat *i_regs)
2306 {
2307   if (opcode[i]==0x0f) { // LUI
2308     if(rt1[i]) {
2309       signed char t;
2310       t=get_reg(i_regs->regmap,rt1[i]);
2311       //assert(t>=0);
2312       if(t>=0) {
2313         if(!((i_regs->isconst>>t)&1))
2314           emit_movimm(imm[i]<<16,t);
2315       }
2316     }
2317   }
2318   if(opcode[i]==0x08||opcode[i]==0x09) { // ADDI/ADDIU
2319     if(rt1[i]) {
2320       signed char s,t;
2321       t=get_reg(i_regs->regmap,rt1[i]);
2322       s=get_reg(i_regs->regmap,rs1[i]);
2323       if(rs1[i]) {
2324         //assert(t>=0);
2325         //assert(s>=0);
2326         if(t>=0) {
2327           if(!((i_regs->isconst>>t)&1)) {
2328             if(s<0) {
2329               if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2330               emit_addimm(t,imm[i],t);
2331             }else{
2332               if(!((i_regs->wasconst>>s)&1))
2333                 emit_addimm(s,imm[i],t);
2334               else
2335                 emit_movimm(constmap[i][s]+imm[i],t);
2336             }
2337           }
2338         }
2339       } else {
2340         if(t>=0) {
2341           if(!((i_regs->isconst>>t)&1))
2342             emit_movimm(imm[i],t);
2343         }
2344       }
2345     }
2346   }
2347   if(opcode[i]==0x18||opcode[i]==0x19) { // DADDI/DADDIU
2348     if(rt1[i]) {
2349       signed char sl,tl;
2350       tl=get_reg(i_regs->regmap,rt1[i]);
2351       sl=get_reg(i_regs->regmap,rs1[i]);
2352       if(tl>=0) {
2353         if(rs1[i]) {
2354           assert(sl>=0);
2355           emit_addimm(sl,imm[i],tl);
2356         } else {
2357           emit_movimm(imm[i],tl);
2358         }
2359       }
2360     }
2361   }
2362   else if(opcode[i]==0x0a||opcode[i]==0x0b) { // SLTI/SLTIU
2363     if(rt1[i]) {
2364       //assert(rs1[i]!=0); // r0 might be valid, but it's probably a bug
2365       signed char sl,t;
2366       t=get_reg(i_regs->regmap,rt1[i]);
2367       sl=get_reg(i_regs->regmap,rs1[i]);
2368       //assert(t>=0);
2369       if(t>=0) {
2370         if(rs1[i]>0) {
2371             if(opcode[i]==0x0a) { // SLTI
2372               if(sl<0) {
2373                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2374                 emit_slti32(t,imm[i],t);
2375               }else{
2376                 emit_slti32(sl,imm[i],t);
2377               }
2378             }
2379             else { // SLTIU
2380               if(sl<0) {
2381                 if(i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2382                 emit_sltiu32(t,imm[i],t);
2383               }else{
2384                 emit_sltiu32(sl,imm[i],t);
2385               }
2386             }
2387         }else{
2388           // SLTI(U) with r0 is just stupid,
2389           // nonetheless examples can be found
2390           if(opcode[i]==0x0a) // SLTI
2391             if(0<imm[i]) emit_movimm(1,t);
2392             else emit_zeroreg(t);
2393           else // SLTIU
2394           {
2395             if(imm[i]) emit_movimm(1,t);
2396             else emit_zeroreg(t);
2397           }
2398         }
2399       }
2400     }
2401   }
2402   else if(opcode[i]>=0x0c&&opcode[i]<=0x0e) { // ANDI/ORI/XORI
2403     if(rt1[i]) {
2404       signed char sl,tl;
2405       tl=get_reg(i_regs->regmap,rt1[i]);
2406       sl=get_reg(i_regs->regmap,rs1[i]);
2407       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2408         if(opcode[i]==0x0c) //ANDI
2409         {
2410           if(rs1[i]) {
2411             if(sl<0) {
2412               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2413               emit_andimm(tl,imm[i],tl);
2414             }else{
2415               if(!((i_regs->wasconst>>sl)&1))
2416                 emit_andimm(sl,imm[i],tl);
2417               else
2418                 emit_movimm(constmap[i][sl]&imm[i],tl);
2419             }
2420           }
2421           else
2422             emit_zeroreg(tl);
2423         }
2424         else
2425         {
2426           if(rs1[i]) {
2427             if(sl<0) {
2428               if(i_regs->regmap_entry[tl]!=rs1[i]) emit_loadreg(rs1[i],tl);
2429             }
2430             if(opcode[i]==0x0d) { // ORI
2431               if(sl<0) {
2432                 emit_orimm(tl,imm[i],tl);
2433               }else{
2434                 if(!((i_regs->wasconst>>sl)&1))
2435                   emit_orimm(sl,imm[i],tl);
2436                 else
2437                   emit_movimm(constmap[i][sl]|imm[i],tl);
2438               }
2439             }
2440             if(opcode[i]==0x0e) { // XORI
2441               if(sl<0) {
2442                 emit_xorimm(tl,imm[i],tl);
2443               }else{
2444                 if(!((i_regs->wasconst>>sl)&1))
2445                   emit_xorimm(sl,imm[i],tl);
2446                 else
2447                   emit_movimm(constmap[i][sl]^imm[i],tl);
2448               }
2449             }
2450           }
2451           else {
2452             emit_movimm(imm[i],tl);
2453           }
2454         }
2455       }
2456     }
2457   }
2458 }
2459
2460 void shiftimm_assemble(int i,struct regstat *i_regs)
2461 {
2462   if(opcode2[i]<=0x3) // SLL/SRL/SRA
2463   {
2464     if(rt1[i]) {
2465       signed char s,t;
2466       t=get_reg(i_regs->regmap,rt1[i]);
2467       s=get_reg(i_regs->regmap,rs1[i]);
2468       //assert(t>=0);
2469       if(t>=0&&!((i_regs->isconst>>t)&1)){
2470         if(rs1[i]==0)
2471         {
2472           emit_zeroreg(t);
2473         }
2474         else
2475         {
2476           if(s<0&&i_regs->regmap_entry[t]!=rs1[i]) emit_loadreg(rs1[i],t);
2477           if(imm[i]) {
2478             if(opcode2[i]==0) // SLL
2479             {
2480               emit_shlimm(s<0?t:s,imm[i],t);
2481             }
2482             if(opcode2[i]==2) // SRL
2483             {
2484               emit_shrimm(s<0?t:s,imm[i],t);
2485             }
2486             if(opcode2[i]==3) // SRA
2487             {
2488               emit_sarimm(s<0?t:s,imm[i],t);
2489             }
2490           }else{
2491             // Shift by zero
2492             if(s>=0 && s!=t) emit_mov(s,t);
2493           }
2494         }
2495       }
2496       //emit_storereg(rt1[i],t); //DEBUG
2497     }
2498   }
2499   if(opcode2[i]>=0x38&&opcode2[i]<=0x3b) // DSLL/DSRL/DSRA
2500   {
2501     assert(0);
2502   }
2503   if(opcode2[i]==0x3c) // DSLL32
2504   {
2505     assert(0);
2506   }
2507   if(opcode2[i]==0x3e) // DSRL32
2508   {
2509     assert(0);
2510   }
2511   if(opcode2[i]==0x3f) // DSRA32
2512   {
2513     assert(0);
2514   }
2515 }
2516
2517 #ifndef shift_assemble
2518 static void shift_assemble(int i,struct regstat *i_regs)
2519 {
2520   signed char s,t,shift;
2521   if (rt1[i] == 0)
2522     return;
2523   assert(opcode2[i]<=0x07); // SLLV/SRLV/SRAV
2524   t = get_reg(i_regs->regmap, rt1[i]);
2525   s = get_reg(i_regs->regmap, rs1[i]);
2526   shift = get_reg(i_regs->regmap, rs2[i]);
2527   if (t < 0)
2528     return;
2529
2530   if(rs1[i]==0)
2531     emit_zeroreg(t);
2532   else if(rs2[i]==0) {
2533     assert(s>=0);
2534     if(s!=t) emit_mov(s,t);
2535   }
2536   else {
2537     host_tempreg_acquire();
2538     emit_andimm(shift,31,HOST_TEMPREG);
2539     switch(opcode2[i]) {
2540     case 4: // SLLV
2541       emit_shl(s,HOST_TEMPREG,t);
2542       break;
2543     case 6: // SRLV
2544       emit_shr(s,HOST_TEMPREG,t);
2545       break;
2546     case 7: // SRAV
2547       emit_sar(s,HOST_TEMPREG,t);
2548       break;
2549     default:
2550       assert(0);
2551     }
2552     host_tempreg_release();
2553   }
2554 }
2555
2556 #endif
2557
2558 enum {
2559   MTYPE_8000 = 0,
2560   MTYPE_8020,
2561   MTYPE_0000,
2562   MTYPE_A000,
2563   MTYPE_1F80,
2564 };
2565
2566 static int get_ptr_mem_type(u_int a)
2567 {
2568   if(a < 0x00200000) {
2569     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2570       // return wrong, must use memhandler for BIOS self-test to pass
2571       // 007 does similar stuff from a00 mirror, weird stuff
2572       return MTYPE_8000;
2573     return MTYPE_0000;
2574   }
2575   if(0x1f800000 <= a && a < 0x1f801000)
2576     return MTYPE_1F80;
2577   if(0x80200000 <= a && a < 0x80800000)
2578     return MTYPE_8020;
2579   if(0xa0000000 <= a && a < 0xa0200000)
2580     return MTYPE_A000;
2581   return MTYPE_8000;
2582 }
2583
2584 static void *emit_fastpath_cmp_jump(int i,int addr,int *addr_reg_override)
2585 {
2586   void *jaddr = NULL;
2587   int type=0;
2588   int mr=rs1[i];
2589   if(((smrv_strong|smrv_weak)>>mr)&1) {
2590     type=get_ptr_mem_type(smrv[mr]);
2591     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2592   }
2593   else {
2594     // use the mirror we are running on
2595     type=get_ptr_mem_type(start);
2596     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2597   }
2598
2599   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2600     host_tempreg_acquire();
2601     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2602     addr=*addr_reg_override=HOST_TEMPREG;
2603     type=0;
2604   }
2605   else if(type==MTYPE_0000) { // RAM 0 mirror
2606     host_tempreg_acquire();
2607     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2608     addr=*addr_reg_override=HOST_TEMPREG;
2609     type=0;
2610   }
2611   else if(type==MTYPE_A000) { // RAM A mirror
2612     host_tempreg_acquire();
2613     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2614     addr=*addr_reg_override=HOST_TEMPREG;
2615     type=0;
2616   }
2617   else if(type==MTYPE_1F80) { // scratchpad
2618     if (psxH == (void *)0x1f800000) {
2619       host_tempreg_acquire();
2620       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2621       emit_cmpimm(HOST_TEMPREG,0x1000);
2622       host_tempreg_release();
2623       jaddr=out;
2624       emit_jc(0);
2625     }
2626     else {
2627       // do the usual RAM check, jump will go to the right handler
2628       type=0;
2629     }
2630   }
2631
2632   if(type==0)
2633   {
2634     emit_cmpimm(addr,RAM_SIZE);
2635     jaddr=out;
2636     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2637     // Hint to branch predictor that the branch is unlikely to be taken
2638     if(rs1[i]>=28)
2639       emit_jno_unlikely(0);
2640     else
2641     #endif
2642       emit_jno(0);
2643     if(ram_offset!=0) {
2644       host_tempreg_acquire();
2645       emit_addimm(addr,ram_offset,HOST_TEMPREG);
2646       addr=*addr_reg_override=HOST_TEMPREG;
2647     }
2648   }
2649
2650   return jaddr;
2651 }
2652
2653 // return memhandler, or get directly accessable address and return 0
2654 static void *get_direct_memhandler(void *table, u_int addr,
2655   enum stub_type type, uintptr_t *addr_host)
2656 {
2657   uintptr_t l1, l2 = 0;
2658   l1 = ((uintptr_t *)table)[addr>>12];
2659   if ((l1 & (1ul << (sizeof(l1)*8-1))) == 0) {
2660     uintptr_t v = l1 << 1;
2661     *addr_host = v + addr;
2662     return NULL;
2663   }
2664   else {
2665     l1 <<= 1;
2666     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2667       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2668     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2669       l2=((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2670     else
2671       l2=((uintptr_t *)l1)[(addr&0xfff)/4];
2672     if ((l2 & (1<<31)) == 0) {
2673       uintptr_t v = l2 << 1;
2674       *addr_host = v + (addr&0xfff);
2675       return NULL;
2676     }
2677     return (void *)(l2 << 1);
2678   }
2679 }
2680
2681 static u_int get_host_reglist(const signed char *regmap)
2682 {
2683   u_int reglist = 0, hr;
2684   for (hr = 0; hr < HOST_REGS; hr++) {
2685     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2686       reglist |= 1 << hr;
2687   }
2688   return reglist;
2689 }
2690
2691 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2692 {
2693   if (r1 >= 0)
2694     reglist &= ~(1u << r1);
2695   if (r2 >= 0)
2696     reglist &= ~(1u << r2);
2697   return reglist;
2698 }
2699
2700 // find a temp caller-saved register not in reglist (so assumed to be free)
2701 static int reglist_find_free(u_int reglist)
2702 {
2703   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2704   if (free_regs == 0)
2705     return -1;
2706   return __builtin_ctz(free_regs);
2707 }
2708
2709 static void load_assemble(int i, const struct regstat *i_regs)
2710 {
2711   int s,tl,addr;
2712   int offset;
2713   void *jaddr=0;
2714   int memtarget=0,c=0;
2715   int fastio_reg_override=-1;
2716   u_int reglist=get_host_reglist(i_regs->regmap);
2717   tl=get_reg(i_regs->regmap,rt1[i]);
2718   s=get_reg(i_regs->regmap,rs1[i]);
2719   offset=imm[i];
2720   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2721   if(s>=0) {
2722     c=(i_regs->wasconst>>s)&1;
2723     if (c) {
2724       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2725     }
2726   }
2727   //printf("load_assemble: c=%d\n",c);
2728   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2729   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2730   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2731     ||rt1[i]==0) {
2732       // could be FIFO, must perform the read
2733       // ||dummy read
2734       assem_debug("(forced read)\n");
2735       tl=get_reg(i_regs->regmap,-1);
2736       assert(tl>=0);
2737   }
2738   if(offset||s<0||c) addr=tl;
2739   else addr=s;
2740   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2741  if(tl>=0) {
2742   //printf("load_assemble: c=%d\n",c);
2743   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2744   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2745   reglist&=~(1<<tl);
2746   if(!c) {
2747     #ifdef R29_HACK
2748     // Strmnnrmn's speed hack
2749     if(rs1[i]!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2750     #endif
2751     {
2752       jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2753     }
2754   }
2755   else if(ram_offset&&memtarget) {
2756     host_tempreg_acquire();
2757     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2758     fastio_reg_override=HOST_TEMPREG;
2759   }
2760   int dummy=(rt1[i]==0)||(tl!=get_reg(i_regs->regmap,rt1[i])); // ignore loads to r0 and unneeded reg
2761   if (opcode[i]==0x20) { // LB
2762     if(!c||memtarget) {
2763       if(!dummy) {
2764         {
2765           int x=0,a=tl;
2766           if(!c) a=addr;
2767           if(fastio_reg_override>=0) a=fastio_reg_override;
2768
2769           emit_movsbl_indexed(x,a,tl);
2770         }
2771       }
2772       if(jaddr)
2773         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2774     }
2775     else
2776       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2777   }
2778   if (opcode[i]==0x21) { // LH
2779     if(!c||memtarget) {
2780       if(!dummy) {
2781         int x=0,a=tl;
2782         if(!c) a=addr;
2783         if(fastio_reg_override>=0) a=fastio_reg_override;
2784         emit_movswl_indexed(x,a,tl);
2785       }
2786       if(jaddr)
2787         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2788     }
2789     else
2790       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2791   }
2792   if (opcode[i]==0x23) { // LW
2793     if(!c||memtarget) {
2794       if(!dummy) {
2795         int a=addr;
2796         if(fastio_reg_override>=0) a=fastio_reg_override;
2797         emit_readword_indexed(0,a,tl);
2798       }
2799       if(jaddr)
2800         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2801     }
2802     else
2803       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2804   }
2805   if (opcode[i]==0x24) { // LBU
2806     if(!c||memtarget) {
2807       if(!dummy) {
2808         int x=0,a=tl;
2809         if(!c) a=addr;
2810         if(fastio_reg_override>=0) a=fastio_reg_override;
2811
2812         emit_movzbl_indexed(x,a,tl);
2813       }
2814       if(jaddr)
2815         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2816     }
2817     else
2818       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2819   }
2820   if (opcode[i]==0x25) { // LHU
2821     if(!c||memtarget) {
2822       if(!dummy) {
2823         int x=0,a=tl;
2824         if(!c) a=addr;
2825         if(fastio_reg_override>=0) a=fastio_reg_override;
2826         emit_movzwl_indexed(x,a,tl);
2827       }
2828       if(jaddr)
2829         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2830     }
2831     else
2832       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,rt1[i],ccadj[i],reglist);
2833   }
2834   if (opcode[i]==0x27) { // LWU
2835     assert(0);
2836   }
2837   if (opcode[i]==0x37) { // LD
2838     assert(0);
2839   }
2840  }
2841  if (fastio_reg_override == HOST_TEMPREG)
2842    host_tempreg_release();
2843 }
2844
2845 #ifndef loadlr_assemble
2846 static void loadlr_assemble(int i, const struct regstat *i_regs)
2847 {
2848   int s,tl,temp,temp2,addr;
2849   int offset;
2850   void *jaddr=0;
2851   int memtarget=0,c=0;
2852   int fastio_reg_override=-1;
2853   u_int reglist=get_host_reglist(i_regs->regmap);
2854   tl=get_reg(i_regs->regmap,rt1[i]);
2855   s=get_reg(i_regs->regmap,rs1[i]);
2856   temp=get_reg(i_regs->regmap,-1);
2857   temp2=get_reg(i_regs->regmap,FTEMP);
2858   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2859   assert(addr<0);
2860   offset=imm[i];
2861   reglist|=1<<temp;
2862   if(offset||s<0||c) addr=temp2;
2863   else addr=s;
2864   if(s>=0) {
2865     c=(i_regs->wasconst>>s)&1;
2866     if(c) {
2867       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2868     }
2869   }
2870   if(!c) {
2871     emit_shlimm(addr,3,temp);
2872     if (opcode[i]==0x22||opcode[i]==0x26) {
2873       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2874     }else{
2875       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2876     }
2877     jaddr=emit_fastpath_cmp_jump(i,temp2,&fastio_reg_override);
2878   }
2879   else {
2880     if(ram_offset&&memtarget) {
2881       host_tempreg_acquire();
2882       emit_addimm(temp2,ram_offset,HOST_TEMPREG);
2883       fastio_reg_override=HOST_TEMPREG;
2884     }
2885     if (opcode[i]==0x22||opcode[i]==0x26) {
2886       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2887     }else{
2888       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2889     }
2890   }
2891   if (opcode[i]==0x22||opcode[i]==0x26) { // LWL/LWR
2892     if(!c||memtarget) {
2893       int a=temp2;
2894       if(fastio_reg_override>=0) a=fastio_reg_override;
2895       emit_readword_indexed(0,a,temp2);
2896       if(fastio_reg_override==HOST_TEMPREG) host_tempreg_release();
2897       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj[i],reglist);
2898     }
2899     else
2900       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj[i],reglist);
2901     if(rt1[i]) {
2902       assert(tl>=0);
2903       emit_andimm(temp,24,temp);
2904       if (opcode[i]==0x22) // LWL
2905         emit_xorimm(temp,24,temp);
2906       host_tempreg_acquire();
2907       emit_movimm(-1,HOST_TEMPREG);
2908       if (opcode[i]==0x26) {
2909         emit_shr(temp2,temp,temp2);
2910         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2911       }else{
2912         emit_shl(temp2,temp,temp2);
2913         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2914       }
2915       host_tempreg_release();
2916       emit_or(temp2,tl,tl);
2917     }
2918     //emit_storereg(rt1[i],tl); // DEBUG
2919   }
2920   if (opcode[i]==0x1A||opcode[i]==0x1B) { // LDL/LDR
2921     assert(0);
2922   }
2923 }
2924 #endif
2925
2926 void store_assemble(int i, const struct regstat *i_regs)
2927 {
2928   int s,tl;
2929   int addr,temp;
2930   int offset;
2931   void *jaddr=0;
2932   enum stub_type type;
2933   int memtarget=0,c=0;
2934   int agr=AGEN1+(i&1);
2935   int fastio_reg_override=-1;
2936   u_int reglist=get_host_reglist(i_regs->regmap);
2937   tl=get_reg(i_regs->regmap,rs2[i]);
2938   s=get_reg(i_regs->regmap,rs1[i]);
2939   temp=get_reg(i_regs->regmap,agr);
2940   if(temp<0) temp=get_reg(i_regs->regmap,-1);
2941   offset=imm[i];
2942   if(s>=0) {
2943     c=(i_regs->wasconst>>s)&1;
2944     if(c) {
2945       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2946     }
2947   }
2948   assert(tl>=0);
2949   assert(temp>=0);
2950   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2951   if(offset||s<0||c) addr=temp;
2952   else addr=s;
2953   if(!c) {
2954     jaddr=emit_fastpath_cmp_jump(i,addr,&fastio_reg_override);
2955   }
2956   else if(ram_offset&&memtarget) {
2957     host_tempreg_acquire();
2958     emit_addimm(addr,ram_offset,HOST_TEMPREG);
2959     fastio_reg_override=HOST_TEMPREG;
2960   }
2961
2962   if (opcode[i]==0x28) { // SB
2963     if(!c||memtarget) {
2964       int x=0,a=temp;
2965       if(!c) a=addr;
2966       if(fastio_reg_override>=0) a=fastio_reg_override;
2967       emit_writebyte_indexed(tl,x,a);
2968     }
2969     type=STOREB_STUB;
2970   }
2971   if (opcode[i]==0x29) { // SH
2972     if(!c||memtarget) {
2973       int x=0,a=temp;
2974       if(!c) a=addr;
2975       if(fastio_reg_override>=0) a=fastio_reg_override;
2976       emit_writehword_indexed(tl,x,a);
2977     }
2978     type=STOREH_STUB;
2979   }
2980   if (opcode[i]==0x2B) { // SW
2981     if(!c||memtarget) {
2982       int a=addr;
2983       if(fastio_reg_override>=0) a=fastio_reg_override;
2984       emit_writeword_indexed(tl,0,a);
2985     }
2986     type=STOREW_STUB;
2987   }
2988   if (opcode[i]==0x3F) { // SD
2989     assert(0);
2990     type=STORED_STUB;
2991   }
2992   if(fastio_reg_override==HOST_TEMPREG)
2993     host_tempreg_release();
2994   if(jaddr) {
2995     // PCSX store handlers don't check invcode again
2996     reglist|=1<<addr;
2997     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
2998     jaddr=0;
2999   }
3000   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3001     if(!c||memtarget) {
3002       #ifdef DESTRUCTIVE_SHIFT
3003       // The x86 shift operation is 'destructive'; it overwrites the
3004       // source register, so we need to make a copy first and use that.
3005       addr=temp;
3006       #endif
3007       #if defined(HOST_IMM8)
3008       int ir=get_reg(i_regs->regmap,INVCP);
3009       assert(ir>=0);
3010       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3011       #else
3012       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3013       #endif
3014       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3015       emit_callne(invalidate_addr_reg[addr]);
3016       #else
3017       void *jaddr2 = out;
3018       emit_jne(0);
3019       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3020       #endif
3021     }
3022   }
3023   u_int addr_val=constmap[i][s]+offset;
3024   if(jaddr) {
3025     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj[i],reglist);
3026   } else if(c&&!memtarget) {
3027     inline_writestub(type,i,addr_val,i_regs->regmap,rs2[i],ccadj[i],reglist);
3028   }
3029   // basic current block modification detection..
3030   // not looking back as that should be in mips cache already
3031   // (see Spyro2 title->attract mode)
3032   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3033     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3034     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3035     if(i_regs->regmap==regs[i].regmap) {
3036       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3037       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3038       emit_movimm(start+i*4+4,0);
3039       emit_writeword(0,&pcaddr);
3040       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3041       emit_far_call(get_addr_ht);
3042       emit_jmpreg(0);
3043     }
3044   }
3045 }
3046
3047 static void storelr_assemble(int i, const struct regstat *i_regs)
3048 {
3049   int s,tl;
3050   int temp;
3051   int offset;
3052   void *jaddr=0;
3053   void *case1, *case2, *case3;
3054   void *done0, *done1, *done2;
3055   int memtarget=0,c=0;
3056   int agr=AGEN1+(i&1);
3057   u_int reglist=get_host_reglist(i_regs->regmap);
3058   tl=get_reg(i_regs->regmap,rs2[i]);
3059   s=get_reg(i_regs->regmap,rs1[i]);
3060   temp=get_reg(i_regs->regmap,agr);
3061   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3062   offset=imm[i];
3063   if(s>=0) {
3064     c=(i_regs->isconst>>s)&1;
3065     if(c) {
3066       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3067     }
3068   }
3069   assert(tl>=0);
3070   assert(temp>=0);
3071   if(!c) {
3072     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3073     if(!offset&&s!=temp) emit_mov(s,temp);
3074     jaddr=out;
3075     emit_jno(0);
3076   }
3077   else
3078   {
3079     if(!memtarget||!rs1[i]) {
3080       jaddr=out;
3081       emit_jmp(0);
3082     }
3083   }
3084   if(ram_offset)
3085     emit_addimm_no_flags(ram_offset,temp);
3086
3087   if (opcode[i]==0x2C||opcode[i]==0x2D) { // SDL/SDR
3088     assert(0);
3089   }
3090
3091   emit_xorimm(temp,3,temp);
3092   emit_testimm(temp,2);
3093   case2=out;
3094   emit_jne(0);
3095   emit_testimm(temp,1);
3096   case1=out;
3097   emit_jne(0);
3098   // 0
3099   if (opcode[i]==0x2A) { // SWL
3100     emit_writeword_indexed(tl,0,temp);
3101   }
3102   else if (opcode[i]==0x2E) { // SWR
3103     emit_writebyte_indexed(tl,3,temp);
3104   }
3105   else
3106     assert(0);
3107   done0=out;
3108   emit_jmp(0);
3109   // 1
3110   set_jump_target(case1, out);
3111   if (opcode[i]==0x2A) { // SWL
3112     // Write 3 msb into three least significant bytes
3113     if(rs2[i]) emit_rorimm(tl,8,tl);
3114     emit_writehword_indexed(tl,-1,temp);
3115     if(rs2[i]) emit_rorimm(tl,16,tl);
3116     emit_writebyte_indexed(tl,1,temp);
3117     if(rs2[i]) emit_rorimm(tl,8,tl);
3118   }
3119   else if (opcode[i]==0x2E) { // SWR
3120     // Write two lsb into two most significant bytes
3121     emit_writehword_indexed(tl,1,temp);
3122   }
3123   done1=out;
3124   emit_jmp(0);
3125   // 2
3126   set_jump_target(case2, out);
3127   emit_testimm(temp,1);
3128   case3=out;
3129   emit_jne(0);
3130   if (opcode[i]==0x2A) { // SWL
3131     // Write two msb into two least significant bytes
3132     if(rs2[i]) emit_rorimm(tl,16,tl);
3133     emit_writehword_indexed(tl,-2,temp);
3134     if(rs2[i]) emit_rorimm(tl,16,tl);
3135   }
3136   else if (opcode[i]==0x2E) { // SWR
3137     // Write 3 lsb into three most significant bytes
3138     emit_writebyte_indexed(tl,-1,temp);
3139     if(rs2[i]) emit_rorimm(tl,8,tl);
3140     emit_writehword_indexed(tl,0,temp);
3141     if(rs2[i]) emit_rorimm(tl,24,tl);
3142   }
3143   done2=out;
3144   emit_jmp(0);
3145   // 3
3146   set_jump_target(case3, out);
3147   if (opcode[i]==0x2A) { // SWL
3148     // Write msb into least significant byte
3149     if(rs2[i]) emit_rorimm(tl,24,tl);
3150     emit_writebyte_indexed(tl,-3,temp);
3151     if(rs2[i]) emit_rorimm(tl,8,tl);
3152   }
3153   else if (opcode[i]==0x2E) { // SWR
3154     // Write entire word
3155     emit_writeword_indexed(tl,-3,temp);
3156   }
3157   set_jump_target(done0, out);
3158   set_jump_target(done1, out);
3159   set_jump_target(done2, out);
3160   if(!c||!memtarget)
3161     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj[i],reglist);
3162   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3163     emit_addimm_no_flags(-ram_offset,temp);
3164     #if defined(HOST_IMM8)
3165     int ir=get_reg(i_regs->regmap,INVCP);
3166     assert(ir>=0);
3167     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3168     #else
3169     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3170     #endif
3171     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3172     emit_callne(invalidate_addr_reg[temp]);
3173     #else
3174     void *jaddr2 = out;
3175     emit_jne(0);
3176     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3177     #endif
3178   }
3179 }
3180
3181 static void cop0_assemble(int i,struct regstat *i_regs)
3182 {
3183   if(opcode2[i]==0) // MFC0
3184   {
3185     signed char t=get_reg(i_regs->regmap,rt1[i]);
3186     u_int copr=(source[i]>>11)&0x1f;
3187     //assert(t>=0); // Why does this happen?  OOT is weird
3188     if(t>=0&&rt1[i]!=0) {
3189       emit_readword(&reg_cop0[copr],t);
3190     }
3191   }
3192   else if(opcode2[i]==4) // MTC0
3193   {
3194     signed char s=get_reg(i_regs->regmap,rs1[i]);
3195     char copr=(source[i]>>11)&0x1f;
3196     assert(s>=0);
3197     wb_register(rs1[i],i_regs->regmap,i_regs->dirty);
3198     if(copr==9||copr==11||copr==12||copr==13) {
3199       emit_readword(&last_count,HOST_TEMPREG);
3200       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3201       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3202       emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3203       emit_writeword(HOST_CCREG,&Count);
3204     }
3205     // What a mess.  The status register (12) can enable interrupts,
3206     // so needs a special case to handle a pending interrupt.
3207     // The interrupt must be taken immediately, because a subsequent
3208     // instruction might disable interrupts again.
3209     if(copr==12||copr==13) {
3210       if (is_delayslot) {
3211         // burn cycles to cause cc_interrupt, which will
3212         // reschedule next_interupt. Relies on CCREG from above.
3213         assem_debug("MTC0 DS %d\n", copr);
3214         emit_writeword(HOST_CCREG,&last_count);
3215         emit_movimm(0,HOST_CCREG);
3216         emit_storereg(CCREG,HOST_CCREG);
3217         emit_loadreg(rs1[i],1);
3218         emit_movimm(copr,0);
3219         emit_far_call(pcsx_mtc0_ds);
3220         emit_loadreg(rs1[i],s);
3221         return;
3222       }
3223       emit_movimm(start+i*4+4,HOST_TEMPREG);
3224       emit_writeword(HOST_TEMPREG,&pcaddr);
3225       emit_movimm(0,HOST_TEMPREG);
3226       emit_writeword(HOST_TEMPREG,&pending_exception);
3227     }
3228     if(s==HOST_CCREG)
3229       emit_loadreg(rs1[i],1);
3230     else if(s!=1)
3231       emit_mov(s,1);
3232     emit_movimm(copr,0);
3233     emit_far_call(pcsx_mtc0);
3234     if(copr==9||copr==11||copr==12||copr==13) {
3235       emit_readword(&Count,HOST_CCREG);
3236       emit_readword(&next_interupt,HOST_TEMPREG);
3237       emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[i]),HOST_CCREG);
3238       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3239       emit_writeword(HOST_TEMPREG,&last_count);
3240       emit_storereg(CCREG,HOST_CCREG);
3241     }
3242     if(copr==12||copr==13) {
3243       assert(!is_delayslot);
3244       emit_readword(&pending_exception,14);
3245       emit_test(14,14);
3246       void *jaddr = out;
3247       emit_jeq(0);
3248       emit_readword(&pcaddr, 0);
3249       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3250       emit_far_call(get_addr_ht);
3251       emit_jmpreg(0);
3252       set_jump_target(jaddr, out);
3253     }
3254     emit_loadreg(rs1[i],s);
3255   }
3256   else
3257   {
3258     assert(opcode2[i]==0x10);
3259     //if((source[i]&0x3f)==0x10) // RFE
3260     {
3261       emit_readword(&Status,0);
3262       emit_andimm(0,0x3c,1);
3263       emit_andimm(0,~0xf,0);
3264       emit_orrshr_imm(1,2,0);
3265       emit_writeword(0,&Status);
3266     }
3267   }
3268 }
3269
3270 static void cop1_unusable(int i,struct regstat *i_regs)
3271 {
3272   // XXX: should just just do the exception instead
3273   //if(!cop1_usable)
3274   {
3275     void *jaddr=out;
3276     emit_jmp(0);
3277     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3278   }
3279 }
3280
3281 static void cop1_assemble(int i,struct regstat *i_regs)
3282 {
3283   cop1_unusable(i, i_regs);
3284 }
3285
3286 static void c1ls_assemble(int i,struct regstat *i_regs)
3287 {
3288   cop1_unusable(i, i_regs);
3289 }
3290
3291 // FP_STUB
3292 static void do_cop1stub(int n)
3293 {
3294   literal_pool(256);
3295   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3296   set_jump_target(stubs[n].addr, out);
3297   int i=stubs[n].a;
3298 //  int rs=stubs[n].b;
3299   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3300   int ds=stubs[n].d;
3301   if(!ds) {
3302     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3303     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3304   }
3305   //else {printf("fp exception in delay slot\n");}
3306   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3307   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3308   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3309   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3310   emit_far_jump(ds?fp_exception_ds:fp_exception);
3311 }
3312
3313 static int cop2_is_stalling_op(int i, int *cycles)
3314 {
3315   if (opcode[i] == 0x3a) { // SWC2
3316     *cycles = 0;
3317     return 1;
3318   }
3319   if (itype[i] == COP2 && (opcode2[i] == 0 || opcode2[i] == 2)) { // MFC2/CFC2
3320     *cycles = 0;
3321     return 1;
3322   }
3323   if (itype[i] == C2OP) {
3324     *cycles = gte_cycletab[source[i] & 0x3f];
3325     return 1;
3326   }
3327   // ... what about MTC2/CTC2/LWC2?
3328   return 0;
3329 }
3330
3331 #if 0
3332 static void log_gte_stall(int stall, u_int cycle)
3333 {
3334   if ((u_int)stall <= 44)
3335     printf("x    stall %2d %u\n", stall, cycle + last_count);
3336 }
3337
3338 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3339 {
3340   save_regs(reglist);
3341   if (stall > 0)
3342     emit_movimm(stall, 0);
3343   else
3344     emit_mov(HOST_TEMPREG, 0);
3345   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3346   emit_far_call(log_gte_stall);
3347   restore_regs(reglist);
3348 }
3349 #endif
3350
3351 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3352 {
3353   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3354   int rtmp = reglist_find_free(reglist);
3355
3356   if (HACK_ENABLED(NDHACK_NO_STALLS))
3357     return;
3358   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3359     // happens occasionally... cc evicted? Don't bother then
3360     //printf("no cc %08x\n", start + i*4);
3361     return;
3362   }
3363   if (!bt[i]) {
3364     for (j = i - 1; j >= 0; j--) {
3365       //if (is_ds[j]) break;
3366       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || bt[j])
3367         break;
3368     }
3369     j = max(j, 0);
3370   }
3371   cycles_passed = CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3372   if (other_gte_op_cycles >= 0)
3373     stall = other_gte_op_cycles - cycles_passed;
3374   else if (cycles_passed >= 44)
3375     stall = 0; // can't stall
3376   if (stall == -MAXBLOCK && rtmp >= 0) {
3377     // unknown stall, do the expensive runtime check
3378     assem_debug("; cop2_do_stall_check\n");
3379 #if 0 // too slow
3380     save_regs(reglist);
3381     emit_movimm(gte_cycletab[op], 0);
3382     emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]), 1);
3383     emit_far_call(call_gteStall);
3384     restore_regs(reglist);
3385 #else
3386     host_tempreg_acquire();
3387     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3388     emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3389     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3390     emit_cmpimm(HOST_TEMPREG, 44);
3391     emit_cmovb_reg(rtmp, HOST_CCREG);
3392     //emit_log_gte_stall(i, 0, reglist);
3393     host_tempreg_release();
3394 #endif
3395   }
3396   else if (stall > 0) {
3397     //emit_log_gte_stall(i, stall, reglist);
3398     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3399   }
3400
3401   // save gteBusyCycle, if needed
3402   if (gte_cycletab[op] == 0)
3403     return;
3404   other_gte_op_cycles = -1;
3405   for (j = i + 1; j < slen; j++) {
3406     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3407       break;
3408     if (is_jump(j)) {
3409       // check ds
3410       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3411         j++;
3412       break;
3413     }
3414   }
3415   if (other_gte_op_cycles >= 0)
3416     // will handle stall when assembling that op
3417     return;
3418   cycles_passed = CLOCK_ADJUST(ccadj[min(j, slen -1)] - ccadj[i]);
3419   if (cycles_passed >= 44)
3420     return;
3421   assem_debug("; save gteBusyCycle\n");
3422   host_tempreg_acquire();
3423 #if 0
3424   emit_readword(&last_count, HOST_TEMPREG);
3425   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3426   emit_addimm(HOST_TEMPREG, CLOCK_ADJUST(ccadj[i]), HOST_TEMPREG);
3427   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3428   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3429 #else
3430   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + gte_cycletab[op], HOST_TEMPREG);
3431   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3432 #endif
3433   host_tempreg_release();
3434 }
3435
3436 static int is_mflohi(int i)
3437 {
3438   return (itype[i] == MOV && (rs1[i] == HIREG || rs1[i] == LOREG));
3439 }
3440
3441 static int check_multdiv(int i, int *cycles)
3442 {
3443   if (itype[i] != MULTDIV)
3444     return 0;
3445   if (opcode2[i] == 0x18 || opcode2[i] == 0x19) // MULT(U)
3446     *cycles = 11; // approx from 7 11 14
3447   else
3448     *cycles = 37;
3449   return 1;
3450 }
3451
3452 static void multdiv_prepare_stall(int i, const struct regstat *i_regs)
3453 {
3454   int j, found = 0, c = 0;
3455   if (HACK_ENABLED(NDHACK_NO_STALLS))
3456     return;
3457   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3458     // happens occasionally... cc evicted? Don't bother then
3459     return;
3460   }
3461   for (j = i + 1; j < slen; j++) {
3462     if (bt[j])
3463       break;
3464     if ((found = is_mflohi(j)))
3465       break;
3466     if (is_jump(j)) {
3467       // check ds
3468       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3469         j++;
3470       break;
3471     }
3472   }
3473   if (found)
3474     // handle all in multdiv_do_stall()
3475     return;
3476   check_multdiv(i, &c);
3477   assert(c > 0);
3478   assem_debug("; muldiv prepare stall %d\n", c);
3479   host_tempreg_acquire();
3480   emit_addimm(HOST_CCREG, CLOCK_ADJUST(ccadj[i]) + c, HOST_TEMPREG);
3481   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3482   host_tempreg_release();
3483 }
3484
3485 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3486 {
3487   int j, known_cycles = 0;
3488   u_int reglist = get_host_reglist(i_regs->regmap);
3489   int rtmp = get_reg(i_regs->regmap, -1);
3490   if (rtmp < 0)
3491     rtmp = reglist_find_free(reglist);
3492   if (HACK_ENABLED(NDHACK_NO_STALLS))
3493     return;
3494   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3495     // happens occasionally... cc evicted? Don't bother then
3496     //printf("no cc/rtmp %08x\n", start + i*4);
3497     return;
3498   }
3499   if (!bt[i]) {
3500     for (j = i - 1; j >= 0; j--) {
3501       if (is_ds[j]) break;
3502       if (check_multdiv(j, &known_cycles) || bt[j])
3503         break;
3504       if (is_mflohi(j))
3505         // already handled by this op
3506         return;
3507     }
3508     j = max(j, 0);
3509   }
3510   if (known_cycles > 0) {
3511     known_cycles -= CLOCK_ADJUST(ccadj[i] - ccadj[j]);
3512     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3513     if (known_cycles > 0)
3514       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3515     return;
3516   }
3517   assem_debug("; muldiv stall unresolved\n");
3518   host_tempreg_acquire();
3519   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3520   emit_addimm(rtmp, -CLOCK_ADJUST(ccadj[i]), rtmp);
3521   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3522   emit_cmpimm(HOST_TEMPREG, 37);
3523   emit_cmovb_reg(rtmp, HOST_CCREG);
3524   //emit_log_gte_stall(i, 0, reglist);
3525   host_tempreg_release();
3526 }
3527
3528 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3529 {
3530   switch (copr) {
3531     case 1:
3532     case 3:
3533     case 5:
3534     case 8:
3535     case 9:
3536     case 10:
3537     case 11:
3538       emit_readword(&reg_cop2d[copr],tl);
3539       emit_signextend16(tl,tl);
3540       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3541       break;
3542     case 7:
3543     case 16:
3544     case 17:
3545     case 18:
3546     case 19:
3547       emit_readword(&reg_cop2d[copr],tl);
3548       emit_andimm(tl,0xffff,tl);
3549       emit_writeword(tl,&reg_cop2d[copr]);
3550       break;
3551     case 15:
3552       emit_readword(&reg_cop2d[14],tl); // SXY2
3553       emit_writeword(tl,&reg_cop2d[copr]);
3554       break;
3555     case 28:
3556     case 29:
3557       c2op_mfc2_29_assemble(tl,temp);
3558       break;
3559     default:
3560       emit_readword(&reg_cop2d[copr],tl);
3561       break;
3562   }
3563 }
3564
3565 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3566 {
3567   switch (copr) {
3568     case 15:
3569       emit_readword(&reg_cop2d[13],temp);  // SXY1
3570       emit_writeword(sl,&reg_cop2d[copr]);
3571       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3572       emit_readword(&reg_cop2d[14],temp);  // SXY2
3573       emit_writeword(sl,&reg_cop2d[14]);
3574       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3575       break;
3576     case 28:
3577       emit_andimm(sl,0x001f,temp);
3578       emit_shlimm(temp,7,temp);
3579       emit_writeword(temp,&reg_cop2d[9]);
3580       emit_andimm(sl,0x03e0,temp);
3581       emit_shlimm(temp,2,temp);
3582       emit_writeword(temp,&reg_cop2d[10]);
3583       emit_andimm(sl,0x7c00,temp);
3584       emit_shrimm(temp,3,temp);
3585       emit_writeword(temp,&reg_cop2d[11]);
3586       emit_writeword(sl,&reg_cop2d[28]);
3587       break;
3588     case 30:
3589       emit_xorsar_imm(sl,sl,31,temp);
3590 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3591       emit_clz(temp,temp);
3592 #else
3593       emit_movs(temp,HOST_TEMPREG);
3594       emit_movimm(0,temp);
3595       emit_jeq((int)out+4*4);
3596       emit_addpl_imm(temp,1,temp);
3597       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3598       emit_jns((int)out-2*4);
3599 #endif
3600       emit_writeword(sl,&reg_cop2d[30]);
3601       emit_writeword(temp,&reg_cop2d[31]);
3602       break;
3603     case 31:
3604       break;
3605     default:
3606       emit_writeword(sl,&reg_cop2d[copr]);
3607       break;
3608   }
3609 }
3610
3611 static void c2ls_assemble(int i, const struct regstat *i_regs)
3612 {
3613   int s,tl;
3614   int ar;
3615   int offset;
3616   int memtarget=0,c=0;
3617   void *jaddr2=NULL;
3618   enum stub_type type;
3619   int agr=AGEN1+(i&1);
3620   int fastio_reg_override=-1;
3621   u_int reglist=get_host_reglist(i_regs->regmap);
3622   u_int copr=(source[i]>>16)&0x1f;
3623   s=get_reg(i_regs->regmap,rs1[i]);
3624   tl=get_reg(i_regs->regmap,FTEMP);
3625   offset=imm[i];
3626   assert(rs1[i]>0);
3627   assert(tl>=0);
3628
3629   if(i_regs->regmap[HOST_CCREG]==CCREG)
3630     reglist&=~(1<<HOST_CCREG);
3631
3632   // get the address
3633   if (opcode[i]==0x3a) { // SWC2
3634     ar=get_reg(i_regs->regmap,agr);
3635     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3636     reglist|=1<<ar;
3637   } else { // LWC2
3638     ar=tl;
3639   }
3640   if(s>=0) c=(i_regs->wasconst>>s)&1;
3641   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3642   if (!offset&&!c&&s>=0) ar=s;
3643   assert(ar>=0);
3644
3645   cop2_do_stall_check(0, i, i_regs, reglist);
3646
3647   if (opcode[i]==0x3a) { // SWC2
3648     cop2_get_dreg(copr,tl,-1);
3649     type=STOREW_STUB;
3650   }
3651   else
3652     type=LOADW_STUB;
3653
3654   if(c&&!memtarget) {
3655     jaddr2=out;
3656     emit_jmp(0); // inline_readstub/inline_writestub?
3657   }
3658   else {
3659     if(!c) {
3660       jaddr2=emit_fastpath_cmp_jump(i,ar,&fastio_reg_override);
3661     }
3662     else if(ram_offset&&memtarget) {
3663       host_tempreg_acquire();
3664       emit_addimm(ar,ram_offset,HOST_TEMPREG);
3665       fastio_reg_override=HOST_TEMPREG;
3666     }
3667     if (opcode[i]==0x32) { // LWC2
3668       int a=ar;
3669       if(fastio_reg_override>=0) a=fastio_reg_override;
3670       emit_readword_indexed(0,a,tl);
3671     }
3672     if (opcode[i]==0x3a) { // SWC2
3673       #ifdef DESTRUCTIVE_SHIFT
3674       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3675       #endif
3676       int a=ar;
3677       if(fastio_reg_override>=0) a=fastio_reg_override;
3678       emit_writeword_indexed(tl,0,a);
3679     }
3680   }
3681   if(fastio_reg_override==HOST_TEMPREG)
3682     host_tempreg_release();
3683   if(jaddr2)
3684     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj[i],reglist);
3685   if(opcode[i]==0x3a) // SWC2
3686   if(!(i_regs->waswritten&(1<<rs1[i])) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3687 #if defined(HOST_IMM8)
3688     int ir=get_reg(i_regs->regmap,INVCP);
3689     assert(ir>=0);
3690     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3691 #else
3692     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3693 #endif
3694     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3695     emit_callne(invalidate_addr_reg[ar]);
3696     #else
3697     void *jaddr3 = out;
3698     emit_jne(0);
3699     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3700     #endif
3701   }
3702   if (opcode[i]==0x32) { // LWC2
3703     host_tempreg_acquire();
3704     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3705     host_tempreg_release();
3706   }
3707 }
3708
3709 static void cop2_assemble(int i, const struct regstat *i_regs)
3710 {
3711   u_int copr = (source[i]>>11) & 0x1f;
3712   signed char temp = get_reg(i_regs->regmap, -1);
3713
3714   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3715     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3716     if (opcode2[i] == 0 || opcode2[i] == 2) { // MFC2/CFC2
3717       signed char tl = get_reg(i_regs->regmap, rt1[i]);
3718       reglist = reglist_exclude(reglist, tl, -1);
3719     }
3720     cop2_do_stall_check(0, i, i_regs, reglist);
3721   }
3722   if (opcode2[i]==0) { // MFC2
3723     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3724     if(tl>=0&&rt1[i]!=0)
3725       cop2_get_dreg(copr,tl,temp);
3726   }
3727   else if (opcode2[i]==4) { // MTC2
3728     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3729     cop2_put_dreg(copr,sl,temp);
3730   }
3731   else if (opcode2[i]==2) // CFC2
3732   {
3733     signed char tl=get_reg(i_regs->regmap,rt1[i]);
3734     if(tl>=0&&rt1[i]!=0)
3735       emit_readword(&reg_cop2c[copr],tl);
3736   }
3737   else if (opcode2[i]==6) // CTC2
3738   {
3739     signed char sl=get_reg(i_regs->regmap,rs1[i]);
3740     switch(copr) {
3741       case 4:
3742       case 12:
3743       case 20:
3744       case 26:
3745       case 27:
3746       case 29:
3747       case 30:
3748         emit_signextend16(sl,temp);
3749         break;
3750       case 31:
3751         c2op_ctc2_31_assemble(sl,temp);
3752         break;
3753       default:
3754         temp=sl;
3755         break;
3756     }
3757     emit_writeword(temp,&reg_cop2c[copr]);
3758     assert(sl>=0);
3759   }
3760 }
3761
3762 static void do_unalignedwritestub(int n)
3763 {
3764   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3765   literal_pool(256);
3766   set_jump_target(stubs[n].addr, out);
3767
3768   int i=stubs[n].a;
3769   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3770   int addr=stubs[n].b;
3771   u_int reglist=stubs[n].e;
3772   signed char *i_regmap=i_regs->regmap;
3773   int temp2=get_reg(i_regmap,FTEMP);
3774   int rt;
3775   rt=get_reg(i_regmap,rs2[i]);
3776   assert(rt>=0);
3777   assert(addr>=0);
3778   assert(opcode[i]==0x2a||opcode[i]==0x2e); // SWL/SWR only implemented
3779   reglist|=(1<<addr);
3780   reglist&=~(1<<temp2);
3781
3782 #if 1
3783   // don't bother with it and call write handler
3784   save_regs(reglist);
3785   pass_args(addr,rt);
3786   int cc=get_reg(i_regmap,CCREG);
3787   if(cc<0)
3788     emit_loadreg(CCREG,2);
3789   emit_addimm(cc<0?2:cc,CLOCK_ADJUST((int)stubs[n].d+1),2);
3790   emit_far_call((opcode[i]==0x2a?jump_handle_swl:jump_handle_swr));
3791   emit_addimm(0,-CLOCK_ADJUST((int)stubs[n].d+1),cc<0?2:cc);
3792   if(cc<0)
3793     emit_storereg(CCREG,2);
3794   restore_regs(reglist);
3795   emit_jmp(stubs[n].retaddr); // return address
3796 #else
3797   emit_andimm(addr,0xfffffffc,temp2);
3798   emit_writeword(temp2,&address);
3799
3800   save_regs(reglist);
3801   emit_shrimm(addr,16,1);
3802   int cc=get_reg(i_regmap,CCREG);
3803   if(cc<0) {
3804     emit_loadreg(CCREG,2);
3805   }
3806   emit_movimm((u_int)readmem,0);
3807   emit_addimm(cc<0?2:cc,2*stubs[n].d+2,2);
3808   emit_call((int)&indirect_jump_indexed);
3809   restore_regs(reglist);
3810
3811   emit_readword(&readmem_dword,temp2);
3812   int temp=addr; //hmh
3813   emit_shlimm(addr,3,temp);
3814   emit_andimm(temp,24,temp);
3815   if (opcode[i]==0x2a) // SWL
3816     emit_xorimm(temp,24,temp);
3817   emit_movimm(-1,HOST_TEMPREG);
3818   if (opcode[i]==0x2a) { // SWL
3819     emit_bic_lsr(temp2,HOST_TEMPREG,temp,temp2);
3820     emit_orrshr(rt,temp,temp2);
3821   }else{
3822     emit_bic_lsl(temp2,HOST_TEMPREG,temp,temp2);
3823     emit_orrshl(rt,temp,temp2);
3824   }
3825   emit_readword(&address,addr);
3826   emit_writeword(temp2,&word);
3827   //save_regs(reglist); // don't need to, no state changes
3828   emit_shrimm(addr,16,1);
3829   emit_movimm((u_int)writemem,0);
3830   //emit_call((int)&indirect_jump_indexed);
3831   emit_mov(15,14);
3832   emit_readword_dualindexedx4(0,1,15);
3833   emit_readword(&Count,HOST_TEMPREG);
3834   emit_readword(&next_interupt,2);
3835   emit_addimm(HOST_TEMPREG,-2*stubs[n].d-2,HOST_TEMPREG);
3836   emit_writeword(2,&last_count);
3837   emit_sub(HOST_TEMPREG,2,cc<0?HOST_TEMPREG:cc);
3838   if(cc<0) {
3839     emit_storereg(CCREG,HOST_TEMPREG);
3840   }
3841   restore_regs(reglist);
3842   emit_jmp(stubs[n].retaddr); // return address
3843 #endif
3844 }
3845
3846 #ifndef multdiv_assemble
3847 void multdiv_assemble(int i,struct regstat *i_regs)
3848 {
3849   printf("Need multdiv_assemble for this architecture.\n");
3850   abort();
3851 }
3852 #endif
3853
3854 static void mov_assemble(int i,struct regstat *i_regs)
3855 {
3856   //if(opcode2[i]==0x10||opcode2[i]==0x12) { // MFHI/MFLO
3857   //if(opcode2[i]==0x11||opcode2[i]==0x13) { // MTHI/MTLO
3858   if(rt1[i]) {
3859     signed char sl,tl;
3860     tl=get_reg(i_regs->regmap,rt1[i]);
3861     //assert(tl>=0);
3862     if(tl>=0) {
3863       sl=get_reg(i_regs->regmap,rs1[i]);
3864       if(sl>=0) emit_mov(sl,tl);
3865       else emit_loadreg(rs1[i],tl);
3866     }
3867   }
3868   if (rs1[i] == HIREG || rs1[i] == LOREG) // MFHI/MFLO
3869     multdiv_do_stall(i, i_regs);
3870 }
3871
3872 // call interpreter, exception handler, things that change pc/regs/cycles ...
3873 static void call_c_cpu_handler(int i, const struct regstat *i_regs, u_int pc, void *func)
3874 {
3875   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3876   assert(ccreg==HOST_CCREG);
3877   assert(!is_delayslot);
3878   (void)ccreg;
3879
3880   emit_movimm(pc,3); // Get PC
3881   emit_readword(&last_count,2);
3882   emit_writeword(3,&psxRegs.pc);
3883   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]),HOST_CCREG); // XXX
3884   emit_add(2,HOST_CCREG,2);
3885   emit_writeword(2,&psxRegs.cycle);
3886   emit_far_call(func);
3887   emit_far_jump(jump_to_new_pc);
3888 }
3889
3890 static void syscall_assemble(int i,struct regstat *i_regs)
3891 {
3892   emit_movimm(0x20,0); // cause code
3893   emit_movimm(0,1);    // not in delay slot
3894   call_c_cpu_handler(i,i_regs,start+i*4,psxException);
3895 }
3896
3897 static void hlecall_assemble(int i,struct regstat *i_regs)
3898 {
3899   void *hlefunc = psxNULL;
3900   uint32_t hleCode = source[i] & 0x03ffffff;
3901   if (hleCode < ARRAY_SIZE(psxHLEt))
3902     hlefunc = psxHLEt[hleCode];
3903
3904   call_c_cpu_handler(i,i_regs,start+i*4+4,hlefunc);
3905 }
3906
3907 static void intcall_assemble(int i,struct regstat *i_regs)
3908 {
3909   call_c_cpu_handler(i,i_regs,start+i*4,execI);
3910 }
3911
3912 static void speculate_mov(int rs,int rt)
3913 {
3914   if(rt!=0) {
3915     smrv_strong_next|=1<<rt;
3916     smrv[rt]=smrv[rs];
3917   }
3918 }
3919
3920 static void speculate_mov_weak(int rs,int rt)
3921 {
3922   if(rt!=0) {
3923     smrv_weak_next|=1<<rt;
3924     smrv[rt]=smrv[rs];
3925   }
3926 }
3927
3928 static void speculate_register_values(int i)
3929 {
3930   if(i==0) {
3931     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3932     // gp,sp are likely to stay the same throughout the block
3933     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3934     smrv_weak_next=~smrv_strong_next;
3935     //printf(" llr %08x\n", smrv[4]);
3936   }
3937   smrv_strong=smrv_strong_next;
3938   smrv_weak=smrv_weak_next;
3939   switch(itype[i]) {
3940     case ALU:
3941       if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3942       else if((smrv_strong>>rs2[i])&1) speculate_mov(rs2[i],rt1[i]);
3943       else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3944       else if((smrv_weak>>rs2[i])&1) speculate_mov_weak(rs2[i],rt1[i]);
3945       else {
3946         smrv_strong_next&=~(1<<rt1[i]);
3947         smrv_weak_next&=~(1<<rt1[i]);
3948       }
3949       break;
3950     case SHIFTIMM:
3951       smrv_strong_next&=~(1<<rt1[i]);
3952       smrv_weak_next&=~(1<<rt1[i]);
3953       // fallthrough
3954     case IMM16:
3955       if(rt1[i]&&is_const(&regs[i],rt1[i])) {
3956         int value,hr=get_reg(regs[i].regmap,rt1[i]);
3957         if(hr>=0) {
3958           if(get_final_value(hr,i,&value))
3959                smrv[rt1[i]]=value;
3960           else smrv[rt1[i]]=constmap[i][hr];
3961           smrv_strong_next|=1<<rt1[i];
3962         }
3963       }
3964       else {
3965         if     ((smrv_strong>>rs1[i])&1) speculate_mov(rs1[i],rt1[i]);
3966         else if((smrv_weak>>rs1[i])&1) speculate_mov_weak(rs1[i],rt1[i]);
3967       }
3968       break;
3969     case LOAD:
3970       if(start<0x2000&&(rt1[i]==26||(smrv[rt1[i]]>>24)==0xa0)) {
3971         // special case for BIOS
3972         smrv[rt1[i]]=0xa0000000;
3973         smrv_strong_next|=1<<rt1[i];
3974         break;
3975       }
3976       // fallthrough
3977     case SHIFT:
3978     case LOADLR:
3979     case MOV:
3980       smrv_strong_next&=~(1<<rt1[i]);
3981       smrv_weak_next&=~(1<<rt1[i]);
3982       break;
3983     case COP0:
3984     case COP2:
3985       if(opcode2[i]==0||opcode2[i]==2) { // MFC/CFC
3986         smrv_strong_next&=~(1<<rt1[i]);
3987         smrv_weak_next&=~(1<<rt1[i]);
3988       }
3989       break;
3990     case C2LS:
3991       if (opcode[i]==0x32) { // LWC2
3992         smrv_strong_next&=~(1<<rt1[i]);
3993         smrv_weak_next&=~(1<<rt1[i]);
3994       }
3995       break;
3996   }
3997 #if 0
3998   int r=4;
3999   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4000     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4001 #endif
4002 }
4003
4004 static void ds_assemble(int i,struct regstat *i_regs)
4005 {
4006   speculate_register_values(i);
4007   is_delayslot=1;
4008   switch(itype[i]) {
4009     case ALU:
4010       alu_assemble(i,i_regs);break;
4011     case IMM16:
4012       imm16_assemble(i,i_regs);break;
4013     case SHIFT:
4014       shift_assemble(i,i_regs);break;
4015     case SHIFTIMM:
4016       shiftimm_assemble(i,i_regs);break;
4017     case LOAD:
4018       load_assemble(i,i_regs);break;
4019     case LOADLR:
4020       loadlr_assemble(i,i_regs);break;
4021     case STORE:
4022       store_assemble(i,i_regs);break;
4023     case STORELR:
4024       storelr_assemble(i,i_regs);break;
4025     case COP0:
4026       cop0_assemble(i,i_regs);break;
4027     case COP1:
4028       cop1_assemble(i,i_regs);break;
4029     case C1LS:
4030       c1ls_assemble(i,i_regs);break;
4031     case COP2:
4032       cop2_assemble(i,i_regs);break;
4033     case C2LS:
4034       c2ls_assemble(i,i_regs);break;
4035     case C2OP:
4036       c2op_assemble(i,i_regs);break;
4037     case MULTDIV:
4038       multdiv_assemble(i,i_regs);
4039       multdiv_prepare_stall(i,i_regs);
4040       break;
4041     case MOV:
4042       mov_assemble(i,i_regs);break;
4043     case SYSCALL:
4044     case HLECALL:
4045     case INTCALL:
4046     case SPAN:
4047     case UJUMP:
4048     case RJUMP:
4049     case CJUMP:
4050     case SJUMP:
4051       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4052   }
4053   is_delayslot=0;
4054 }
4055
4056 // Is the branch target a valid internal jump?
4057 static int internal_branch(int addr)
4058 {
4059   if(addr&1) return 0; // Indirect (register) jump
4060   if(addr>=start && addr<start+slen*4-4)
4061   {
4062     return 1;
4063   }
4064   return 0;
4065 }
4066
4067 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4068 {
4069   int hr;
4070   for(hr=0;hr<HOST_REGS;hr++) {
4071     if(hr!=EXCLUDE_REG) {
4072       if(pre[hr]!=entry[hr]) {
4073         if(pre[hr]>=0) {
4074           if((dirty>>hr)&1) {
4075             if(get_reg(entry,pre[hr])<0) {
4076               assert(pre[hr]<64);
4077               if(!((u>>pre[hr])&1))
4078                 emit_storereg(pre[hr],hr);
4079             }
4080           }
4081         }
4082       }
4083     }
4084   }
4085   // Move from one register to another (no writeback)
4086   for(hr=0;hr<HOST_REGS;hr++) {
4087     if(hr!=EXCLUDE_REG) {
4088       if(pre[hr]!=entry[hr]) {
4089         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4090           int nr;
4091           if((nr=get_reg(entry,pre[hr]))>=0) {
4092             emit_mov(hr,nr);
4093           }
4094         }
4095       }
4096     }
4097   }
4098 }
4099
4100 // Load the specified registers
4101 // This only loads the registers given as arguments because
4102 // we don't want to load things that will be overwritten
4103 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4104 {
4105   int hr;
4106   // Load 32-bit regs
4107   for(hr=0;hr<HOST_REGS;hr++) {
4108     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4109       if(entry[hr]!=regmap[hr]) {
4110         if(regmap[hr]==rs1||regmap[hr]==rs2)
4111         {
4112           if(regmap[hr]==0) {
4113             emit_zeroreg(hr);
4114           }
4115           else
4116           {
4117             emit_loadreg(regmap[hr],hr);
4118           }
4119         }
4120       }
4121     }
4122   }
4123 }
4124
4125 // Load registers prior to the start of a loop
4126 // so that they are not loaded within the loop
4127 static void loop_preload(signed char pre[],signed char entry[])
4128 {
4129   int hr;
4130   for(hr=0;hr<HOST_REGS;hr++) {
4131     if(hr!=EXCLUDE_REG) {
4132       if(pre[hr]!=entry[hr]) {
4133         if(entry[hr]>=0) {
4134           if(get_reg(pre,entry[hr])<0) {
4135             assem_debug("loop preload:\n");
4136             //printf("loop preload: %d\n",hr);
4137             if(entry[hr]==0) {
4138               emit_zeroreg(hr);
4139             }
4140             else if(entry[hr]<TEMPREG)
4141             {
4142               emit_loadreg(entry[hr],hr);
4143             }
4144             else if(entry[hr]-64<TEMPREG)
4145             {
4146               emit_loadreg(entry[hr],hr);
4147             }
4148           }
4149         }
4150       }
4151     }
4152   }
4153 }
4154
4155 // Generate address for load/store instruction
4156 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4157 void address_generation(int i,struct regstat *i_regs,signed char entry[])
4158 {
4159   if(itype[i]==LOAD||itype[i]==LOADLR||itype[i]==STORE||itype[i]==STORELR||itype[i]==C1LS||itype[i]==C2LS) {
4160     int ra=-1;
4161     int agr=AGEN1+(i&1);
4162     if(itype[i]==LOAD) {
4163       ra=get_reg(i_regs->regmap,rt1[i]);
4164       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4165       assert(ra>=0);
4166     }
4167     if(itype[i]==LOADLR) {
4168       ra=get_reg(i_regs->regmap,FTEMP);
4169     }
4170     if(itype[i]==STORE||itype[i]==STORELR) {
4171       ra=get_reg(i_regs->regmap,agr);
4172       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4173     }
4174     if(itype[i]==C1LS||itype[i]==C2LS) {
4175       if ((opcode[i]&0x3b)==0x31||(opcode[i]&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4176         ra=get_reg(i_regs->regmap,FTEMP);
4177       else { // SWC1/SDC1/SWC2/SDC2
4178         ra=get_reg(i_regs->regmap,agr);
4179         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4180       }
4181     }
4182     int rs=get_reg(i_regs->regmap,rs1[i]);
4183     if(ra>=0) {
4184       int offset=imm[i];
4185       int c=(i_regs->wasconst>>rs)&1;
4186       if(rs1[i]==0) {
4187         // Using r0 as a base address
4188         if(!entry||entry[ra]!=agr) {
4189           if (opcode[i]==0x22||opcode[i]==0x26) {
4190             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4191           }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
4192             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4193           }else{
4194             emit_movimm(offset,ra);
4195           }
4196         } // else did it in the previous cycle
4197       }
4198       else if(rs<0) {
4199         if(!entry||entry[ra]!=rs1[i])
4200           emit_loadreg(rs1[i],ra);
4201         //if(!entry||entry[ra]!=rs1[i])
4202         //  printf("poor load scheduling!\n");
4203       }
4204       else if(c) {
4205         if(rs1[i]!=rt1[i]||itype[i]!=LOAD) {
4206           if(!entry||entry[ra]!=agr) {
4207             if (opcode[i]==0x22||opcode[i]==0x26) {
4208               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4209             }else if (opcode[i]==0x1a||opcode[i]==0x1b) {
4210               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4211             }else{
4212               emit_movimm(constmap[i][rs]+offset,ra);
4213               regs[i].loadedconst|=1<<ra;
4214             }
4215           } // else did it in the previous cycle
4216         } // else load_consts already did it
4217       }
4218       if(offset&&!c&&rs1[i]) {
4219         if(rs>=0) {
4220           emit_addimm(rs,offset,ra);
4221         }else{
4222           emit_addimm(ra,offset,ra);
4223         }
4224       }
4225     }
4226   }
4227   // Preload constants for next instruction
4228   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) {
4229     int agr,ra;
4230     // Actual address
4231     agr=AGEN1+((i+1)&1);
4232     ra=get_reg(i_regs->regmap,agr);
4233     if(ra>=0) {
4234       int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
4235       int offset=imm[i+1];
4236       int c=(regs[i+1].wasconst>>rs)&1;
4237       if(c&&(rs1[i+1]!=rt1[i+1]||itype[i+1]!=LOAD)) {
4238         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
4239           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4240         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
4241           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4242         }else{
4243           emit_movimm(constmap[i+1][rs]+offset,ra);
4244           regs[i+1].loadedconst|=1<<ra;
4245         }
4246       }
4247       else if(rs1[i+1]==0) {
4248         // Using r0 as a base address
4249         if (opcode[i+1]==0x22||opcode[i+1]==0x26) {
4250           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4251         }else if (opcode[i+1]==0x1a||opcode[i+1]==0x1b) {
4252           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4253         }else{
4254           emit_movimm(offset,ra);
4255         }
4256       }
4257     }
4258   }
4259 }
4260
4261 static int get_final_value(int hr, int i, int *value)
4262 {
4263   int reg=regs[i].regmap[hr];
4264   while(i<slen-1) {
4265     if(regs[i+1].regmap[hr]!=reg) break;
4266     if(!((regs[i+1].isconst>>hr)&1)) break;
4267     if(bt[i+1]) break;
4268     i++;
4269   }
4270   if(i<slen-1) {
4271     if(itype[i]==UJUMP||itype[i]==RJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
4272       *value=constmap[i][hr];
4273       return 1;
4274     }
4275     if(!bt[i+1]) {
4276       if(itype[i+1]==UJUMP||itype[i+1]==RJUMP||itype[i+1]==CJUMP||itype[i+1]==SJUMP) {
4277         // Load in delay slot, out-of-order execution
4278         if(itype[i+2]==LOAD&&rs1[i+2]==reg&&rt1[i+2]==reg&&((regs[i+1].wasconst>>hr)&1))
4279         {
4280           // Precompute load address
4281           *value=constmap[i][hr]+imm[i+2];
4282           return 1;
4283         }
4284       }
4285       if(itype[i+1]==LOAD&&rs1[i+1]==reg&&rt1[i+1]==reg)
4286       {
4287         // Precompute load address
4288         *value=constmap[i][hr]+imm[i+1];
4289         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4290         return 1;
4291       }
4292     }
4293   }
4294   *value=constmap[i][hr];
4295   //printf("c=%lx\n",(long)constmap[i][hr]);
4296   if(i==slen-1) return 1;
4297   assert(reg < 64);
4298   return !((unneeded_reg[i+1]>>reg)&1);
4299 }
4300
4301 // Load registers with known constants
4302 static void load_consts(signed char pre[],signed char regmap[],int i)
4303 {
4304   int hr,hr2;
4305   // propagate loaded constant flags
4306   if(i==0||bt[i])
4307     regs[i].loadedconst=0;
4308   else {
4309     for(hr=0;hr<HOST_REGS;hr++) {
4310       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4311          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4312       {
4313         regs[i].loadedconst|=1<<hr;
4314       }
4315     }
4316   }
4317   // Load 32-bit regs
4318   for(hr=0;hr<HOST_REGS;hr++) {
4319     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4320       //if(entry[hr]!=regmap[hr]) {
4321       if(!((regs[i].loadedconst>>hr)&1)) {
4322         assert(regmap[hr]<64);
4323         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4324           int value,similar=0;
4325           if(get_final_value(hr,i,&value)) {
4326             // see if some other register has similar value
4327             for(hr2=0;hr2<HOST_REGS;hr2++) {
4328               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4329                 if(is_similar_value(value,constmap[i][hr2])) {
4330                   similar=1;
4331                   break;
4332                 }
4333               }
4334             }
4335             if(similar) {
4336               int value2;
4337               if(get_final_value(hr2,i,&value2)) // is this needed?
4338                 emit_movimm_from(value2,hr2,value,hr);
4339               else
4340                 emit_movimm(value,hr);
4341             }
4342             else if(value==0) {
4343               emit_zeroreg(hr);
4344             }
4345             else {
4346               emit_movimm(value,hr);
4347             }
4348           }
4349           regs[i].loadedconst|=1<<hr;
4350         }
4351       }
4352     }
4353   }
4354 }
4355
4356 void load_all_consts(signed char regmap[], u_int dirty, int i)
4357 {
4358   int hr;
4359   // Load 32-bit regs
4360   for(hr=0;hr<HOST_REGS;hr++) {
4361     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4362       assert(regmap[hr] < 64);
4363       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4364         int value=constmap[i][hr];
4365         if(value==0) {
4366           emit_zeroreg(hr);
4367         }
4368         else {
4369           emit_movimm(value,hr);
4370         }
4371       }
4372     }
4373   }
4374 }
4375
4376 // Write out all dirty registers (except cycle count)
4377 static void wb_dirtys(signed char i_regmap[],uint64_t i_dirty)
4378 {
4379   int hr;
4380   for(hr=0;hr<HOST_REGS;hr++) {
4381     if(hr!=EXCLUDE_REG) {
4382       if(i_regmap[hr]>0) {
4383         if(i_regmap[hr]!=CCREG) {
4384           if((i_dirty>>hr)&1) {
4385             assert(i_regmap[hr]<64);
4386             emit_storereg(i_regmap[hr],hr);
4387           }
4388         }
4389       }
4390     }
4391   }
4392 }
4393
4394 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4395 // This writes the registers not written by store_regs_bt
4396 void wb_needed_dirtys(signed char i_regmap[],uint64_t i_dirty,int addr)
4397 {
4398   int hr;
4399   int t=(addr-start)>>2;
4400   for(hr=0;hr<HOST_REGS;hr++) {
4401     if(hr!=EXCLUDE_REG) {
4402       if(i_regmap[hr]>0) {
4403         if(i_regmap[hr]!=CCREG) {
4404           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4405             if((i_dirty>>hr)&1) {
4406               assert(i_regmap[hr]<64);
4407               emit_storereg(i_regmap[hr],hr);
4408             }
4409           }
4410         }
4411       }
4412     }
4413   }
4414 }
4415
4416 // Load all registers (except cycle count)
4417 void load_all_regs(signed char i_regmap[])
4418 {
4419   int hr;
4420   for(hr=0;hr<HOST_REGS;hr++) {
4421     if(hr!=EXCLUDE_REG) {
4422       if(i_regmap[hr]==0) {
4423         emit_zeroreg(hr);
4424       }
4425       else
4426       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4427       {
4428         emit_loadreg(i_regmap[hr],hr);
4429       }
4430     }
4431   }
4432 }
4433
4434 // Load all current registers also needed by next instruction
4435 void load_needed_regs(signed char i_regmap[],signed char next_regmap[])
4436 {
4437   int hr;
4438   for(hr=0;hr<HOST_REGS;hr++) {
4439     if(hr!=EXCLUDE_REG) {
4440       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4441         if(i_regmap[hr]==0) {
4442           emit_zeroreg(hr);
4443         }
4444         else
4445         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4446         {
4447           emit_loadreg(i_regmap[hr],hr);
4448         }
4449       }
4450     }
4451   }
4452 }
4453
4454 // Load all regs, storing cycle count if necessary
4455 void load_regs_entry(int t)
4456 {
4457   int hr;
4458   if(is_ds[t]) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4459   else if(ccadj[t]) emit_addimm(HOST_CCREG,-CLOCK_ADJUST(ccadj[t]),HOST_CCREG);
4460   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4461     emit_storereg(CCREG,HOST_CCREG);
4462   }
4463   // Load 32-bit regs
4464   for(hr=0;hr<HOST_REGS;hr++) {
4465     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4466       if(regs[t].regmap_entry[hr]==0) {
4467         emit_zeroreg(hr);
4468       }
4469       else if(regs[t].regmap_entry[hr]!=CCREG)
4470       {
4471         emit_loadreg(regs[t].regmap_entry[hr],hr);
4472       }
4473     }
4474   }
4475 }
4476
4477 // Store dirty registers prior to branch
4478 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4479 {
4480   if(internal_branch(addr))
4481   {
4482     int t=(addr-start)>>2;
4483     int hr;
4484     for(hr=0;hr<HOST_REGS;hr++) {
4485       if(hr!=EXCLUDE_REG) {
4486         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4487           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4488             if((i_dirty>>hr)&1) {
4489               assert(i_regmap[hr]<64);
4490               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4491                 emit_storereg(i_regmap[hr],hr);
4492             }
4493           }
4494         }
4495       }
4496     }
4497   }
4498   else
4499   {
4500     // Branch out of this block, write out all dirty regs
4501     wb_dirtys(i_regmap,i_dirty);
4502   }
4503 }
4504
4505 // Load all needed registers for branch target
4506 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4507 {
4508   //if(addr>=start && addr<(start+slen*4))
4509   if(internal_branch(addr))
4510   {
4511     int t=(addr-start)>>2;
4512     int hr;
4513     // Store the cycle count before loading something else
4514     if(i_regmap[HOST_CCREG]!=CCREG) {
4515       assert(i_regmap[HOST_CCREG]==-1);
4516     }
4517     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4518       emit_storereg(CCREG,HOST_CCREG);
4519     }
4520     // Load 32-bit regs
4521     for(hr=0;hr<HOST_REGS;hr++) {
4522       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4523         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4524           if(regs[t].regmap_entry[hr]==0) {
4525             emit_zeroreg(hr);
4526           }
4527           else if(regs[t].regmap_entry[hr]!=CCREG)
4528           {
4529             emit_loadreg(regs[t].regmap_entry[hr],hr);
4530           }
4531         }
4532       }
4533     }
4534   }
4535 }
4536
4537 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4538 {
4539   if(addr>=start && addr<start+slen*4-4)
4540   {
4541     int t=(addr-start)>>2;
4542     int hr;
4543     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4544     for(hr=0;hr<HOST_REGS;hr++)
4545     {
4546       if(hr!=EXCLUDE_REG)
4547       {
4548         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4549         {
4550           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4551           {
4552             return 0;
4553           }
4554           else
4555           if((i_dirty>>hr)&1)
4556           {
4557             if(i_regmap[hr]<TEMPREG)
4558             {
4559               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4560                 return 0;
4561             }
4562             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4563             {
4564               assert(0);
4565             }
4566           }
4567         }
4568         else // Same register but is it 32-bit or dirty?
4569         if(i_regmap[hr]>=0)
4570         {
4571           if(!((regs[t].dirty>>hr)&1))
4572           {
4573             if((i_dirty>>hr)&1)
4574             {
4575               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4576               {
4577                 //printf("%x: dirty no match\n",addr);
4578                 return 0;
4579               }
4580             }
4581           }
4582         }
4583       }
4584     }
4585     // Delay slots are not valid branch targets
4586     //if(t>0&&(itype[t-1]==RJUMP||itype[t-1]==UJUMP||itype[t-1]==CJUMP||itype[t-1]==SJUMP)) return 0;
4587     // Delay slots require additional processing, so do not match
4588     if(is_ds[t]) return 0;
4589   }
4590   else
4591   {
4592     int hr;
4593     for(hr=0;hr<HOST_REGS;hr++)
4594     {
4595       if(hr!=EXCLUDE_REG)
4596       {
4597         if(i_regmap[hr]>=0)
4598         {
4599           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4600           {
4601             if((i_dirty>>hr)&1)
4602             {
4603               return 0;
4604             }
4605           }
4606         }
4607       }
4608     }
4609   }
4610   return 1;
4611 }
4612
4613 #ifdef DRC_DBG
4614 static void drc_dbg_emit_do_cmp(int i)
4615 {
4616   extern void do_insn_cmp();
4617   //extern int cycle;
4618   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4619
4620   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4621   save_regs(reglist);
4622   // write out changed consts to match the interpreter
4623   if (i > 0 && !bt[i]) {
4624     for (hr = 0; hr < HOST_REGS; hr++) {
4625       int reg = regs[i-1].regmap[hr];
4626       if (hr == EXCLUDE_REG || reg < 0)
4627         continue;
4628       if (!((regs[i-1].isconst >> hr) & 1))
4629         continue;
4630       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4631         continue;
4632       emit_movimm(constmap[i-1][hr],0);
4633       emit_storereg(reg, 0);
4634     }
4635   }
4636   emit_movimm(start+i*4,0);
4637   emit_writeword(0,&pcaddr);
4638   emit_far_call(do_insn_cmp);
4639   //emit_readword(&cycle,0);
4640   //emit_addimm(0,2,0);
4641   //emit_writeword(0,&cycle);
4642   (void)get_reg2;
4643   restore_regs(reglist);
4644   assem_debug("\\\\do_insn_cmp\n");
4645 }
4646 #else
4647 #define drc_dbg_emit_do_cmp(x)
4648 #endif
4649
4650 // Used when a branch jumps into the delay slot of another branch
4651 static void ds_assemble_entry(int i)
4652 {
4653   int t=(ba[i]-start)>>2;
4654   if (!instr_addr[t])
4655     instr_addr[t] = out;
4656   assem_debug("Assemble delay slot at %x\n",ba[i]);
4657   assem_debug("<->\n");
4658   drc_dbg_emit_do_cmp(t);
4659   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4660     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4661   load_regs(regs[t].regmap_entry,regs[t].regmap,rs1[t],rs2[t]);
4662   address_generation(t,&regs[t],regs[t].regmap_entry);
4663   if(itype[t]==STORE||itype[t]==STORELR||(opcode[t]&0x3b)==0x39||(opcode[t]&0x3b)==0x3a)
4664     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4665   is_delayslot=0;
4666   switch(itype[t]) {
4667     case ALU:
4668       alu_assemble(t,&regs[t]);break;
4669     case IMM16:
4670       imm16_assemble(t,&regs[t]);break;
4671     case SHIFT:
4672       shift_assemble(t,&regs[t]);break;
4673     case SHIFTIMM:
4674       shiftimm_assemble(t,&regs[t]);break;
4675     case LOAD:
4676       load_assemble(t,&regs[t]);break;
4677     case LOADLR:
4678       loadlr_assemble(t,&regs[t]);break;
4679     case STORE:
4680       store_assemble(t,&regs[t]);break;
4681     case STORELR:
4682       storelr_assemble(t,&regs[t]);break;
4683     case COP0:
4684       cop0_assemble(t,&regs[t]);break;
4685     case COP1:
4686       cop1_assemble(t,&regs[t]);break;
4687     case C1LS:
4688       c1ls_assemble(t,&regs[t]);break;
4689     case COP2:
4690       cop2_assemble(t,&regs[t]);break;
4691     case C2LS:
4692       c2ls_assemble(t,&regs[t]);break;
4693     case C2OP:
4694       c2op_assemble(t,&regs[t]);break;
4695     case MULTDIV:
4696       multdiv_assemble(t,&regs[t]);
4697       multdiv_prepare_stall(i,&regs[t]);
4698       break;
4699     case MOV:
4700       mov_assemble(t,&regs[t]);break;
4701     case SYSCALL:
4702     case HLECALL:
4703     case INTCALL:
4704     case SPAN:
4705     case UJUMP:
4706     case RJUMP:
4707     case CJUMP:
4708     case SJUMP:
4709       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4710   }
4711   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4712   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4713   if(internal_branch(ba[i]+4))
4714     assem_debug("branch: internal\n");
4715   else
4716     assem_debug("branch: external\n");
4717   assert(internal_branch(ba[i]+4));
4718   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4719   emit_jmp(0);
4720 }
4721
4722 static void emit_extjump(void *addr, u_int target)
4723 {
4724   emit_extjump2(addr, target, dyna_linker);
4725 }
4726
4727 static void emit_extjump_ds(void *addr, u_int target)
4728 {
4729   emit_extjump2(addr, target, dyna_linker_ds);
4730 }
4731
4732 // Load 2 immediates optimizing for small code size
4733 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4734 {
4735   emit_movimm(imm1,rt1);
4736   emit_movimm_from(imm1,rt1,imm2,rt2);
4737 }
4738
4739 void do_cc(int i,signed char i_regmap[],int *adj,int addr,int taken,int invert)
4740 {
4741   int count;
4742   void *jaddr;
4743   void *idle=NULL;
4744   int t=0;
4745   if(itype[i]==RJUMP)
4746   {
4747     *adj=0;
4748   }
4749   //if(ba[i]>=start && ba[i]<(start+slen*4))
4750   if(internal_branch(ba[i]))
4751   {
4752     t=(ba[i]-start)>>2;
4753     if(is_ds[t]) *adj=-1; // Branch into delay slot adds an extra cycle
4754     else *adj=ccadj[t];
4755   }
4756   else
4757   {
4758     *adj=0;
4759   }
4760   count=ccadj[i];
4761   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4762     // Idle loop
4763     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4764     idle=out;
4765     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4766     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4767     jaddr=out;
4768     emit_jmp(0);
4769   }
4770   else if(*adj==0||invert) {
4771     int cycles=CLOCK_ADJUST(count+2);
4772     // faster loop HACK
4773 #if 0
4774     if (t&&*adj) {
4775       int rel=t-i;
4776       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4777         cycles=CLOCK_ADJUST(*adj)+count+2-*adj;
4778     }
4779 #endif
4780     emit_addimm_and_set_flags(cycles,HOST_CCREG);
4781     jaddr=out;
4782     emit_jns(0);
4783   }
4784   else
4785   {
4786     emit_cmpimm(HOST_CCREG,-CLOCK_ADJUST(count+2));
4787     jaddr=out;
4788     emit_jns(0);
4789   }
4790   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:(count+2),i,addr,taken,0);
4791 }
4792
4793 static void do_ccstub(int n)
4794 {
4795   literal_pool(256);
4796   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4797   set_jump_target(stubs[n].addr, out);
4798   int i=stubs[n].b;
4799   if(stubs[n].d==NULLDS) {
4800     // Delay slot instruction is nullified ("likely" branch)
4801     wb_dirtys(regs[i].regmap,regs[i].dirty);
4802   }
4803   else if(stubs[n].d!=TAKEN) {
4804     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4805   }
4806   else {
4807     if(internal_branch(ba[i]))
4808       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4809   }
4810   if(stubs[n].c!=-1)
4811   {
4812     // Save PC as return address
4813     emit_movimm(stubs[n].c,EAX);
4814     emit_writeword(EAX,&pcaddr);
4815   }
4816   else
4817   {
4818     // Return address depends on which way the branch goes
4819     if(itype[i]==CJUMP||itype[i]==SJUMP)
4820     {
4821       int s1l=get_reg(branch_regs[i].regmap,rs1[i]);
4822       int s2l=get_reg(branch_regs[i].regmap,rs2[i]);
4823       if(rs1[i]==0)
4824       {
4825         s1l=s2l;
4826         s2l=-1;
4827       }
4828       else if(rs2[i]==0)
4829       {
4830         s2l=-1;
4831       }
4832       assert(s1l>=0);
4833       #ifdef DESTRUCTIVE_WRITEBACK
4834       if(rs1[i]) {
4835         if((branch_regs[i].dirty>>s1l)&&1)
4836           emit_loadreg(rs1[i],s1l);
4837       }
4838       else {
4839         if((branch_regs[i].dirty>>s1l)&1)
4840           emit_loadreg(rs2[i],s1l);
4841       }
4842       if(s2l>=0)
4843         if((branch_regs[i].dirty>>s2l)&1)
4844           emit_loadreg(rs2[i],s2l);
4845       #endif
4846       int hr=0;
4847       int addr=-1,alt=-1,ntaddr=-1;
4848       while(hr<HOST_REGS)
4849       {
4850         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4851            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4852            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4853         {
4854           addr=hr++;break;
4855         }
4856         hr++;
4857       }
4858       while(hr<HOST_REGS)
4859       {
4860         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4861            (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4862            (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4863         {
4864           alt=hr++;break;
4865         }
4866         hr++;
4867       }
4868       if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
4869       {
4870         while(hr<HOST_REGS)
4871         {
4872           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4873              (branch_regs[i].regmap[hr]&63)!=rs1[i] &&
4874              (branch_regs[i].regmap[hr]&63)!=rs2[i] )
4875           {
4876             ntaddr=hr;break;
4877           }
4878           hr++;
4879         }
4880         assert(hr<HOST_REGS);
4881       }
4882       if((opcode[i]&0x2f)==4) // BEQ
4883       {
4884         #ifdef HAVE_CMOV_IMM
4885         if(s2l>=0) emit_cmp(s1l,s2l);
4886         else emit_test(s1l,s1l);
4887         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4888         #else
4889         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4890         if(s2l>=0) emit_cmp(s1l,s2l);
4891         else emit_test(s1l,s1l);
4892         emit_cmovne_reg(alt,addr);
4893         #endif
4894       }
4895       if((opcode[i]&0x2f)==5) // BNE
4896       {
4897         #ifdef HAVE_CMOV_IMM
4898         if(s2l>=0) emit_cmp(s1l,s2l);
4899         else emit_test(s1l,s1l);
4900         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4901         #else
4902         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4903         if(s2l>=0) emit_cmp(s1l,s2l);
4904         else emit_test(s1l,s1l);
4905         emit_cmovne_reg(alt,addr);
4906         #endif
4907       }
4908       if((opcode[i]&0x2f)==6) // BLEZ
4909       {
4910         //emit_movimm(ba[i],alt);
4911         //emit_movimm(start+i*4+8,addr);
4912         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4913         emit_cmpimm(s1l,1);
4914         emit_cmovl_reg(alt,addr);
4915       }
4916       if((opcode[i]&0x2f)==7) // BGTZ
4917       {
4918         //emit_movimm(ba[i],addr);
4919         //emit_movimm(start+i*4+8,ntaddr);
4920         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
4921         emit_cmpimm(s1l,1);
4922         emit_cmovl_reg(ntaddr,addr);
4923       }
4924       if((opcode[i]==1)&&(opcode2[i]&0x2D)==0) // BLTZ
4925       {
4926         //emit_movimm(ba[i],alt);
4927         //emit_movimm(start+i*4+8,addr);
4928         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4929         emit_test(s1l,s1l);
4930         emit_cmovs_reg(alt,addr);
4931       }
4932       if((opcode[i]==1)&&(opcode2[i]&0x2D)==1) // BGEZ
4933       {
4934         //emit_movimm(ba[i],addr);
4935         //emit_movimm(start+i*4+8,alt);
4936         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4937         emit_test(s1l,s1l);
4938         emit_cmovs_reg(alt,addr);
4939       }
4940       if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
4941         if(source[i]&0x10000) // BC1T
4942         {
4943           //emit_movimm(ba[i],alt);
4944           //emit_movimm(start+i*4+8,addr);
4945           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
4946           emit_testimm(s1l,0x800000);
4947           emit_cmovne_reg(alt,addr);
4948         }
4949         else // BC1F
4950         {
4951           //emit_movimm(ba[i],addr);
4952           //emit_movimm(start+i*4+8,alt);
4953           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4954           emit_testimm(s1l,0x800000);
4955           emit_cmovne_reg(alt,addr);
4956         }
4957       }
4958       emit_writeword(addr,&pcaddr);
4959     }
4960     else
4961     if(itype[i]==RJUMP)
4962     {
4963       int r=get_reg(branch_regs[i].regmap,rs1[i]);
4964       if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
4965         r=get_reg(branch_regs[i].regmap,RTEMP);
4966       }
4967       emit_writeword(r,&pcaddr);
4968     }
4969     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
4970   }
4971   // Update cycle count
4972   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
4973   if(stubs[n].a) emit_addimm(HOST_CCREG,CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4974   emit_far_call(cc_interrupt);
4975   if(stubs[n].a) emit_addimm(HOST_CCREG,-CLOCK_ADJUST((signed int)stubs[n].a),HOST_CCREG);
4976   if(stubs[n].d==TAKEN) {
4977     if(internal_branch(ba[i]))
4978       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
4979     else if(itype[i]==RJUMP) {
4980       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
4981         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
4982       else
4983         emit_loadreg(rs1[i],get_reg(branch_regs[i].regmap,rs1[i]));
4984     }
4985   }else if(stubs[n].d==NOTTAKEN) {
4986     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
4987     else load_all_regs(branch_regs[i].regmap);
4988   }else if(stubs[n].d==NULLDS) {
4989     // Delay slot instruction is nullified ("likely" branch)
4990     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
4991     else load_all_regs(regs[i].regmap);
4992   }else{
4993     load_all_regs(branch_regs[i].regmap);
4994   }
4995   if (stubs[n].retaddr)
4996     emit_jmp(stubs[n].retaddr);
4997   else
4998     do_jump_vaddr(stubs[n].e);
4999 }
5000
5001 static void add_to_linker(void *addr, u_int target, int ext)
5002 {
5003   assert(linkcount < ARRAY_SIZE(link_addr));
5004   link_addr[linkcount].addr = addr;
5005   link_addr[linkcount].target = target;
5006   link_addr[linkcount].ext = ext;
5007   linkcount++;
5008 }
5009
5010 static void ujump_assemble_write_ra(int i)
5011 {
5012   int rt;
5013   unsigned int return_address;
5014   rt=get_reg(branch_regs[i].regmap,31);
5015   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]);
5016   //assert(rt>=0);
5017   return_address=start+i*4+8;
5018   if(rt>=0) {
5019     #ifdef USE_MINI_HT
5020     if(internal_branch(return_address)&&rt1[i+1]!=31) {
5021       int temp=-1; // note: must be ds-safe
5022       #ifdef HOST_TEMPREG
5023       temp=HOST_TEMPREG;
5024       #endif
5025       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5026       else emit_movimm(return_address,rt);
5027     }
5028     else
5029     #endif
5030     {
5031       #ifdef REG_PREFETCH
5032       if(temp>=0)
5033       {
5034         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5035       }
5036       #endif
5037       emit_movimm(return_address,rt); // PC into link register
5038       #ifdef IMM_PREFETCH
5039       emit_prefetch(hash_table_get(return_address));
5040       #endif
5041     }
5042   }
5043 }
5044
5045 static void ujump_assemble(int i,struct regstat *i_regs)
5046 {
5047   int ra_done=0;
5048   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5049   address_generation(i+1,i_regs,regs[i].regmap_entry);
5050   #ifdef REG_PREFETCH
5051   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5052   if(rt1[i]==31&&temp>=0)
5053   {
5054     signed char *i_regmap=i_regs->regmap;
5055     int return_address=start+i*4+8;
5056     if(get_reg(branch_regs[i].regmap,31)>0)
5057     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5058   }
5059   #endif
5060   if(rt1[i]==31&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
5061     ujump_assemble_write_ra(i); // writeback ra for DS
5062     ra_done=1;
5063   }
5064   ds_assemble(i+1,i_regs);
5065   uint64_t bc_unneeded=branch_regs[i].u;
5066   bc_unneeded|=1|(1LL<<rt1[i]);
5067   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5068   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5069   if(!ra_done&&rt1[i]==31)
5070     ujump_assemble_write_ra(i);
5071   int cc,adj;
5072   cc=get_reg(branch_regs[i].regmap,CCREG);
5073   assert(cc==HOST_CCREG);
5074   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5075   #ifdef REG_PREFETCH
5076   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
5077   #endif
5078   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5079   if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5080   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5081   if(internal_branch(ba[i]))
5082     assem_debug("branch: internal\n");
5083   else
5084     assem_debug("branch: external\n");
5085   if(internal_branch(ba[i])&&is_ds[(ba[i]-start)>>2]) {
5086     ds_assemble_entry(i);
5087   }
5088   else {
5089     add_to_linker(out,ba[i],internal_branch(ba[i]));
5090     emit_jmp(0);
5091   }
5092 }
5093
5094 static void rjump_assemble_write_ra(int i)
5095 {
5096   int rt,return_address;
5097   assert(rt1[i+1]!=rt1[i]);
5098   assert(rt2[i+1]!=rt1[i]);
5099   rt=get_reg(branch_regs[i].regmap,rt1[i]);
5100   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]);
5101   assert(rt>=0);
5102   return_address=start+i*4+8;
5103   #ifdef REG_PREFETCH
5104   if(temp>=0)
5105   {
5106     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5107   }
5108   #endif
5109   emit_movimm(return_address,rt); // PC into link register
5110   #ifdef IMM_PREFETCH
5111   emit_prefetch(hash_table_get(return_address));
5112   #endif
5113 }
5114
5115 static void rjump_assemble(int i,struct regstat *i_regs)
5116 {
5117   int temp;
5118   int rs,cc;
5119   int ra_done=0;
5120   rs=get_reg(branch_regs[i].regmap,rs1[i]);
5121   assert(rs>=0);
5122   if(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]) {
5123     // Delay slot abuse, make a copy of the branch address register
5124     temp=get_reg(branch_regs[i].regmap,RTEMP);
5125     assert(temp>=0);
5126     assert(regs[i].regmap[temp]==RTEMP);
5127     emit_mov(rs,temp);
5128     rs=temp;
5129   }
5130   address_generation(i+1,i_regs,regs[i].regmap_entry);
5131   #ifdef REG_PREFETCH
5132   if(rt1[i]==31)
5133   {
5134     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5135       signed char *i_regmap=i_regs->regmap;
5136       int return_address=start+i*4+8;
5137       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5138     }
5139   }
5140   #endif
5141   #ifdef USE_MINI_HT
5142   if(rs1[i]==31) {
5143     int rh=get_reg(regs[i].regmap,RHASH);
5144     if(rh>=0) do_preload_rhash(rh);
5145   }
5146   #endif
5147   if(rt1[i]!=0&&(rt1[i]==rs1[i+1]||rt1[i]==rs2[i+1])) {
5148     rjump_assemble_write_ra(i);
5149     ra_done=1;
5150   }
5151   ds_assemble(i+1,i_regs);
5152   uint64_t bc_unneeded=branch_regs[i].u;
5153   bc_unneeded|=1|(1LL<<rt1[i]);
5154   bc_unneeded&=~(1LL<<rs1[i]);
5155   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5156   load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],CCREG);
5157   if(!ra_done&&rt1[i]!=0)
5158     rjump_assemble_write_ra(i);
5159   cc=get_reg(branch_regs[i].regmap,CCREG);
5160   assert(cc==HOST_CCREG);
5161   (void)cc;
5162   #ifdef USE_MINI_HT
5163   int rh=get_reg(branch_regs[i].regmap,RHASH);
5164   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5165   if(rs1[i]==31) {
5166     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5167     do_preload_rhtbl(ht);
5168     do_rhash(rs,rh);
5169   }
5170   #endif
5171   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5172   #ifdef DESTRUCTIVE_WRITEBACK
5173   if((branch_regs[i].dirty>>rs)&1) {
5174     if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
5175       emit_loadreg(rs1[i],rs);
5176     }
5177   }
5178   #endif
5179   #ifdef REG_PREFETCH
5180   if(rt1[i]==31&&temp>=0) emit_prefetchreg(temp);
5181   #endif
5182   #ifdef USE_MINI_HT
5183   if(rs1[i]==31) {
5184     do_miniht_load(ht,rh);
5185   }
5186   #endif
5187   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5188   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5189   //assert(adj==0);
5190   emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5191   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5192   if(itype[i+1]==COP0&&(source[i+1]&0x3f)==0x10)
5193     // special case for RFE
5194     emit_jmp(0);
5195   else
5196     emit_jns(0);
5197   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5198   #ifdef USE_MINI_HT
5199   if(rs1[i]==31) {
5200     do_miniht_jump(rs,rh,ht);
5201   }
5202   else
5203   #endif
5204   {
5205     do_jump_vaddr(rs);
5206   }
5207   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5208   if(rt1[i]!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5209   #endif
5210 }
5211
5212 static void cjump_assemble(int i,struct regstat *i_regs)
5213 {
5214   signed char *i_regmap=i_regs->regmap;
5215   int cc;
5216   int match;
5217   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5218   assem_debug("match=%d\n",match);
5219   int s1l,s2l;
5220   int unconditional=0,nop=0;
5221   int invert=0;
5222   int internal=internal_branch(ba[i]);
5223   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5224   if(!match) invert=1;
5225   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5226   if(i>(ba[i]-start)>>2) invert=1;
5227   #endif
5228   #ifdef __aarch64__
5229   invert=1; // because of near cond. branches
5230   #endif
5231
5232   if(ooo[i]) {
5233     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5234     s2l=get_reg(branch_regs[i].regmap,rs2[i]);
5235   }
5236   else {
5237     s1l=get_reg(i_regmap,rs1[i]);
5238     s2l=get_reg(i_regmap,rs2[i]);
5239   }
5240   if(rs1[i]==0&&rs2[i]==0)
5241   {
5242     if(opcode[i]&1) nop=1;
5243     else unconditional=1;
5244     //assert(opcode[i]!=5);
5245     //assert(opcode[i]!=7);
5246     //assert(opcode[i]!=0x15);
5247     //assert(opcode[i]!=0x17);
5248   }
5249   else if(rs1[i]==0)
5250   {
5251     s1l=s2l;
5252     s2l=-1;
5253   }
5254   else if(rs2[i]==0)
5255   {
5256     s2l=-1;
5257   }
5258
5259   if(ooo[i]) {
5260     // Out of order execution (delay slot first)
5261     //printf("OOOE\n");
5262     address_generation(i+1,i_regs,regs[i].regmap_entry);
5263     ds_assemble(i+1,i_regs);
5264     int adj;
5265     uint64_t bc_unneeded=branch_regs[i].u;
5266     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5267     bc_unneeded|=1;
5268     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5269     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs2[i]);
5270     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5271     cc=get_reg(branch_regs[i].regmap,CCREG);
5272     assert(cc==HOST_CCREG);
5273     if(unconditional)
5274       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5275     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5276     //assem_debug("cycle count (adj)\n");
5277     if(unconditional) {
5278       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5279       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5280         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5281         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5282         if(internal)
5283           assem_debug("branch: internal\n");
5284         else
5285           assem_debug("branch: external\n");
5286         if(internal&&is_ds[(ba[i]-start)>>2]) {
5287           ds_assemble_entry(i);
5288         }
5289         else {
5290           add_to_linker(out,ba[i],internal);
5291           emit_jmp(0);
5292         }
5293         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5294         if(((u_int)out)&7) emit_addnop(0);
5295         #endif
5296       }
5297     }
5298     else if(nop) {
5299       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5300       void *jaddr=out;
5301       emit_jns(0);
5302       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5303     }
5304     else {
5305       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5306       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5307       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5308
5309       //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]);
5310       assert(s1l>=0);
5311       if(opcode[i]==4) // BEQ
5312       {
5313         if(s2l>=0) emit_cmp(s1l,s2l);
5314         else emit_test(s1l,s1l);
5315         if(invert){
5316           nottaken=out;
5317           emit_jne(DJT_1);
5318         }else{
5319           add_to_linker(out,ba[i],internal);
5320           emit_jeq(0);
5321         }
5322       }
5323       if(opcode[i]==5) // BNE
5324       {
5325         if(s2l>=0) emit_cmp(s1l,s2l);
5326         else emit_test(s1l,s1l);
5327         if(invert){
5328           nottaken=out;
5329           emit_jeq(DJT_1);
5330         }else{
5331           add_to_linker(out,ba[i],internal);
5332           emit_jne(0);
5333         }
5334       }
5335       if(opcode[i]==6) // BLEZ
5336       {
5337         emit_cmpimm(s1l,1);
5338         if(invert){
5339           nottaken=out;
5340           emit_jge(DJT_1);
5341         }else{
5342           add_to_linker(out,ba[i],internal);
5343           emit_jl(0);
5344         }
5345       }
5346       if(opcode[i]==7) // BGTZ
5347       {
5348         emit_cmpimm(s1l,1);
5349         if(invert){
5350           nottaken=out;
5351           emit_jl(DJT_1);
5352         }else{
5353           add_to_linker(out,ba[i],internal);
5354           emit_jge(0);
5355         }
5356       }
5357       if(invert) {
5358         if(taken) set_jump_target(taken, out);
5359         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5360         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5361           if(adj) {
5362             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5363             add_to_linker(out,ba[i],internal);
5364           }else{
5365             emit_addnop(13);
5366             add_to_linker(out,ba[i],internal*2);
5367           }
5368           emit_jmp(0);
5369         }else
5370         #endif
5371         {
5372           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5373           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5374           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5375           if(internal)
5376             assem_debug("branch: internal\n");
5377           else
5378             assem_debug("branch: external\n");
5379           if(internal&&is_ds[(ba[i]-start)>>2]) {
5380             ds_assemble_entry(i);
5381           }
5382           else {
5383             add_to_linker(out,ba[i],internal);
5384             emit_jmp(0);
5385           }
5386         }
5387         set_jump_target(nottaken, out);
5388       }
5389
5390       if(nottaken1) set_jump_target(nottaken1, out);
5391       if(adj) {
5392         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5393       }
5394     } // (!unconditional)
5395   } // if(ooo)
5396   else
5397   {
5398     // In-order execution (branch first)
5399     //if(likely[i]) printf("IOL\n");
5400     //else
5401     //printf("IOE\n");
5402     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5403     if(!unconditional&&!nop) {
5404       //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]);
5405       assert(s1l>=0);
5406       if((opcode[i]&0x2f)==4) // BEQ
5407       {
5408         if(s2l>=0) emit_cmp(s1l,s2l);
5409         else emit_test(s1l,s1l);
5410         nottaken=out;
5411         emit_jne(DJT_2);
5412       }
5413       if((opcode[i]&0x2f)==5) // BNE
5414       {
5415         if(s2l>=0) emit_cmp(s1l,s2l);
5416         else emit_test(s1l,s1l);
5417         nottaken=out;
5418         emit_jeq(DJT_2);
5419       }
5420       if((opcode[i]&0x2f)==6) // BLEZ
5421       {
5422         emit_cmpimm(s1l,1);
5423         nottaken=out;
5424         emit_jge(DJT_2);
5425       }
5426       if((opcode[i]&0x2f)==7) // BGTZ
5427       {
5428         emit_cmpimm(s1l,1);
5429         nottaken=out;
5430         emit_jl(DJT_2);
5431       }
5432     } // if(!unconditional)
5433     int adj;
5434     uint64_t ds_unneeded=branch_regs[i].u;
5435     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5436     ds_unneeded|=1;
5437     // branch taken
5438     if(!nop) {
5439       if(taken) set_jump_target(taken, out);
5440       assem_debug("1:\n");
5441       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5442       // load regs
5443       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5444       address_generation(i+1,&branch_regs[i],0);
5445       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5446       ds_assemble(i+1,&branch_regs[i]);
5447       cc=get_reg(branch_regs[i].regmap,CCREG);
5448       if(cc==-1) {
5449         emit_loadreg(CCREG,cc=HOST_CCREG);
5450         // CHECK: Is the following instruction (fall thru) allocated ok?
5451       }
5452       assert(cc==HOST_CCREG);
5453       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5454       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5455       assem_debug("cycle count (adj)\n");
5456       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5457       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5458       if(internal)
5459         assem_debug("branch: internal\n");
5460       else
5461         assem_debug("branch: external\n");
5462       if(internal&&is_ds[(ba[i]-start)>>2]) {
5463         ds_assemble_entry(i);
5464       }
5465       else {
5466         add_to_linker(out,ba[i],internal);
5467         emit_jmp(0);
5468       }
5469     }
5470     // branch not taken
5471     if(!unconditional) {
5472       if(nottaken1) set_jump_target(nottaken1, out);
5473       set_jump_target(nottaken, out);
5474       assem_debug("2:\n");
5475       if(!likely[i]) {
5476         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5477         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5478         address_generation(i+1,&branch_regs[i],0);
5479         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5480         ds_assemble(i+1,&branch_regs[i]);
5481       }
5482       cc=get_reg(branch_regs[i].regmap,CCREG);
5483       if(cc==-1&&!likely[i]) {
5484         // Cycle count isn't in a register, temporarily load it then write it out
5485         emit_loadreg(CCREG,HOST_CCREG);
5486         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5487         void *jaddr=out;
5488         emit_jns(0);
5489         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5490         emit_storereg(CCREG,HOST_CCREG);
5491       }
5492       else{
5493         cc=get_reg(i_regmap,CCREG);
5494         assert(cc==HOST_CCREG);
5495         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5496         void *jaddr=out;
5497         emit_jns(0);
5498         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5499       }
5500     }
5501   }
5502 }
5503
5504 static void sjump_assemble(int i,struct regstat *i_regs)
5505 {
5506   signed char *i_regmap=i_regs->regmap;
5507   int cc;
5508   int match;
5509   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5510   assem_debug("smatch=%d\n",match);
5511   int s1l;
5512   int unconditional=0,nevertaken=0;
5513   int invert=0;
5514   int internal=internal_branch(ba[i]);
5515   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5516   if(!match) invert=1;
5517   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5518   if(i>(ba[i]-start)>>2) invert=1;
5519   #endif
5520   #ifdef __aarch64__
5521   invert=1; // because of near cond. branches
5522   #endif
5523
5524   //if(opcode2[i]>=0x10) return; // FIXME (BxxZAL)
5525   //assert(opcode2[i]<0x10||rs1[i]==0); // FIXME (BxxZAL)
5526
5527   if(ooo[i]) {
5528     s1l=get_reg(branch_regs[i].regmap,rs1[i]);
5529   }
5530   else {
5531     s1l=get_reg(i_regmap,rs1[i]);
5532   }
5533   if(rs1[i]==0)
5534   {
5535     if(opcode2[i]&1) unconditional=1;
5536     else nevertaken=1;
5537     // These are never taken (r0 is never less than zero)
5538     //assert(opcode2[i]!=0);
5539     //assert(opcode2[i]!=2);
5540     //assert(opcode2[i]!=0x10);
5541     //assert(opcode2[i]!=0x12);
5542   }
5543
5544   if(ooo[i]) {
5545     // Out of order execution (delay slot first)
5546     //printf("OOOE\n");
5547     address_generation(i+1,i_regs,regs[i].regmap_entry);
5548     ds_assemble(i+1,i_regs);
5549     int adj;
5550     uint64_t bc_unneeded=branch_regs[i].u;
5551     bc_unneeded&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
5552     bc_unneeded|=1;
5553     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5554     load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i],rs1[i]);
5555     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5556     if(rt1[i]==31) {
5557       int rt,return_address;
5558       rt=get_reg(branch_regs[i].regmap,31);
5559       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]);
5560       if(rt>=0) {
5561         // Save the PC even if the branch is not taken
5562         return_address=start+i*4+8;
5563         emit_movimm(return_address,rt); // PC into link register
5564         #ifdef IMM_PREFETCH
5565         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5566         #endif
5567       }
5568     }
5569     cc=get_reg(branch_regs[i].regmap,CCREG);
5570     assert(cc==HOST_CCREG);
5571     if(unconditional)
5572       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5573     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5574     assem_debug("cycle count (adj)\n");
5575     if(unconditional) {
5576       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5577       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5578         if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5579         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5580         if(internal)
5581           assem_debug("branch: internal\n");
5582         else
5583           assem_debug("branch: external\n");
5584         if(internal&&is_ds[(ba[i]-start)>>2]) {
5585           ds_assemble_entry(i);
5586         }
5587         else {
5588           add_to_linker(out,ba[i],internal);
5589           emit_jmp(0);
5590         }
5591         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5592         if(((u_int)out)&7) emit_addnop(0);
5593         #endif
5594       }
5595     }
5596     else if(nevertaken) {
5597       emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5598       void *jaddr=out;
5599       emit_jns(0);
5600       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5601     }
5602     else {
5603       void *nottaken = NULL;
5604       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5605       if(adj&&!invert) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5606       {
5607         assert(s1l>=0);
5608         if((opcode2[i]&0xf)==0) // BLTZ/BLTZAL
5609         {
5610           emit_test(s1l,s1l);
5611           if(invert){
5612             nottaken=out;
5613             emit_jns(DJT_1);
5614           }else{
5615             add_to_linker(out,ba[i],internal);
5616             emit_js(0);
5617           }
5618         }
5619         if((opcode2[i]&0xf)==1) // BGEZ/BLTZAL
5620         {
5621           emit_test(s1l,s1l);
5622           if(invert){
5623             nottaken=out;
5624             emit_js(DJT_1);
5625           }else{
5626             add_to_linker(out,ba[i],internal);
5627             emit_jns(0);
5628           }
5629         }
5630       }
5631
5632       if(invert) {
5633         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5634         if(match&&(!internal||!is_ds[(ba[i]-start)>>2])) {
5635           if(adj) {
5636             emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5637             add_to_linker(out,ba[i],internal);
5638           }else{
5639             emit_addnop(13);
5640             add_to_linker(out,ba[i],internal*2);
5641           }
5642           emit_jmp(0);
5643         }else
5644         #endif
5645         {
5646           if(adj) emit_addimm(cc,-CLOCK_ADJUST(adj),cc);
5647           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5648           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5649           if(internal)
5650             assem_debug("branch: internal\n");
5651           else
5652             assem_debug("branch: external\n");
5653           if(internal&&is_ds[(ba[i]-start)>>2]) {
5654             ds_assemble_entry(i);
5655           }
5656           else {
5657             add_to_linker(out,ba[i],internal);
5658             emit_jmp(0);
5659           }
5660         }
5661         set_jump_target(nottaken, out);
5662       }
5663
5664       if(adj) {
5665         if(!invert) emit_addimm(cc,CLOCK_ADJUST(adj),cc);
5666       }
5667     } // (!unconditional)
5668   } // if(ooo)
5669   else
5670   {
5671     // In-order execution (branch first)
5672     //printf("IOE\n");
5673     void *nottaken = NULL;
5674     if(rt1[i]==31) {
5675       int rt,return_address;
5676       rt=get_reg(branch_regs[i].regmap,31);
5677       if(rt>=0) {
5678         // Save the PC even if the branch is not taken
5679         return_address=start+i*4+8;
5680         emit_movimm(return_address,rt); // PC into link register
5681         #ifdef IMM_PREFETCH
5682         emit_prefetch(hash_table_get(return_address));
5683         #endif
5684       }
5685     }
5686     if(!unconditional) {
5687       //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]);
5688         assert(s1l>=0);
5689         if((opcode2[i]&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5690         {
5691           emit_test(s1l,s1l);
5692           nottaken=out;
5693           emit_jns(DJT_1);
5694         }
5695         if((opcode2[i]&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5696         {
5697           emit_test(s1l,s1l);
5698           nottaken=out;
5699           emit_js(DJT_1);
5700         }
5701     } // if(!unconditional)
5702     int adj;
5703     uint64_t ds_unneeded=branch_regs[i].u;
5704     ds_unneeded&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
5705     ds_unneeded|=1;
5706     // branch taken
5707     if(!nevertaken) {
5708       //assem_debug("1:\n");
5709       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5710       // load regs
5711       load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5712       address_generation(i+1,&branch_regs[i],0);
5713       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5714       ds_assemble(i+1,&branch_regs[i]);
5715       cc=get_reg(branch_regs[i].regmap,CCREG);
5716       if(cc==-1) {
5717         emit_loadreg(CCREG,cc=HOST_CCREG);
5718         // CHECK: Is the following instruction (fall thru) allocated ok?
5719       }
5720       assert(cc==HOST_CCREG);
5721       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5722       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5723       assem_debug("cycle count (adj)\n");
5724       if(adj) emit_addimm(cc,CLOCK_ADJUST(ccadj[i]+2-adj),cc);
5725       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5726       if(internal)
5727         assem_debug("branch: internal\n");
5728       else
5729         assem_debug("branch: external\n");
5730       if(internal&&is_ds[(ba[i]-start)>>2]) {
5731         ds_assemble_entry(i);
5732       }
5733       else {
5734         add_to_linker(out,ba[i],internal);
5735         emit_jmp(0);
5736       }
5737     }
5738     // branch not taken
5739     if(!unconditional) {
5740       set_jump_target(nottaken, out);
5741       assem_debug("1:\n");
5742       if(!likely[i]) {
5743         wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5744         load_regs(regs[i].regmap,branch_regs[i].regmap,rs1[i+1],rs2[i+1]);
5745         address_generation(i+1,&branch_regs[i],0);
5746         load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5747         ds_assemble(i+1,&branch_regs[i]);
5748       }
5749       cc=get_reg(branch_regs[i].regmap,CCREG);
5750       if(cc==-1&&!likely[i]) {
5751         // Cycle count isn't in a register, temporarily load it then write it out
5752         emit_loadreg(CCREG,HOST_CCREG);
5753         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5754         void *jaddr=out;
5755         emit_jns(0);
5756         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5757         emit_storereg(CCREG,HOST_CCREG);
5758       }
5759       else{
5760         cc=get_reg(i_regmap,CCREG);
5761         assert(cc==HOST_CCREG);
5762         emit_addimm_and_set_flags(CLOCK_ADJUST(ccadj[i]+2),cc);
5763         void *jaddr=out;
5764         emit_jns(0);
5765         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,likely[i]?NULLDS:NOTTAKEN,0);
5766       }
5767     }
5768   }
5769 }
5770
5771 static void pagespan_assemble(int i,struct regstat *i_regs)
5772 {
5773   int s1l=get_reg(i_regs->regmap,rs1[i]);
5774   int s2l=get_reg(i_regs->regmap,rs2[i]);
5775   void *taken = NULL;
5776   void *nottaken = NULL;
5777   int unconditional=0;
5778   if(rs1[i]==0)
5779   {
5780     s1l=s2l;
5781     s2l=-1;
5782   }
5783   else if(rs2[i]==0)
5784   {
5785     s2l=-1;
5786   }
5787   int hr=0;
5788   int addr=-1,alt=-1,ntaddr=-1;
5789   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5790   else {
5791     while(hr<HOST_REGS)
5792     {
5793       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5794          (i_regs->regmap[hr]&63)!=rs1[i] &&
5795          (i_regs->regmap[hr]&63)!=rs2[i] )
5796       {
5797         addr=hr++;break;
5798       }
5799       hr++;
5800     }
5801   }
5802   while(hr<HOST_REGS)
5803   {
5804     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5805        (i_regs->regmap[hr]&63)!=rs1[i] &&
5806        (i_regs->regmap[hr]&63)!=rs2[i] )
5807     {
5808       alt=hr++;break;
5809     }
5810     hr++;
5811   }
5812   if((opcode[i]&0x2E)==6) // BLEZ/BGTZ needs another register
5813   {
5814     while(hr<HOST_REGS)
5815     {
5816       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5817          (i_regs->regmap[hr]&63)!=rs1[i] &&
5818          (i_regs->regmap[hr]&63)!=rs2[i] )
5819       {
5820         ntaddr=hr;break;
5821       }
5822       hr++;
5823     }
5824   }
5825   assert(hr<HOST_REGS);
5826   if((opcode[i]&0x2e)==4||opcode[i]==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5827     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5828   }
5829   emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i]+2),HOST_CCREG);
5830   if(opcode[i]==2) // J
5831   {
5832     unconditional=1;
5833   }
5834   if(opcode[i]==3) // JAL
5835   {
5836     // TODO: mini_ht
5837     int rt=get_reg(i_regs->regmap,31);
5838     emit_movimm(start+i*4+8,rt);
5839     unconditional=1;
5840   }
5841   if(opcode[i]==0&&(opcode2[i]&0x3E)==8) // JR/JALR
5842   {
5843     emit_mov(s1l,addr);
5844     if(opcode2[i]==9) // JALR
5845     {
5846       int rt=get_reg(i_regs->regmap,rt1[i]);
5847       emit_movimm(start+i*4+8,rt);
5848     }
5849   }
5850   if((opcode[i]&0x3f)==4) // BEQ
5851   {
5852     if(rs1[i]==rs2[i])
5853     {
5854       unconditional=1;
5855     }
5856     else
5857     #ifdef HAVE_CMOV_IMM
5858     if(1) {
5859       if(s2l>=0) emit_cmp(s1l,s2l);
5860       else emit_test(s1l,s1l);
5861       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5862     }
5863     else
5864     #endif
5865     {
5866       assert(s1l>=0);
5867       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5868       if(s2l>=0) emit_cmp(s1l,s2l);
5869       else emit_test(s1l,s1l);
5870       emit_cmovne_reg(alt,addr);
5871     }
5872   }
5873   if((opcode[i]&0x3f)==5) // BNE
5874   {
5875     #ifdef HAVE_CMOV_IMM
5876     if(s2l>=0) emit_cmp(s1l,s2l);
5877     else emit_test(s1l,s1l);
5878     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5879     #else
5880     assert(s1l>=0);
5881     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5882     if(s2l>=0) emit_cmp(s1l,s2l);
5883     else emit_test(s1l,s1l);
5884     emit_cmovne_reg(alt,addr);
5885     #endif
5886   }
5887   if((opcode[i]&0x3f)==0x14) // BEQL
5888   {
5889     if(s2l>=0) emit_cmp(s1l,s2l);
5890     else emit_test(s1l,s1l);
5891     if(nottaken) set_jump_target(nottaken, out);
5892     nottaken=out;
5893     emit_jne(0);
5894   }
5895   if((opcode[i]&0x3f)==0x15) // BNEL
5896   {
5897     if(s2l>=0) emit_cmp(s1l,s2l);
5898     else emit_test(s1l,s1l);
5899     nottaken=out;
5900     emit_jeq(0);
5901     if(taken) set_jump_target(taken, out);
5902   }
5903   if((opcode[i]&0x3f)==6) // BLEZ
5904   {
5905     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5906     emit_cmpimm(s1l,1);
5907     emit_cmovl_reg(alt,addr);
5908   }
5909   if((opcode[i]&0x3f)==7) // BGTZ
5910   {
5911     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5912     emit_cmpimm(s1l,1);
5913     emit_cmovl_reg(ntaddr,addr);
5914   }
5915   if((opcode[i]&0x3f)==0x16) // BLEZL
5916   {
5917     assert((opcode[i]&0x3f)!=0x16);
5918   }
5919   if((opcode[i]&0x3f)==0x17) // BGTZL
5920   {
5921     assert((opcode[i]&0x3f)!=0x17);
5922   }
5923   assert(opcode[i]!=1); // BLTZ/BGEZ
5924
5925   //FIXME: Check CSREG
5926   if(opcode[i]==0x11 && opcode2[i]==0x08 ) {
5927     if((source[i]&0x30000)==0) // BC1F
5928     {
5929       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5930       emit_testimm(s1l,0x800000);
5931       emit_cmovne_reg(alt,addr);
5932     }
5933     if((source[i]&0x30000)==0x10000) // BC1T
5934     {
5935       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5936       emit_testimm(s1l,0x800000);
5937       emit_cmovne_reg(alt,addr);
5938     }
5939     if((source[i]&0x30000)==0x20000) // BC1FL
5940     {
5941       emit_testimm(s1l,0x800000);
5942       nottaken=out;
5943       emit_jne(0);
5944     }
5945     if((source[i]&0x30000)==0x30000) // BC1TL
5946     {
5947       emit_testimm(s1l,0x800000);
5948       nottaken=out;
5949       emit_jeq(0);
5950     }
5951   }
5952
5953   assert(i_regs->regmap[HOST_CCREG]==CCREG);
5954   wb_dirtys(regs[i].regmap,regs[i].dirty);
5955   if(likely[i]||unconditional)
5956   {
5957     emit_movimm(ba[i],HOST_BTREG);
5958   }
5959   else if(addr!=HOST_BTREG)
5960   {
5961     emit_mov(addr,HOST_BTREG);
5962   }
5963   void *branch_addr=out;
5964   emit_jmp(0);
5965   int target_addr=start+i*4+5;
5966   void *stub=out;
5967   void *compiled_target_addr=check_addr(target_addr);
5968   emit_extjump_ds(branch_addr, target_addr);
5969   if(compiled_target_addr) {
5970     set_jump_target(branch_addr, compiled_target_addr);
5971     add_link(target_addr,stub);
5972   }
5973   else set_jump_target(branch_addr, stub);
5974   if(likely[i]) {
5975     // Not-taken path
5976     set_jump_target(nottaken, out);
5977     wb_dirtys(regs[i].regmap,regs[i].dirty);
5978     void *branch_addr=out;
5979     emit_jmp(0);
5980     int target_addr=start+i*4+8;
5981     void *stub=out;
5982     void *compiled_target_addr=check_addr(target_addr);
5983     emit_extjump_ds(branch_addr, target_addr);
5984     if(compiled_target_addr) {
5985       set_jump_target(branch_addr, compiled_target_addr);
5986       add_link(target_addr,stub);
5987     }
5988     else set_jump_target(branch_addr, stub);
5989   }
5990 }
5991
5992 // Assemble the delay slot for the above
5993 static void pagespan_ds()
5994 {
5995   assem_debug("initial delay slot:\n");
5996   u_int vaddr=start+1;
5997   u_int page=get_page(vaddr);
5998   u_int vpage=get_vpage(vaddr);
5999   ll_add(jump_dirty+vpage,vaddr,(void *)out);
6000   do_dirty_stub_ds();
6001   ll_add(jump_in+page,vaddr,(void *)out);
6002   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
6003   if(regs[0].regmap[HOST_CCREG]!=CCREG)
6004     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
6005   if(regs[0].regmap[HOST_BTREG]!=BTREG)
6006     emit_writeword(HOST_BTREG,&branch_target);
6007   load_regs(regs[0].regmap_entry,regs[0].regmap,rs1[0],rs2[0]);
6008   address_generation(0,&regs[0],regs[0].regmap_entry);
6009   if(itype[0]==STORE||itype[0]==STORELR||(opcode[0]&0x3b)==0x39||(opcode[0]&0x3b)==0x3a)
6010     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
6011   is_delayslot=0;
6012   switch(itype[0]) {
6013     case ALU:
6014       alu_assemble(0,&regs[0]);break;
6015     case IMM16:
6016       imm16_assemble(0,&regs[0]);break;
6017     case SHIFT:
6018       shift_assemble(0,&regs[0]);break;
6019     case SHIFTIMM:
6020       shiftimm_assemble(0,&regs[0]);break;
6021     case LOAD:
6022       load_assemble(0,&regs[0]);break;
6023     case LOADLR:
6024       loadlr_assemble(0,&regs[0]);break;
6025     case STORE:
6026       store_assemble(0,&regs[0]);break;
6027     case STORELR:
6028       storelr_assemble(0,&regs[0]);break;
6029     case COP0:
6030       cop0_assemble(0,&regs[0]);break;
6031     case COP1:
6032       cop1_assemble(0,&regs[0]);break;
6033     case C1LS:
6034       c1ls_assemble(0,&regs[0]);break;
6035     case COP2:
6036       cop2_assemble(0,&regs[0]);break;
6037     case C2LS:
6038       c2ls_assemble(0,&regs[0]);break;
6039     case C2OP:
6040       c2op_assemble(0,&regs[0]);break;
6041     case MULTDIV:
6042       multdiv_assemble(0,&regs[0]);
6043       multdiv_prepare_stall(0,&regs[0]);
6044       break;
6045     case MOV:
6046       mov_assemble(0,&regs[0]);break;
6047     case SYSCALL:
6048     case HLECALL:
6049     case INTCALL:
6050     case SPAN:
6051     case UJUMP:
6052     case RJUMP:
6053     case CJUMP:
6054     case SJUMP:
6055       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
6056   }
6057   int btaddr=get_reg(regs[0].regmap,BTREG);
6058   if(btaddr<0) {
6059     btaddr=get_reg(regs[0].regmap,-1);
6060     emit_readword(&branch_target,btaddr);
6061   }
6062   assert(btaddr!=HOST_CCREG);
6063   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6064 #ifdef HOST_IMM8
6065   host_tempreg_acquire();
6066   emit_movimm(start+4,HOST_TEMPREG);
6067   emit_cmp(btaddr,HOST_TEMPREG);
6068   host_tempreg_release();
6069 #else
6070   emit_cmpimm(btaddr,start+4);
6071 #endif
6072   void *branch = out;
6073   emit_jeq(0);
6074   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6075   do_jump_vaddr(btaddr);
6076   set_jump_target(branch, out);
6077   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6078   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6079 }
6080
6081 // Basic liveness analysis for MIPS registers
6082 void unneeded_registers(int istart,int iend,int r)
6083 {
6084   int i;
6085   uint64_t u,gte_u,b,gte_b;
6086   uint64_t temp_u,temp_gte_u=0;
6087   uint64_t gte_u_unknown=0;
6088   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6089     gte_u_unknown=~0ll;
6090   if(iend==slen-1) {
6091     u=1;
6092     gte_u=gte_u_unknown;
6093   }else{
6094     //u=unneeded_reg[iend+1];
6095     u=1;
6096     gte_u=gte_unneeded[iend+1];
6097   }
6098
6099   for (i=iend;i>=istart;i--)
6100   {
6101     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6102     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6103     {
6104       // If subroutine call, flag return address as a possible branch target
6105       if(rt1[i]==31 && i<slen-2) bt[i+2]=1;
6106
6107       if(ba[i]<start || ba[i]>=(start+slen*4))
6108       {
6109         // Branch out of this block, flush all regs
6110         u=1;
6111         gte_u=gte_u_unknown;
6112         branch_unneeded_reg[i]=u;
6113         // Merge in delay slot
6114         u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6115         u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6116         u|=1;
6117         gte_u|=gte_rt[i+1];
6118         gte_u&=~gte_rs[i+1];
6119         // If branch is "likely" (and conditional)
6120         // then we skip the delay slot on the fall-thru path
6121         if(likely[i]) {
6122           if(i<slen-1) {
6123             u&=unneeded_reg[i+2];
6124             gte_u&=gte_unneeded[i+2];
6125           }
6126           else
6127           {
6128             u=1;
6129             gte_u=gte_u_unknown;
6130           }
6131         }
6132       }
6133       else
6134       {
6135         // Internal branch, flag target
6136         bt[(ba[i]-start)>>2]=1;
6137         if(ba[i]<=start+i*4) {
6138           // Backward branch
6139           if(is_ujump(i))
6140           {
6141             // Unconditional branch
6142             temp_u=1;
6143             temp_gte_u=0;
6144           } else {
6145             // Conditional branch (not taken case)
6146             temp_u=unneeded_reg[i+2];
6147             temp_gte_u&=gte_unneeded[i+2];
6148           }
6149           // Merge in delay slot
6150           temp_u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6151           temp_u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6152           temp_u|=1;
6153           temp_gte_u|=gte_rt[i+1];
6154           temp_gte_u&=~gte_rs[i+1];
6155           // If branch is "likely" (and conditional)
6156           // then we skip the delay slot on the fall-thru path
6157           if(likely[i]) {
6158             if(i<slen-1) {
6159               temp_u&=unneeded_reg[i+2];
6160               temp_gte_u&=gte_unneeded[i+2];
6161             }
6162             else
6163             {
6164               temp_u=1;
6165               temp_gte_u=gte_u_unknown;
6166             }
6167           }
6168           temp_u|=(1LL<<rt1[i])|(1LL<<rt2[i]);
6169           temp_u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
6170           temp_u|=1;
6171           temp_gte_u|=gte_rt[i];
6172           temp_gte_u&=~gte_rs[i];
6173           unneeded_reg[i]=temp_u;
6174           gte_unneeded[i]=temp_gte_u;
6175           // Only go three levels deep.  This recursion can take an
6176           // excessive amount of time if there are a lot of nested loops.
6177           if(r<2) {
6178             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6179           }else{
6180             unneeded_reg[(ba[i]-start)>>2]=1;
6181             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6182           }
6183         } /*else*/ if(1) {
6184           if (is_ujump(i))
6185           {
6186             // Unconditional branch
6187             u=unneeded_reg[(ba[i]-start)>>2];
6188             gte_u=gte_unneeded[(ba[i]-start)>>2];
6189             branch_unneeded_reg[i]=u;
6190             // Merge in delay slot
6191             u|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6192             u&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6193             u|=1;
6194             gte_u|=gte_rt[i+1];
6195             gte_u&=~gte_rs[i+1];
6196           } else {
6197             // Conditional branch
6198             b=unneeded_reg[(ba[i]-start)>>2];
6199             gte_b=gte_unneeded[(ba[i]-start)>>2];
6200             branch_unneeded_reg[i]=b;
6201             // Branch delay slot
6202             b|=(1LL<<rt1[i+1])|(1LL<<rt2[i+1]);
6203             b&=~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
6204             b|=1;
6205             gte_b|=gte_rt[i+1];
6206             gte_b&=~gte_rs[i+1];
6207             // If branch is "likely" then we skip the
6208             // delay slot on the fall-thru path
6209             if(likely[i]) {
6210               u=b;
6211               gte_u=gte_b;
6212               if(i<slen-1) {
6213                 u&=unneeded_reg[i+2];
6214                 gte_u&=gte_unneeded[i+2];
6215               }
6216             } else {
6217               u&=b;
6218               gte_u&=gte_b;
6219             }
6220             if(i<slen-1) {
6221               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6222             } else {
6223               branch_unneeded_reg[i]=1;
6224             }
6225           }
6226         }
6227       }
6228     }
6229     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6230     {
6231       // SYSCALL instruction (software interrupt)
6232       u=1;
6233     }
6234     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6235     {
6236       // ERET instruction (return from interrupt)
6237       u=1;
6238     }
6239     //u=1; // DEBUG
6240     // Written registers are unneeded
6241     u|=1LL<<rt1[i];
6242     u|=1LL<<rt2[i];
6243     gte_u|=gte_rt[i];
6244     // Accessed registers are needed
6245     u&=~(1LL<<rs1[i]);
6246     u&=~(1LL<<rs2[i]);
6247     gte_u&=~gte_rs[i];
6248     if(gte_rs[i]&&rt1[i]&&(unneeded_reg[i+1]&(1ll<<rt1[i])))
6249       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6250     // Source-target dependencies
6251     // R0 is always unneeded
6252     u|=1;
6253     // Save it
6254     unneeded_reg[i]=u;
6255     gte_unneeded[i]=gte_u;
6256     /*
6257     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6258     printf("U:");
6259     int r;
6260     for(r=1;r<=CCREG;r++) {
6261       if((unneeded_reg[i]>>r)&1) {
6262         if(r==HIREG) printf(" HI");
6263         else if(r==LOREG) printf(" LO");
6264         else printf(" r%d",r);
6265       }
6266     }
6267     printf("\n");
6268     */
6269   }
6270 }
6271
6272 // Write back dirty registers as soon as we will no longer modify them,
6273 // so that we don't end up with lots of writes at the branches.
6274 void clean_registers(int istart,int iend,int wr)
6275 {
6276   int i;
6277   int r;
6278   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6279   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6280   if(iend==slen-1) {
6281     will_dirty_i=will_dirty_next=0;
6282     wont_dirty_i=wont_dirty_next=0;
6283   }else{
6284     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6285     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6286   }
6287   for (i=iend;i>=istart;i--)
6288   {
6289     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6290     {
6291       if(ba[i]<start || ba[i]>=(start+slen*4))
6292       {
6293         // Branch out of this block, flush all regs
6294         if (is_ujump(i))
6295         {
6296           // Unconditional branch
6297           will_dirty_i=0;
6298           wont_dirty_i=0;
6299           // Merge in delay slot (will dirty)
6300           for(r=0;r<HOST_REGS;r++) {
6301             if(r!=EXCLUDE_REG) {
6302               if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6303               if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6304               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6305               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6306               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6307               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6308               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6309               if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6310               if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6311               if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6312               if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6313               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6314               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6315               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6316             }
6317           }
6318         }
6319         else
6320         {
6321           // Conditional branch
6322           will_dirty_i=0;
6323           wont_dirty_i=wont_dirty_next;
6324           // Merge in delay slot (will dirty)
6325           for(r=0;r<HOST_REGS;r++) {
6326             if(r!=EXCLUDE_REG) {
6327               if(!likely[i]) {
6328                 // Might not dirty if likely branch is not taken
6329                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6330                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6331                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6332                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6333                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6334                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6335                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6336                 //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6337                 //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6338                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6339                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6340                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6341                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6342                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6343               }
6344             }
6345           }
6346         }
6347         // Merge in delay slot (wont dirty)
6348         for(r=0;r<HOST_REGS;r++) {
6349           if(r!=EXCLUDE_REG) {
6350             if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6351             if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6352             if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6353             if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6354             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6355             if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6356             if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6357             if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6358             if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6359             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6360           }
6361         }
6362         if(wr) {
6363           #ifndef DESTRUCTIVE_WRITEBACK
6364           branch_regs[i].dirty&=wont_dirty_i;
6365           #endif
6366           branch_regs[i].dirty|=will_dirty_i;
6367         }
6368       }
6369       else
6370       {
6371         // Internal branch
6372         if(ba[i]<=start+i*4) {
6373           // Backward branch
6374           if (is_ujump(i))
6375           {
6376             // Unconditional branch
6377             temp_will_dirty=0;
6378             temp_wont_dirty=0;
6379             // Merge in delay slot (will dirty)
6380             for(r=0;r<HOST_REGS;r++) {
6381               if(r!=EXCLUDE_REG) {
6382                 if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6383                 if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6384                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6385                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6386                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6387                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6388                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6389                 if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6390                 if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6391                 if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6392                 if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6393                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6394                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6395                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6396               }
6397             }
6398           } else {
6399             // Conditional branch (not taken case)
6400             temp_will_dirty=will_dirty_next;
6401             temp_wont_dirty=wont_dirty_next;
6402             // Merge in delay slot (will dirty)
6403             for(r=0;r<HOST_REGS;r++) {
6404               if(r!=EXCLUDE_REG) {
6405                 if(!likely[i]) {
6406                   // Will not dirty if likely branch is not taken
6407                   if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6408                   if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6409                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6410                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6411                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6412                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6413                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6414                   //if((regs[i].regmap[r]&63)==rt1[i]) temp_will_dirty|=1<<r;
6415                   //if((regs[i].regmap[r]&63)==rt2[i]) temp_will_dirty|=1<<r;
6416                   if((regs[i].regmap[r]&63)==rt1[i+1]) temp_will_dirty|=1<<r;
6417                   if((regs[i].regmap[r]&63)==rt2[i+1]) temp_will_dirty|=1<<r;
6418                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6419                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6420                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6421                 }
6422               }
6423             }
6424           }
6425           // Merge in delay slot (wont dirty)
6426           for(r=0;r<HOST_REGS;r++) {
6427             if(r!=EXCLUDE_REG) {
6428               if((regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6429               if((regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6430               if((regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6431               if((regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6432               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6433               if((branch_regs[i].regmap[r]&63)==rt1[i]) temp_wont_dirty|=1<<r;
6434               if((branch_regs[i].regmap[r]&63)==rt2[i]) temp_wont_dirty|=1<<r;
6435               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) temp_wont_dirty|=1<<r;
6436               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) temp_wont_dirty|=1<<r;
6437               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6438             }
6439           }
6440           // Deal with changed mappings
6441           if(i<iend) {
6442             for(r=0;r<HOST_REGS;r++) {
6443               if(r!=EXCLUDE_REG) {
6444                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6445                   temp_will_dirty&=~(1<<r);
6446                   temp_wont_dirty&=~(1<<r);
6447                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6448                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6449                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6450                   } else {
6451                     temp_will_dirty|=1<<r;
6452                     temp_wont_dirty|=1<<r;
6453                   }
6454                 }
6455               }
6456             }
6457           }
6458           if(wr) {
6459             will_dirty[i]=temp_will_dirty;
6460             wont_dirty[i]=temp_wont_dirty;
6461             clean_registers((ba[i]-start)>>2,i-1,0);
6462           }else{
6463             // Limit recursion.  It can take an excessive amount
6464             // of time if there are a lot of nested loops.
6465             will_dirty[(ba[i]-start)>>2]=0;
6466             wont_dirty[(ba[i]-start)>>2]=-1;
6467           }
6468         }
6469         /*else*/ if(1)
6470         {
6471           if (is_ujump(i))
6472           {
6473             // Unconditional branch
6474             will_dirty_i=0;
6475             wont_dirty_i=0;
6476           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6477             for(r=0;r<HOST_REGS;r++) {
6478               if(r!=EXCLUDE_REG) {
6479                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6480                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6481                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6482                 }
6483                 if(branch_regs[i].regmap[r]>=0) {
6484                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6485                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6486                 }
6487               }
6488             }
6489           //}
6490             // Merge in delay slot
6491             for(r=0;r<HOST_REGS;r++) {
6492               if(r!=EXCLUDE_REG) {
6493                 if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6494                 if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6495                 if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6496                 if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6497                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6498                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6499                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6500                 if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6501                 if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6502                 if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6503                 if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6504                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6505                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6506                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6507               }
6508             }
6509           } else {
6510             // Conditional branch
6511             will_dirty_i=will_dirty_next;
6512             wont_dirty_i=wont_dirty_next;
6513           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6514             for(r=0;r<HOST_REGS;r++) {
6515               if(r!=EXCLUDE_REG) {
6516                 signed char target_reg=branch_regs[i].regmap[r];
6517                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6518                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6519                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6520                 }
6521                 else if(target_reg>=0) {
6522                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6523                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6524                 }
6525                 // Treat delay slot as part of branch too
6526                 /*if(regs[i+1].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6527                   will_dirty[i+1]&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6528                   wont_dirty[i+1]|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6529                 }
6530                 else
6531                 {
6532                   will_dirty[i+1]&=~(1<<r);
6533                 }*/
6534               }
6535             }
6536           //}
6537             // Merge in delay slot
6538             for(r=0;r<HOST_REGS;r++) {
6539               if(r!=EXCLUDE_REG) {
6540                 if(!likely[i]) {
6541                   // Might not dirty if likely branch is not taken
6542                   if((branch_regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6543                   if((branch_regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6544                   if((branch_regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6545                   if((branch_regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6546                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6547                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6548                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6549                   //if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6550                   //if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6551                   if((regs[i].regmap[r]&63)==rt1[i+1]) will_dirty_i|=1<<r;
6552                   if((regs[i].regmap[r]&63)==rt2[i+1]) will_dirty_i|=1<<r;
6553                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6554                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6555                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6556                 }
6557               }
6558             }
6559           }
6560           // Merge in delay slot (won't dirty)
6561           for(r=0;r<HOST_REGS;r++) {
6562             if(r!=EXCLUDE_REG) {
6563               if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6564               if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6565               if((regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6566               if((regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6567               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6568               if((branch_regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6569               if((branch_regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6570               if((branch_regs[i].regmap[r]&63)==rt1[i+1]) wont_dirty_i|=1<<r;
6571               if((branch_regs[i].regmap[r]&63)==rt2[i+1]) wont_dirty_i|=1<<r;
6572               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6573             }
6574           }
6575           if(wr) {
6576             #ifndef DESTRUCTIVE_WRITEBACK
6577             branch_regs[i].dirty&=wont_dirty_i;
6578             #endif
6579             branch_regs[i].dirty|=will_dirty_i;
6580           }
6581         }
6582       }
6583     }
6584     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
6585     {
6586       // SYSCALL instruction (software interrupt)
6587       will_dirty_i=0;
6588       wont_dirty_i=0;
6589     }
6590     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
6591     {
6592       // ERET instruction (return from interrupt)
6593       will_dirty_i=0;
6594       wont_dirty_i=0;
6595     }
6596     will_dirty_next=will_dirty_i;
6597     wont_dirty_next=wont_dirty_i;
6598     for(r=0;r<HOST_REGS;r++) {
6599       if(r!=EXCLUDE_REG) {
6600         if((regs[i].regmap[r]&63)==rt1[i]) will_dirty_i|=1<<r;
6601         if((regs[i].regmap[r]&63)==rt2[i]) will_dirty_i|=1<<r;
6602         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6603         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6604         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6605         if((regs[i].regmap[r]&63)==rt1[i]) wont_dirty_i|=1<<r;
6606         if((regs[i].regmap[r]&63)==rt2[i]) wont_dirty_i|=1<<r;
6607         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6608         if(i>istart) {
6609           if(itype[i]!=RJUMP&&itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP)
6610           {
6611             // Don't store a register immediately after writing it,
6612             // may prevent dual-issue.
6613             if((regs[i].regmap[r]&63)==rt1[i-1]) wont_dirty_i|=1<<r;
6614             if((regs[i].regmap[r]&63)==rt2[i-1]) wont_dirty_i|=1<<r;
6615           }
6616         }
6617       }
6618     }
6619     // Save it
6620     will_dirty[i]=will_dirty_i;
6621     wont_dirty[i]=wont_dirty_i;
6622     // Mark registers that won't be dirtied as not dirty
6623     if(wr) {
6624       /*printf("wr (%d,%d) %x will:",istart,iend,start+i*4);
6625       for(r=0;r<HOST_REGS;r++) {
6626         if((will_dirty_i>>r)&1) {
6627           printf(" r%d",r);
6628         }
6629       }
6630       printf("\n");*/
6631
6632       //if(i==istart||(itype[i-1]!=RJUMP&&itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP)) {
6633         regs[i].dirty|=will_dirty_i;
6634         #ifndef DESTRUCTIVE_WRITEBACK
6635         regs[i].dirty&=wont_dirty_i;
6636         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
6637         {
6638           if (i < iend-1 && !is_ujump(i)) {
6639             for(r=0;r<HOST_REGS;r++) {
6640               if(r!=EXCLUDE_REG) {
6641                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6642                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6643                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6644               }
6645             }
6646           }
6647         }
6648         else
6649         {
6650           if(i<iend) {
6651             for(r=0;r<HOST_REGS;r++) {
6652               if(r!=EXCLUDE_REG) {
6653                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6654                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6655                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6656               }
6657             }
6658           }
6659         }
6660         #endif
6661       //}
6662     }
6663     // Deal with changed mappings
6664     temp_will_dirty=will_dirty_i;
6665     temp_wont_dirty=wont_dirty_i;
6666     for(r=0;r<HOST_REGS;r++) {
6667       if(r!=EXCLUDE_REG) {
6668         int nr;
6669         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6670           if(wr) {
6671             #ifndef DESTRUCTIVE_WRITEBACK
6672             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6673             #endif
6674             regs[i].wasdirty|=will_dirty_i&(1<<r);
6675           }
6676         }
6677         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6678           // Register moved to a different register
6679           will_dirty_i&=~(1<<r);
6680           wont_dirty_i&=~(1<<r);
6681           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6682           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6683           if(wr) {
6684             #ifndef DESTRUCTIVE_WRITEBACK
6685             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6686             #endif
6687             regs[i].wasdirty|=will_dirty_i&(1<<r);
6688           }
6689         }
6690         else {
6691           will_dirty_i&=~(1<<r);
6692           wont_dirty_i&=~(1<<r);
6693           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6694             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6695             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6696           } else {
6697             wont_dirty_i|=1<<r;
6698             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6699           }
6700         }
6701       }
6702     }
6703   }
6704 }
6705
6706 #ifdef DISASM
6707   /* disassembly */
6708 void disassemble_inst(int i)
6709 {
6710     if (bt[i]) printf("*"); else printf(" ");
6711     switch(itype[i]) {
6712       case UJUMP:
6713         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6714       case CJUMP:
6715         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;
6716       case SJUMP:
6717         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;
6718       case RJUMP:
6719         if (opcode[i]==0x9&&rt1[i]!=31)
6720           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i]);
6721         else
6722           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6723         break;
6724       case SPAN:
6725         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],rs1[i],rs2[i],ba[i]);break;
6726       case IMM16:
6727         if(opcode[i]==0xf) //LUI
6728           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],rt1[i],imm[i]&0xffff);
6729         else
6730           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6731         break;
6732       case LOAD:
6733       case LOADLR:
6734         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6735         break;
6736       case STORE:
6737       case STORELR:
6738         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],rs2[i],rs1[i],imm[i]);
6739         break;
6740       case ALU:
6741       case SHIFT:
6742         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],rt1[i],rs1[i],rs2[i]);
6743         break;
6744       case MULTDIV:
6745         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],rs1[i],rs2[i]);
6746         break;
6747       case SHIFTIMM:
6748         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],rt1[i],rs1[i],imm[i]);
6749         break;
6750       case MOV:
6751         if((opcode2[i]&0x1d)==0x10)
6752           printf (" %x: %s r%d\n",start+i*4,insn[i],rt1[i]);
6753         else if((opcode2[i]&0x1d)==0x11)
6754           printf (" %x: %s r%d\n",start+i*4,insn[i],rs1[i]);
6755         else
6756           printf (" %x: %s\n",start+i*4,insn[i]);
6757         break;
6758       case COP0:
6759         if(opcode2[i]==0)
6760           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC0
6761         else if(opcode2[i]==4)
6762           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC0
6763         else printf (" %x: %s\n",start+i*4,insn[i]);
6764         break;
6765       case COP1:
6766         if(opcode2[i]<3)
6767           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC1
6768         else if(opcode2[i]>3)
6769           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC1
6770         else printf (" %x: %s\n",start+i*4,insn[i]);
6771         break;
6772       case COP2:
6773         if(opcode2[i]<3)
6774           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rt1[i],(source[i]>>11)&0x1f); // MFC2
6775         else if(opcode2[i]>3)
6776           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],rs1[i],(source[i]>>11)&0x1f); // MTC2
6777         else printf (" %x: %s\n",start+i*4,insn[i]);
6778         break;
6779       case C1LS:
6780         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6781         break;
6782       case C2LS:
6783         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,rs1[i],imm[i]);
6784         break;
6785       case INTCALL:
6786         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6787         break;
6788       default:
6789         //printf (" %s %8x\n",insn[i],source[i]);
6790         printf (" %x: %s\n",start+i*4,insn[i]);
6791     }
6792 }
6793 #else
6794 static void disassemble_inst(int i) {}
6795 #endif // DISASM
6796
6797 #define DRC_TEST_VAL 0x74657374
6798
6799 static void new_dynarec_test(void)
6800 {
6801   int (*testfunc)(void);
6802   void *beginning;
6803   int ret[2];
6804   size_t i;
6805
6806   // check structure linkage
6807   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6808   {
6809     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6810   }
6811
6812   SysPrintf("testing if we can run recompiled code...\n");
6813   ((volatile u_int *)out)[0]++; // make cache dirty
6814
6815   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6816     out = ndrc->translation_cache;
6817     beginning = start_block();
6818     emit_movimm(DRC_TEST_VAL + i, 0); // test
6819     emit_ret();
6820     literal_pool(0);
6821     end_block(beginning);
6822     testfunc = beginning;
6823     ret[i] = testfunc();
6824   }
6825
6826   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6827     SysPrintf("test passed.\n");
6828   else
6829     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6830   out = ndrc->translation_cache;
6831 }
6832
6833 // clear the state completely, instead of just marking
6834 // things invalid like invalidate_all_pages() does
6835 void new_dynarec_clear_full(void)
6836 {
6837   int n;
6838   out = ndrc->translation_cache;
6839   memset(invalid_code,1,sizeof(invalid_code));
6840   memset(hash_table,0xff,sizeof(hash_table));
6841   memset(mini_ht,-1,sizeof(mini_ht));
6842   memset(restore_candidate,0,sizeof(restore_candidate));
6843   memset(shadow,0,sizeof(shadow));
6844   copy=shadow;
6845   expirep=16384; // Expiry pointer, +2 blocks
6846   pending_exception=0;
6847   literalcount=0;
6848   stop_after_jal=0;
6849   inv_code_start=inv_code_end=~0;
6850   // TLB
6851   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6852   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6853   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6854
6855   cycle_multiplier_old = cycle_multiplier;
6856   new_dynarec_hacks_old = new_dynarec_hacks;
6857 }
6858
6859 void new_dynarec_init(void)
6860 {
6861   SysPrintf("Init new dynarec\n");
6862
6863 #ifdef BASE_ADDR_DYNAMIC
6864   #ifdef VITA
6865   sceBlock = sceKernelAllocMemBlockForVM("code", 1 << TARGET_SIZE_2);
6866   if (sceBlock < 0)
6867     SysPrintf("sceKernelAllocMemBlockForVM failed\n");
6868   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6869   if (ret < 0)
6870     SysPrintf("sceKernelGetMemBlockBase failed\n");
6871   #else
6872   uintptr_t desired_addr = 0;
6873   #ifdef __ELF__
6874   extern char _end;
6875   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6876   #endif
6877   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6878             PROT_READ | PROT_WRITE | PROT_EXEC,
6879             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6880   if (ndrc == MAP_FAILED) {
6881     SysPrintf("mmap() failed: %s\n", strerror(errno));
6882     abort();
6883   }
6884   #endif
6885 #else
6886   #ifndef NO_WRITE_EXEC
6887   // not all systems allow execute in data segment by default
6888   if (mprotect(ndrc, sizeof(ndrc->translation_cache) + sizeof(ndrc->tramp.ops),
6889                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6890     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6891   #endif
6892 #endif
6893   out = ndrc->translation_cache;
6894   cycle_multiplier=200;
6895   new_dynarec_clear_full();
6896 #ifdef HOST_IMM8
6897   // Copy this into local area so we don't have to put it in every literal pool
6898   invc_ptr=invalid_code;
6899 #endif
6900   arch_init();
6901   new_dynarec_test();
6902 #ifndef RAM_FIXED
6903   ram_offset=(uintptr_t)rdram-0x80000000;
6904 #endif
6905   if (ram_offset!=0)
6906     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6907 }
6908
6909 void new_dynarec_cleanup(void)
6910 {
6911   int n;
6912 #ifdef BASE_ADDR_DYNAMIC
6913   #ifdef VITA
6914   sceKernelFreeMemBlock(sceBlock);
6915   sceBlock = -1;
6916   #else
6917   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6918     SysPrintf("munmap() failed\n");
6919   #endif
6920 #endif
6921   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6922   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6923   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6924   #ifdef ROM_COPY
6925   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6926   #endif
6927 }
6928
6929 static u_int *get_source_start(u_int addr, u_int *limit)
6930 {
6931   if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6932     cycle_multiplier_override = 0;
6933
6934   if (addr < 0x00200000 ||
6935     (0xa0000000 <= addr && addr < 0xa0200000))
6936   {
6937     // used for BIOS calls mostly?
6938     *limit = (addr&0xa0000000)|0x00200000;
6939     return (u_int *)(rdram + (addr&0x1fffff));
6940   }
6941   else if (!Config.HLE && (
6942     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6943     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6944   {
6945     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6946     // but timings in PCSX are too tied to the interpreter's BIAS
6947     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6948       cycle_multiplier_override = 200;
6949
6950     *limit = (addr & 0xfff00000) | 0x80000;
6951     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6952   }
6953   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6954     *limit = (addr & 0x80600000) + 0x00200000;
6955     return (u_int *)(rdram + (addr&0x1fffff));
6956   }
6957   return NULL;
6958 }
6959
6960 static u_int scan_for_ret(u_int addr)
6961 {
6962   u_int limit = 0;
6963   u_int *mem;
6964
6965   mem = get_source_start(addr, &limit);
6966   if (mem == NULL)
6967     return addr;
6968
6969   if (limit > addr + 0x1000)
6970     limit = addr + 0x1000;
6971   for (; addr < limit; addr += 4, mem++) {
6972     if (*mem == 0x03e00008) // jr $ra
6973       return addr + 8;
6974   }
6975   return addr;
6976 }
6977
6978 struct savestate_block {
6979   uint32_t addr;
6980   uint32_t regflags;
6981 };
6982
6983 static int addr_cmp(const void *p1_, const void *p2_)
6984 {
6985   const struct savestate_block *p1 = p1_, *p2 = p2_;
6986   return p1->addr - p2->addr;
6987 }
6988
6989 int new_dynarec_save_blocks(void *save, int size)
6990 {
6991   struct savestate_block *blocks = save;
6992   int maxcount = size / sizeof(blocks[0]);
6993   struct savestate_block tmp_blocks[1024];
6994   struct ll_entry *head;
6995   int p, s, d, o, bcnt;
6996   u_int addr;
6997
6998   o = 0;
6999   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
7000     bcnt = 0;
7001     for (head = jump_in[p]; head != NULL; head = head->next) {
7002       tmp_blocks[bcnt].addr = head->vaddr;
7003       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
7004       bcnt++;
7005     }
7006     if (bcnt < 1)
7007       continue;
7008     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
7009
7010     addr = tmp_blocks[0].addr;
7011     for (s = d = 0; s < bcnt; s++) {
7012       if (tmp_blocks[s].addr < addr)
7013         continue;
7014       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
7015         tmp_blocks[d++] = tmp_blocks[s];
7016       addr = scan_for_ret(tmp_blocks[s].addr);
7017     }
7018
7019     if (o + d > maxcount)
7020       d = maxcount - o;
7021     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
7022     o += d;
7023   }
7024
7025   return o * sizeof(blocks[0]);
7026 }
7027
7028 void new_dynarec_load_blocks(const void *save, int size)
7029 {
7030   const struct savestate_block *blocks = save;
7031   int count = size / sizeof(blocks[0]);
7032   u_int regs_save[32];
7033   uint32_t f;
7034   int i, b;
7035
7036   get_addr(psxRegs.pc);
7037
7038   // change GPRs for speculation to at least partially work..
7039   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
7040   for (i = 1; i < 32; i++)
7041     psxRegs.GPR.r[i] = 0x80000000;
7042
7043   for (b = 0; b < count; b++) {
7044     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7045       if (f & 1)
7046         psxRegs.GPR.r[i] = 0x1f800000;
7047     }
7048
7049     get_addr(blocks[b].addr);
7050
7051     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7052       if (f & 1)
7053         psxRegs.GPR.r[i] = 0x80000000;
7054     }
7055   }
7056
7057   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
7058 }
7059
7060 int new_recompile_block(u_int addr)
7061 {
7062   u_int pagelimit = 0;
7063   u_int state_rflags = 0;
7064   int i;
7065
7066   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
7067   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
7068   //if(debug)
7069   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
7070
7071   // this is just for speculation
7072   for (i = 1; i < 32; i++) {
7073     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
7074       state_rflags |= 1 << i;
7075   }
7076
7077   start = (u_int)addr&~3;
7078   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7079   new_dynarec_did_compile=1;
7080   if (Config.HLE && start == 0x80001000) // hlecall
7081   {
7082     // XXX: is this enough? Maybe check hleSoftCall?
7083     void *beginning=start_block();
7084     u_int page=get_page(start);
7085
7086     invalid_code[start>>12]=0;
7087     emit_movimm(start,0);
7088     emit_writeword(0,&pcaddr);
7089     emit_far_jump(new_dyna_leave);
7090     literal_pool(0);
7091     end_block(beginning);
7092     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7093     return 0;
7094   }
7095
7096   source = get_source_start(start, &pagelimit);
7097   if (source == NULL) {
7098     SysPrintf("Compile at bogus memory address: %08x\n", addr);
7099     abort();
7100   }
7101
7102   /* Pass 1: disassemble */
7103   /* Pass 2: register dependencies, branch targets */
7104   /* Pass 3: register allocation */
7105   /* Pass 4: branch dependencies */
7106   /* Pass 5: pre-alloc */
7107   /* Pass 6: optimize clean/dirty state */
7108   /* Pass 7: flag 32-bit registers */
7109   /* Pass 8: assembly */
7110   /* Pass 9: linker */
7111   /* Pass 10: garbage collection / free memory */
7112
7113   int j;
7114   int done=0;
7115   unsigned int type,op,op2;
7116
7117   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7118
7119   /* Pass 1 disassembly */
7120
7121   for(i=0;!done;i++) {
7122     bt[i]=0;likely[i]=0;ooo[i]=0;op2=0;
7123     minimum_free_regs[i]=0;
7124     opcode[i]=op=source[i]>>26;
7125     switch(op)
7126     {
7127       case 0x00: strcpy(insn[i],"special"); type=NI;
7128         op2=source[i]&0x3f;
7129         switch(op2)
7130         {
7131           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7132           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7133           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7134           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7135           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7136           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7137           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7138           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7139           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7140           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
7141           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7142           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7143           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7144           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7145           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7146           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7147           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7148           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7149           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7150           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7151           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7152           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7153           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7154           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7155           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7156           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7157           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7158           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7159           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7160           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7161           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7162           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7163           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7164           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7165           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7166 #if 0
7167           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7168           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7169           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7170           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7171           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7172           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7173           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7174           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7175           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7176           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7177           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7178           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7179           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7180           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7181           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7182           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7183           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7184 #endif
7185         }
7186         break;
7187       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7188         op2=(source[i]>>16)&0x1f;
7189         switch(op2)
7190         {
7191           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7192           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7193           case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7194           case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7195           case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7196           case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7197           case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7198           case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7199           case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7200           case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7201           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7202           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7203           case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7204           case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7205         }
7206         break;
7207       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7208       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7209       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7210       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7211       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7212       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7213       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7214       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7215       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7216       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7217       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7218       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7219       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7220       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7221       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7222         op2=(source[i]>>21)&0x1f;
7223         switch(op2)
7224         {
7225           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7226           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7227           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7228           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7229           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7230         }
7231         break;
7232       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7233         op2=(source[i]>>21)&0x1f;
7234         break;
7235 #if 0
7236       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7237       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7238       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7239       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7240       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7241       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7242       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7243       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7244 #endif
7245       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7246       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7247       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7248       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7249       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7250       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7251       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7252 #if 0
7253       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7254 #endif
7255       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7256       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7257       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7258       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7259 #if 0
7260       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7261       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7262 #endif
7263       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7264       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7265       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7266       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7267 #if 0
7268       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7269       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7270       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7271 #endif
7272       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7273       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7274 #if 0
7275       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7276       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7277       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7278 #endif
7279       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7280         op2=(source[i]>>21)&0x1f;
7281         //if (op2 & 0x10)
7282         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7283           if (gte_handlers[source[i]&0x3f]!=NULL) {
7284             if (gte_regnames[source[i]&0x3f]!=NULL)
7285               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7286             else
7287               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7288             type=C2OP;
7289           }
7290         }
7291         else switch(op2)
7292         {
7293           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7294           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7295           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7296           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7297         }
7298         break;
7299       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7300       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7301       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7302       default: strcpy(insn[i],"???"); type=NI;
7303         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7304         break;
7305     }
7306     itype[i]=type;
7307     opcode2[i]=op2;
7308     /* Get registers/immediates */
7309     lt1[i]=0;
7310     dep1[i]=0;
7311     dep2[i]=0;
7312     gte_rs[i]=gte_rt[i]=0;
7313     switch(type) {
7314       case LOAD:
7315         rs1[i]=(source[i]>>21)&0x1f;
7316         rs2[i]=0;
7317         rt1[i]=(source[i]>>16)&0x1f;
7318         rt2[i]=0;
7319         imm[i]=(short)source[i];
7320         break;
7321       case STORE:
7322       case STORELR:
7323         rs1[i]=(source[i]>>21)&0x1f;
7324         rs2[i]=(source[i]>>16)&0x1f;
7325         rt1[i]=0;
7326         rt2[i]=0;
7327         imm[i]=(short)source[i];
7328         break;
7329       case LOADLR:
7330         // LWL/LWR only load part of the register,
7331         // therefore the target register must be treated as a source too
7332         rs1[i]=(source[i]>>21)&0x1f;
7333         rs2[i]=(source[i]>>16)&0x1f;
7334         rt1[i]=(source[i]>>16)&0x1f;
7335         rt2[i]=0;
7336         imm[i]=(short)source[i];
7337         if(op==0x26) dep1[i]=rt1[i]; // LWR
7338         break;
7339       case IMM16:
7340         if (op==0x0f) rs1[i]=0; // LUI instruction has no source register
7341         else rs1[i]=(source[i]>>21)&0x1f;
7342         rs2[i]=0;
7343         rt1[i]=(source[i]>>16)&0x1f;
7344         rt2[i]=0;
7345         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7346           imm[i]=(unsigned short)source[i];
7347         }else{
7348           imm[i]=(short)source[i];
7349         }
7350         if(op==0x0d||op==0x0e) dep1[i]=rs1[i]; // ORI/XORI
7351         break;
7352       case UJUMP:
7353         rs1[i]=0;
7354         rs2[i]=0;
7355         rt1[i]=0;
7356         rt2[i]=0;
7357         // The JAL instruction writes to r31.
7358         if (op&1) {
7359           rt1[i]=31;
7360         }
7361         rs2[i]=CCREG;
7362         break;
7363       case RJUMP:
7364         rs1[i]=(source[i]>>21)&0x1f;
7365         rs2[i]=0;
7366         rt1[i]=0;
7367         rt2[i]=0;
7368         // The JALR instruction writes to rd.
7369         if (op2&1) {
7370           rt1[i]=(source[i]>>11)&0x1f;
7371         }
7372         rs2[i]=CCREG;
7373         break;
7374       case CJUMP:
7375         rs1[i]=(source[i]>>21)&0x1f;
7376         rs2[i]=(source[i]>>16)&0x1f;
7377         rt1[i]=0;
7378         rt2[i]=0;
7379         if(op&2) { // BGTZ/BLEZ
7380           rs2[i]=0;
7381         }
7382         likely[i]=op>>4;
7383         break;
7384       case SJUMP:
7385         rs1[i]=(source[i]>>21)&0x1f;
7386         rs2[i]=CCREG;
7387         rt1[i]=0;
7388         rt2[i]=0;
7389         if(op2&0x10) { // BxxAL
7390           rt1[i]=31;
7391           // NOTE: If the branch is not taken, r31 is still overwritten
7392         }
7393         likely[i]=(op2&2)>>1;
7394         break;
7395       case ALU:
7396         rs1[i]=(source[i]>>21)&0x1f; // source
7397         rs2[i]=(source[i]>>16)&0x1f; // subtract amount
7398         rt1[i]=(source[i]>>11)&0x1f; // destination
7399         rt2[i]=0;
7400         if(op2>=0x24&&op2<=0x27) { // AND/OR/XOR/NOR
7401           dep1[i]=rs1[i];dep2[i]=rs2[i];
7402         }
7403         else if(op2>=0x2c&&op2<=0x2f) { // DADD/DSUB
7404           dep1[i]=rs1[i];dep2[i]=rs2[i];
7405         }
7406         break;
7407       case MULTDIV:
7408         rs1[i]=(source[i]>>21)&0x1f; // source
7409         rs2[i]=(source[i]>>16)&0x1f; // divisor
7410         rt1[i]=HIREG;
7411         rt2[i]=LOREG;
7412         break;
7413       case MOV:
7414         rs1[i]=0;
7415         rs2[i]=0;
7416         rt1[i]=0;
7417         rt2[i]=0;
7418         if(op2==0x10) rs1[i]=HIREG; // MFHI
7419         if(op2==0x11) rt1[i]=HIREG; // MTHI
7420         if(op2==0x12) rs1[i]=LOREG; // MFLO
7421         if(op2==0x13) rt1[i]=LOREG; // MTLO
7422         if((op2&0x1d)==0x10) rt1[i]=(source[i]>>11)&0x1f; // MFxx
7423         if((op2&0x1d)==0x11) rs1[i]=(source[i]>>21)&0x1f; // MTxx
7424         dep1[i]=rs1[i];
7425         break;
7426       case SHIFT:
7427         rs1[i]=(source[i]>>16)&0x1f; // target of shift
7428         rs2[i]=(source[i]>>21)&0x1f; // shift amount
7429         rt1[i]=(source[i]>>11)&0x1f; // destination
7430         rt2[i]=0;
7431         break;
7432       case SHIFTIMM:
7433         rs1[i]=(source[i]>>16)&0x1f;
7434         rs2[i]=0;
7435         rt1[i]=(source[i]>>11)&0x1f;
7436         rt2[i]=0;
7437         imm[i]=(source[i]>>6)&0x1f;
7438         // DSxx32 instructions
7439         if(op2>=0x3c) imm[i]|=0x20;
7440         break;
7441       case COP0:
7442         rs1[i]=0;
7443         rs2[i]=0;
7444         rt1[i]=0;
7445         rt2[i]=0;
7446         if(op2==0||op2==2) rt1[i]=(source[i]>>16)&0x1F; // MFC0/CFC0
7447         if(op2==4||op2==6) rs1[i]=(source[i]>>16)&0x1F; // MTC0/CTC0
7448         if(op2==4&&((source[i]>>11)&0x1f)==12) rt2[i]=CSREG; // Status
7449         if(op2==16) if((source[i]&0x3f)==0x18) rs2[i]=CCREG; // ERET
7450         break;
7451       case COP1:
7452         rs1[i]=0;
7453         rs2[i]=0;
7454         rt1[i]=0;
7455         rt2[i]=0;
7456         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7457         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7458         rs2[i]=CSREG;
7459         break;
7460       case COP2:
7461         rs1[i]=0;
7462         rs2[i]=0;
7463         rt1[i]=0;
7464         rt2[i]=0;
7465         if(op2<3) rt1[i]=(source[i]>>16)&0x1F; // MFC2/CFC2
7466         if(op2>3) rs1[i]=(source[i]>>16)&0x1F; // MTC2/CTC2
7467         rs2[i]=CSREG;
7468         int gr=(source[i]>>11)&0x1F;
7469         switch(op2)
7470         {
7471           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7472           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7473           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7474           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7475         }
7476         break;
7477       case C1LS:
7478         rs1[i]=(source[i]>>21)&0x1F;
7479         rs2[i]=CSREG;
7480         rt1[i]=0;
7481         rt2[i]=0;
7482         imm[i]=(short)source[i];
7483         break;
7484       case C2LS:
7485         rs1[i]=(source[i]>>21)&0x1F;
7486         rs2[i]=0;
7487         rt1[i]=0;
7488         rt2[i]=0;
7489         imm[i]=(short)source[i];
7490         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7491         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7492         break;
7493       case C2OP:
7494         rs1[i]=0;
7495         rs2[i]=0;
7496         rt1[i]=0;
7497         rt2[i]=0;
7498         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7499         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7500         gte_rt[i]|=1ll<<63; // every op changes flags
7501         if((source[i]&0x3f)==GTE_MVMVA) {
7502           int v = (source[i] >> 15) & 3;
7503           gte_rs[i]&=~0xe3fll;
7504           if(v==3) gte_rs[i]|=0xe00ll;
7505           else gte_rs[i]|=3ll<<(v*2);
7506         }
7507         break;
7508       case SYSCALL:
7509       case HLECALL:
7510       case INTCALL:
7511         rs1[i]=CCREG;
7512         rs2[i]=0;
7513         rt1[i]=0;
7514         rt2[i]=0;
7515         break;
7516       default:
7517         rs1[i]=0;
7518         rs2[i]=0;
7519         rt1[i]=0;
7520         rt2[i]=0;
7521     }
7522     /* Calculate branch target addresses */
7523     if(type==UJUMP)
7524       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7525     else if(type==CJUMP&&rs1[i]==rs2[i]&&(op&1))
7526       ba[i]=start+i*4+8; // Ignore never taken branch
7527     else if(type==SJUMP&&rs1[i]==0&&!(op2&1))
7528       ba[i]=start+i*4+8; // Ignore never taken branch
7529     else if(type==CJUMP||type==SJUMP)
7530       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7531     else ba[i]=-1;
7532     if (i > 0 && is_jump(i-1)) {
7533       int do_in_intrp=0;
7534       // branch in delay slot?
7535       if(type==RJUMP||type==UJUMP||type==CJUMP||type==SJUMP) {
7536         // don't handle first branch and call interpreter if it's hit
7537         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7538         do_in_intrp=1;
7539       }
7540       // basic load delay detection
7541       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&rt1[i]!=0) {
7542         int t=(ba[i-1]-start)/4;
7543         if(0 <= t && t < i &&(rt1[i]==rs1[t]||rt1[i]==rs2[t])&&itype[t]!=CJUMP&&itype[t]!=SJUMP) {
7544           // jump target wants DS result - potential load delay effect
7545           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7546           do_in_intrp=1;
7547           bt[t+1]=1; // expected return from interpreter
7548         }
7549         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&&
7550               !(i>=3&&is_jump(i-3))) {
7551           // v0 overwrite like this is a sign of trouble, bail out
7552           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7553           do_in_intrp=1;
7554         }
7555       }
7556       if(do_in_intrp) {
7557         rs1[i-1]=CCREG;
7558         rs2[i-1]=rt1[i-1]=rt2[i-1]=0;
7559         ba[i-1]=-1;
7560         itype[i-1]=INTCALL;
7561         done=2;
7562         i--; // don't compile the DS
7563       }
7564     }
7565     /* Is this the end of the block? */
7566     if (i > 0 && is_ujump(i-1)) {
7567       if(rt1[i-1]==0) { // Continue past subroutine call (JAL)
7568         done=2;
7569       }
7570       else {
7571         if(stop_after_jal) done=1;
7572         // Stop on BREAK
7573         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7574       }
7575       // Don't recompile stuff that's already compiled
7576       if(check_addr(start+i*4+4)) done=1;
7577       // Don't get too close to the limit
7578       if(i>MAXBLOCK/2) done=1;
7579     }
7580     if(itype[i]==SYSCALL&&stop_after_jal) done=1;
7581     if(itype[i]==HLECALL||itype[i]==INTCALL) done=2;
7582     if(done==2) {
7583       // Does the block continue due to a branch?
7584       for(j=i-1;j>=0;j--)
7585       {
7586         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7587         if(ba[j]==start+i*4+4) done=j=0;
7588         if(ba[j]==start+i*4+8) done=j=0;
7589       }
7590     }
7591     //assert(i<MAXBLOCK-1);
7592     if(start+i*4==pagelimit-4) done=1;
7593     assert(start+i*4<pagelimit);
7594     if (i==MAXBLOCK-1) done=1;
7595     // Stop if we're compiling junk
7596     if(itype[i]==NI&&opcode[i]==0x11) {
7597       done=stop_after_jal=1;
7598       SysPrintf("Disabled speculative precompilation\n");
7599     }
7600   }
7601   slen=i;
7602   if(itype[i-1]==UJUMP||itype[i-1]==CJUMP||itype[i-1]==SJUMP||itype[i-1]==RJUMP) {
7603     if(start+i*4==pagelimit) {
7604       itype[i-1]=SPAN;
7605     }
7606   }
7607   assert(slen>0);
7608
7609   /* Pass 2 - Register dependencies and branch targets */
7610
7611   unneeded_registers(0,slen-1,0);
7612
7613   /* Pass 3 - Register allocation */
7614
7615   struct regstat current; // Current register allocations/status
7616   current.dirty=0;
7617   current.u=unneeded_reg[0];
7618   clear_all_regs(current.regmap);
7619   alloc_reg(&current,0,CCREG);
7620   dirty_reg(&current,CCREG);
7621   current.isconst=0;
7622   current.wasconst=0;
7623   current.waswritten=0;
7624   int ds=0;
7625   int cc=0;
7626   int hr=-1;
7627
7628   if((u_int)addr&1) {
7629     // First instruction is delay slot
7630     cc=-1;
7631     bt[1]=1;
7632     ds=1;
7633     unneeded_reg[0]=1;
7634     current.regmap[HOST_BTREG]=BTREG;
7635   }
7636
7637   for(i=0;i<slen;i++)
7638   {
7639     if(bt[i])
7640     {
7641       int hr;
7642       for(hr=0;hr<HOST_REGS;hr++)
7643       {
7644         // Is this really necessary?
7645         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7646       }
7647       current.isconst=0;
7648       current.waswritten=0;
7649     }
7650
7651     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7652     regs[i].wasconst=current.isconst;
7653     regs[i].wasdirty=current.dirty;
7654     regs[i].loadedconst=0;
7655     if(itype[i]!=UJUMP&&itype[i]!=CJUMP&&itype[i]!=SJUMP&&itype[i]!=RJUMP) {
7656       if(i+1<slen) {
7657         current.u=unneeded_reg[i+1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
7658         current.u|=1;
7659       } else {
7660         current.u=1;
7661       }
7662     } else {
7663       if(i+1<slen) {
7664         current.u=branch_unneeded_reg[i]&~((1LL<<rs1[i+1])|(1LL<<rs2[i+1]));
7665         current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7666         current.u|=1;
7667       } else { SysPrintf("oops, branch at end of block with no delay slot\n");abort(); }
7668     }
7669     is_ds[i]=ds;
7670     if(ds) {
7671       ds=0; // Skip delay slot, already allocated as part of branch
7672       // ...but we need to alloc it in case something jumps here
7673       if(i+1<slen) {
7674         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7675       }else{
7676         current.u=branch_unneeded_reg[i-1];
7677       }
7678       current.u&=~((1LL<<rs1[i])|(1LL<<rs2[i]));
7679       current.u|=1;
7680       struct regstat temp;
7681       memcpy(&temp,&current,sizeof(current));
7682       temp.wasdirty=temp.dirty;
7683       // TODO: Take into account unconditional branches, as below
7684       delayslot_alloc(&temp,i);
7685       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7686       regs[i].wasdirty=temp.wasdirty;
7687       regs[i].dirty=temp.dirty;
7688       regs[i].isconst=0;
7689       regs[i].wasconst=0;
7690       current.isconst=0;
7691       // Create entry (branch target) regmap
7692       for(hr=0;hr<HOST_REGS;hr++)
7693       {
7694         int r=temp.regmap[hr];
7695         if(r>=0) {
7696           if(r!=regmap_pre[i][hr]) {
7697             regs[i].regmap_entry[hr]=-1;
7698           }
7699           else
7700           {
7701               assert(r < 64);
7702               if((current.u>>r)&1) {
7703                 regs[i].regmap_entry[hr]=-1;
7704                 regs[i].regmap[hr]=-1;
7705                 //Don't clear regs in the delay slot as the branch might need them
7706                 //current.regmap[hr]=-1;
7707               }else
7708                 regs[i].regmap_entry[hr]=r;
7709           }
7710         } else {
7711           // First instruction expects CCREG to be allocated
7712           if(i==0&&hr==HOST_CCREG)
7713             regs[i].regmap_entry[hr]=CCREG;
7714           else
7715             regs[i].regmap_entry[hr]=-1;
7716         }
7717       }
7718     }
7719     else { // Not delay slot
7720       switch(itype[i]) {
7721         case UJUMP:
7722           //current.isconst=0; // DEBUG
7723           //current.wasconst=0; // DEBUG
7724           //regs[i].wasconst=0; // DEBUG
7725           clear_const(&current,rt1[i]);
7726           alloc_cc(&current,i);
7727           dirty_reg(&current,CCREG);
7728           if (rt1[i]==31) {
7729             alloc_reg(&current,i,31);
7730             dirty_reg(&current,31);
7731             //assert(rs1[i+1]!=31&&rs2[i+1]!=31);
7732             //assert(rt1[i+1]!=rt1[i]);
7733             #ifdef REG_PREFETCH
7734             alloc_reg(&current,i,PTEMP);
7735             #endif
7736           }
7737           ooo[i]=1;
7738           delayslot_alloc(&current,i+1);
7739           //current.isconst=0; // DEBUG
7740           ds=1;
7741           //printf("i=%d, isconst=%x\n",i,current.isconst);
7742           break;
7743         case RJUMP:
7744           //current.isconst=0;
7745           //current.wasconst=0;
7746           //regs[i].wasconst=0;
7747           clear_const(&current,rs1[i]);
7748           clear_const(&current,rt1[i]);
7749           alloc_cc(&current,i);
7750           dirty_reg(&current,CCREG);
7751           if(rs1[i]!=rt1[i+1]&&rs1[i]!=rt2[i+1]) {
7752             alloc_reg(&current,i,rs1[i]);
7753             if (rt1[i]!=0) {
7754               alloc_reg(&current,i,rt1[i]);
7755               dirty_reg(&current,rt1[i]);
7756               assert(rs1[i+1]!=rt1[i]&&rs2[i+1]!=rt1[i]);
7757               assert(rt1[i+1]!=rt1[i]);
7758               #ifdef REG_PREFETCH
7759               alloc_reg(&current,i,PTEMP);
7760               #endif
7761             }
7762             #ifdef USE_MINI_HT
7763             if(rs1[i]==31) { // JALR
7764               alloc_reg(&current,i,RHASH);
7765               alloc_reg(&current,i,RHTBL);
7766             }
7767             #endif
7768             delayslot_alloc(&current,i+1);
7769           } else {
7770             // The delay slot overwrites our source register,
7771             // allocate a temporary register to hold the old value.
7772             current.isconst=0;
7773             current.wasconst=0;
7774             regs[i].wasconst=0;
7775             delayslot_alloc(&current,i+1);
7776             current.isconst=0;
7777             alloc_reg(&current,i,RTEMP);
7778           }
7779           //current.isconst=0; // DEBUG
7780           ooo[i]=1;
7781           ds=1;
7782           break;
7783         case CJUMP:
7784           //current.isconst=0;
7785           //current.wasconst=0;
7786           //regs[i].wasconst=0;
7787           clear_const(&current,rs1[i]);
7788           clear_const(&current,rs2[i]);
7789           if((opcode[i]&0x3E)==4) // BEQ/BNE
7790           {
7791             alloc_cc(&current,i);
7792             dirty_reg(&current,CCREG);
7793             if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7794             if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7795             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1]))||
7796                (rs2[i]&&(rs2[i]==rt1[i+1]||rs2[i]==rt2[i+1]))) {
7797               // The delay slot overwrites one of our conditions.
7798               // Allocate the branch condition registers instead.
7799               current.isconst=0;
7800               current.wasconst=0;
7801               regs[i].wasconst=0;
7802               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7803               if(rs2[i]) alloc_reg(&current,i,rs2[i]);
7804             }
7805             else
7806             {
7807               ooo[i]=1;
7808               delayslot_alloc(&current,i+1);
7809             }
7810           }
7811           else
7812           if((opcode[i]&0x3E)==6) // BLEZ/BGTZ
7813           {
7814             alloc_cc(&current,i);
7815             dirty_reg(&current,CCREG);
7816             alloc_reg(&current,i,rs1[i]);
7817             if(rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) {
7818               // The delay slot overwrites one of our conditions.
7819               // Allocate the branch condition registers instead.
7820               current.isconst=0;
7821               current.wasconst=0;
7822               regs[i].wasconst=0;
7823               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7824             }
7825             else
7826             {
7827               ooo[i]=1;
7828               delayslot_alloc(&current,i+1);
7829             }
7830           }
7831           else
7832           // Don't alloc the delay slot yet because we might not execute it
7833           if((opcode[i]&0x3E)==0x14) // BEQL/BNEL
7834           {
7835             current.isconst=0;
7836             current.wasconst=0;
7837             regs[i].wasconst=0;
7838             alloc_cc(&current,i);
7839             dirty_reg(&current,CCREG);
7840             alloc_reg(&current,i,rs1[i]);
7841             alloc_reg(&current,i,rs2[i]);
7842           }
7843           else
7844           if((opcode[i]&0x3E)==0x16) // BLEZL/BGTZL
7845           {
7846             current.isconst=0;
7847             current.wasconst=0;
7848             regs[i].wasconst=0;
7849             alloc_cc(&current,i);
7850             dirty_reg(&current,CCREG);
7851             alloc_reg(&current,i,rs1[i]);
7852           }
7853           ds=1;
7854           //current.isconst=0;
7855           break;
7856         case SJUMP:
7857           //current.isconst=0;
7858           //current.wasconst=0;
7859           //regs[i].wasconst=0;
7860           clear_const(&current,rs1[i]);
7861           clear_const(&current,rt1[i]);
7862           //if((opcode2[i]&0x1E)==0x0) // BLTZ/BGEZ
7863           if((opcode2[i]&0x0E)==0x0) // BLTZ/BGEZ
7864           {
7865             alloc_cc(&current,i);
7866             dirty_reg(&current,CCREG);
7867             alloc_reg(&current,i,rs1[i]);
7868             if (rt1[i]==31) { // BLTZAL/BGEZAL
7869               alloc_reg(&current,i,31);
7870               dirty_reg(&current,31);
7871               //#ifdef REG_PREFETCH
7872               //alloc_reg(&current,i,PTEMP);
7873               //#endif
7874             }
7875             if((rs1[i]&&(rs1[i]==rt1[i+1]||rs1[i]==rt2[i+1])) // The delay slot overwrites the branch condition.
7876                ||(rt1[i]==31&&(rs1[i+1]==31||rs2[i+1]==31||rt1[i+1]==31||rt2[i+1]==31))) { // DS touches $ra
7877               // Allocate the branch condition registers instead.
7878               current.isconst=0;
7879               current.wasconst=0;
7880               regs[i].wasconst=0;
7881               if(rs1[i]) alloc_reg(&current,i,rs1[i]);
7882             }
7883             else
7884             {
7885               ooo[i]=1;
7886               delayslot_alloc(&current,i+1);
7887             }
7888           }
7889           else
7890           // Don't alloc the delay slot yet because we might not execute it
7891           if((opcode2[i]&0x1E)==0x2) // BLTZL/BGEZL
7892           {
7893             current.isconst=0;
7894             current.wasconst=0;
7895             regs[i].wasconst=0;
7896             alloc_cc(&current,i);
7897             dirty_reg(&current,CCREG);
7898             alloc_reg(&current,i,rs1[i]);
7899           }
7900           ds=1;
7901           //current.isconst=0;
7902           break;
7903         case IMM16:
7904           imm16_alloc(&current,i);
7905           break;
7906         case LOAD:
7907         case LOADLR:
7908           load_alloc(&current,i);
7909           break;
7910         case STORE:
7911         case STORELR:
7912           store_alloc(&current,i);
7913           break;
7914         case ALU:
7915           alu_alloc(&current,i);
7916           break;
7917         case SHIFT:
7918           shift_alloc(&current,i);
7919           break;
7920         case MULTDIV:
7921           multdiv_alloc(&current,i);
7922           break;
7923         case SHIFTIMM:
7924           shiftimm_alloc(&current,i);
7925           break;
7926         case MOV:
7927           mov_alloc(&current,i);
7928           break;
7929         case COP0:
7930           cop0_alloc(&current,i);
7931           break;
7932         case COP1:
7933           break;
7934         case COP2:
7935           cop2_alloc(&current,i);
7936           break;
7937         case C1LS:
7938           c1ls_alloc(&current,i);
7939           break;
7940         case C2LS:
7941           c2ls_alloc(&current,i);
7942           break;
7943         case C2OP:
7944           c2op_alloc(&current,i);
7945           break;
7946         case SYSCALL:
7947         case HLECALL:
7948         case INTCALL:
7949           syscall_alloc(&current,i);
7950           break;
7951         case SPAN:
7952           pagespan_alloc(&current,i);
7953           break;
7954       }
7955
7956       // Create entry (branch target) regmap
7957       for(hr=0;hr<HOST_REGS;hr++)
7958       {
7959         int r,or;
7960         r=current.regmap[hr];
7961         if(r>=0) {
7962           if(r!=regmap_pre[i][hr]) {
7963             // TODO: delay slot (?)
7964             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7965             if(or<0||(r&63)>=TEMPREG){
7966               regs[i].regmap_entry[hr]=-1;
7967             }
7968             else
7969             {
7970               // Just move it to a different register
7971               regs[i].regmap_entry[hr]=r;
7972               // If it was dirty before, it's still dirty
7973               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
7974             }
7975           }
7976           else
7977           {
7978             // Unneeded
7979             if(r==0){
7980               regs[i].regmap_entry[hr]=0;
7981             }
7982             else
7983             {
7984               assert(r<64);
7985               if((current.u>>r)&1) {
7986                 regs[i].regmap_entry[hr]=-1;
7987                 //regs[i].regmap[hr]=-1;
7988                 current.regmap[hr]=-1;
7989               }else
7990                 regs[i].regmap_entry[hr]=r;
7991             }
7992           }
7993         } else {
7994           // Branches expect CCREG to be allocated at the target
7995           if(regmap_pre[i][hr]==CCREG)
7996             regs[i].regmap_entry[hr]=CCREG;
7997           else
7998             regs[i].regmap_entry[hr]=-1;
7999         }
8000       }
8001       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
8002     }
8003
8004     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)
8005       current.waswritten|=1<<rs1[i-1];
8006     current.waswritten&=~(1<<rt1[i]);
8007     current.waswritten&=~(1<<rt2[i]);
8008     if((itype[i]==STORE||itype[i]==STORELR||(itype[i]==C2LS&&opcode[i]==0x3a))&&(u_int)imm[i]>=0x800)
8009       current.waswritten&=~(1<<rs1[i]);
8010
8011     /* Branch post-alloc */
8012     if(i>0)
8013     {
8014       current.wasdirty=current.dirty;
8015       switch(itype[i-1]) {
8016         case UJUMP:
8017           memcpy(&branch_regs[i-1],&current,sizeof(current));
8018           branch_regs[i-1].isconst=0;
8019           branch_regs[i-1].wasconst=0;
8020           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8021           alloc_cc(&branch_regs[i-1],i-1);
8022           dirty_reg(&branch_regs[i-1],CCREG);
8023           if(rt1[i-1]==31) { // JAL
8024             alloc_reg(&branch_regs[i-1],i-1,31);
8025             dirty_reg(&branch_regs[i-1],31);
8026           }
8027           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8028           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8029           break;
8030         case RJUMP:
8031           memcpy(&branch_regs[i-1],&current,sizeof(current));
8032           branch_regs[i-1].isconst=0;
8033           branch_regs[i-1].wasconst=0;
8034           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8035           alloc_cc(&branch_regs[i-1],i-1);
8036           dirty_reg(&branch_regs[i-1],CCREG);
8037           alloc_reg(&branch_regs[i-1],i-1,rs1[i-1]);
8038           if(rt1[i-1]!=0) { // JALR
8039             alloc_reg(&branch_regs[i-1],i-1,rt1[i-1]);
8040             dirty_reg(&branch_regs[i-1],rt1[i-1]);
8041           }
8042           #ifdef USE_MINI_HT
8043           if(rs1[i-1]==31) { // JALR
8044             alloc_reg(&branch_regs[i-1],i-1,RHASH);
8045             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
8046           }
8047           #endif
8048           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8049           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8050           break;
8051         case CJUMP:
8052           if((opcode[i-1]&0x3E)==4) // BEQ/BNE
8053           {
8054             alloc_cc(&current,i-1);
8055             dirty_reg(&current,CCREG);
8056             if((rs1[i-1]&&(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]))||
8057                (rs2[i-1]&&(rs2[i-1]==rt1[i]||rs2[i-1]==rt2[i]))) {
8058               // The delay slot overwrote one of our conditions
8059               // Delay slot goes after the test (in order)
8060               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8061               current.u|=1;
8062               delayslot_alloc(&current,i);
8063               current.isconst=0;
8064             }
8065             else
8066             {
8067               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i-1])|(1LL<<rs2[i-1]));
8068               // Alloc the branch condition registers
8069               if(rs1[i-1]) alloc_reg(&current,i-1,rs1[i-1]);
8070               if(rs2[i-1]) alloc_reg(&current,i-1,rs2[i-1]);
8071             }
8072             memcpy(&branch_regs[i-1],&current,sizeof(current));
8073             branch_regs[i-1].isconst=0;
8074             branch_regs[i-1].wasconst=0;
8075             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8076             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8077           }
8078           else
8079           if((opcode[i-1]&0x3E)==6) // BLEZ/BGTZ
8080           {
8081             alloc_cc(&current,i-1);
8082             dirty_reg(&current,CCREG);
8083             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
8084               // The delay slot overwrote the branch condition
8085               // Delay slot goes after the test (in order)
8086               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8087               current.u|=1;
8088               delayslot_alloc(&current,i);
8089               current.isconst=0;
8090             }
8091             else
8092             {
8093               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
8094               // Alloc the branch condition register
8095               alloc_reg(&current,i-1,rs1[i-1]);
8096             }
8097             memcpy(&branch_regs[i-1],&current,sizeof(current));
8098             branch_regs[i-1].isconst=0;
8099             branch_regs[i-1].wasconst=0;
8100             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8101             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8102           }
8103           else
8104           // Alloc the delay slot in case the branch is taken
8105           if((opcode[i-1]&0x3E)==0x14) // BEQL/BNEL
8106           {
8107             memcpy(&branch_regs[i-1],&current,sizeof(current));
8108             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8109             alloc_cc(&branch_regs[i-1],i);
8110             dirty_reg(&branch_regs[i-1],CCREG);
8111             delayslot_alloc(&branch_regs[i-1],i);
8112             branch_regs[i-1].isconst=0;
8113             alloc_reg(&current,i,CCREG); // Not taken path
8114             dirty_reg(&current,CCREG);
8115             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8116           }
8117           else
8118           if((opcode[i-1]&0x3E)==0x16) // BLEZL/BGTZL
8119           {
8120             memcpy(&branch_regs[i-1],&current,sizeof(current));
8121             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8122             alloc_cc(&branch_regs[i-1],i);
8123             dirty_reg(&branch_regs[i-1],CCREG);
8124             delayslot_alloc(&branch_regs[i-1],i);
8125             branch_regs[i-1].isconst=0;
8126             alloc_reg(&current,i,CCREG); // Not taken path
8127             dirty_reg(&current,CCREG);
8128             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8129           }
8130           break;
8131         case SJUMP:
8132           //if((opcode2[i-1]&0x1E)==0) // BLTZ/BGEZ
8133           if((opcode2[i-1]&0x0E)==0) // BLTZ/BGEZ
8134           {
8135             alloc_cc(&current,i-1);
8136             dirty_reg(&current,CCREG);
8137             if(rs1[i-1]==rt1[i]||rs1[i-1]==rt2[i]) {
8138               // The delay slot overwrote the branch condition
8139               // Delay slot goes after the test (in order)
8140               current.u=branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i]));
8141               current.u|=1;
8142               delayslot_alloc(&current,i);
8143               current.isconst=0;
8144             }
8145             else
8146             {
8147               current.u=branch_unneeded_reg[i-1]&~(1LL<<rs1[i-1]);
8148               // Alloc the branch condition register
8149               alloc_reg(&current,i-1,rs1[i-1]);
8150             }
8151             memcpy(&branch_regs[i-1],&current,sizeof(current));
8152             branch_regs[i-1].isconst=0;
8153             branch_regs[i-1].wasconst=0;
8154             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8155             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8156           }
8157           else
8158           // Alloc the delay slot in case the branch is taken
8159           if((opcode2[i-1]&0x1E)==2) // BLTZL/BGEZL
8160           {
8161             memcpy(&branch_regs[i-1],&current,sizeof(current));
8162             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<rs1[i])|(1LL<<rs2[i])|(1LL<<rt1[i])|(1LL<<rt2[i])))|1;
8163             alloc_cc(&branch_regs[i-1],i);
8164             dirty_reg(&branch_regs[i-1],CCREG);
8165             delayslot_alloc(&branch_regs[i-1],i);
8166             branch_regs[i-1].isconst=0;
8167             alloc_reg(&current,i,CCREG); // Not taken path
8168             dirty_reg(&current,CCREG);
8169             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8170           }
8171           // FIXME: BLTZAL/BGEZAL
8172           if(opcode2[i-1]&0x10) { // BxxZAL
8173             alloc_reg(&branch_regs[i-1],i-1,31);
8174             dirty_reg(&branch_regs[i-1],31);
8175           }
8176           break;
8177       }
8178
8179       if (is_ujump(i-1))
8180       {
8181         if(rt1[i-1]==31) // JAL/JALR
8182         {
8183           // Subroutine call will return here, don't alloc any registers
8184           current.dirty=0;
8185           clear_all_regs(current.regmap);
8186           alloc_reg(&current,i,CCREG);
8187           dirty_reg(&current,CCREG);
8188         }
8189         else if(i+1<slen)
8190         {
8191           // Internal branch will jump here, match registers to caller
8192           current.dirty=0;
8193           clear_all_regs(current.regmap);
8194           alloc_reg(&current,i,CCREG);
8195           dirty_reg(&current,CCREG);
8196           for(j=i-1;j>=0;j--)
8197           {
8198             if(ba[j]==start+i*4+4) {
8199               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8200               current.dirty=branch_regs[j].dirty;
8201               break;
8202             }
8203           }
8204           while(j>=0) {
8205             if(ba[j]==start+i*4+4) {
8206               for(hr=0;hr<HOST_REGS;hr++) {
8207                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8208                   current.regmap[hr]=-1;
8209                 }
8210                 current.dirty&=branch_regs[j].dirty;
8211               }
8212             }
8213             j--;
8214           }
8215         }
8216       }
8217     }
8218
8219     // Count cycles in between branches
8220     ccadj[i]=cc;
8221     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))
8222     {
8223       cc=0;
8224     }
8225 #if !defined(DRC_DBG)
8226     else if(itype[i]==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8227     {
8228       // this should really be removed since the real stalls have been implemented,
8229       // but doing so causes sizeable perf regression against the older version
8230       u_int gtec = gte_cycletab[source[i] & 0x3f];
8231       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8232     }
8233     else if(i>1&&itype[i]==STORE&&itype[i-1]==STORE&&itype[i-2]==STORE&&!bt[i])
8234     {
8235       cc+=4;
8236     }
8237     else if(itype[i]==C2LS)
8238     {
8239       // same as with C2OP
8240       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8241     }
8242 #endif
8243     else
8244     {
8245       cc++;
8246     }
8247
8248     if(!is_ds[i]) {
8249       regs[i].dirty=current.dirty;
8250       regs[i].isconst=current.isconst;
8251       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8252     }
8253     for(hr=0;hr<HOST_REGS;hr++) {
8254       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8255         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8256           regs[i].wasconst&=~(1<<hr);
8257         }
8258       }
8259     }
8260     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8261     regs[i].waswritten=current.waswritten;
8262   }
8263
8264   /* Pass 4 - Cull unused host registers */
8265
8266   uint64_t nr=0;
8267
8268   for (i=slen-1;i>=0;i--)
8269   {
8270     int hr;
8271     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8272     {
8273       if(ba[i]<start || ba[i]>=(start+slen*4))
8274       {
8275         // Branch out of this block, don't need anything
8276         nr=0;
8277       }
8278       else
8279       {
8280         // Internal branch
8281         // Need whatever matches the target
8282         nr=0;
8283         int t=(ba[i]-start)>>2;
8284         for(hr=0;hr<HOST_REGS;hr++)
8285         {
8286           if(regs[i].regmap_entry[hr]>=0) {
8287             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8288           }
8289         }
8290       }
8291       // Conditional branch may need registers for following instructions
8292       if (!is_ujump(i))
8293       {
8294         if(i<slen-2) {
8295           nr|=needed_reg[i+2];
8296           for(hr=0;hr<HOST_REGS;hr++)
8297           {
8298             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8299             //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]);
8300           }
8301         }
8302       }
8303       // Don't need stuff which is overwritten
8304       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8305       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8306       // Merge in delay slot
8307       for(hr=0;hr<HOST_REGS;hr++)
8308       {
8309         if(!likely[i]) {
8310           // These are overwritten unless the branch is "likely"
8311           // and the delay slot is nullified if not taken
8312           if(rt1[i+1]&&rt1[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8313           if(rt2[i+1]&&rt2[i+1]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8314         }
8315         if(rs1[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8316         if(rs2[i+1]==regmap_pre[i][hr]) nr|=1<<hr;
8317         if(rs1[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8318         if(rs2[i+1]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8319         if(itype[i+1]==STORE || itype[i+1]==STORELR || (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) {
8320           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8321           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8322         }
8323       }
8324     }
8325     else if(itype[i]==SYSCALL||itype[i]==HLECALL||itype[i]==INTCALL)
8326     {
8327       // SYSCALL instruction (software interrupt)
8328       nr=0;
8329     }
8330     else if(itype[i]==COP0 && (source[i]&0x3f)==0x18)
8331     {
8332       // ERET instruction (return from interrupt)
8333       nr=0;
8334     }
8335     else // Non-branch
8336     {
8337       if(i<slen-1) {
8338         for(hr=0;hr<HOST_REGS;hr++) {
8339           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8340           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8341           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8342           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8343         }
8344       }
8345     }
8346     for(hr=0;hr<HOST_REGS;hr++)
8347     {
8348       // Overwritten registers are not needed
8349       if(rt1[i]&&rt1[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8350       if(rt2[i]&&rt2[i]==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8351       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8352       // Source registers are needed
8353       if(rs1[i]==regmap_pre[i][hr]) nr|=1<<hr;
8354       if(rs2[i]==regmap_pre[i][hr]) nr|=1<<hr;
8355       if(rs1[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8356       if(rs2[i]==regs[i].regmap_entry[hr]) nr|=1<<hr;
8357       if(itype[i]==STORE || itype[i]==STORELR || (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) {
8358         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8359         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8360       }
8361       // Don't store a register immediately after writing it,
8362       // may prevent dual-issue.
8363       // But do so if this is a branch target, otherwise we
8364       // might have to load the register before the branch.
8365       if(i>0&&!bt[i]&&((regs[i].wasdirty>>hr)&1)) {
8366         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8367           if(rt1[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8368           if(rt2[i-1]==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8369         }
8370         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8371           if(rt1[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8372           if(rt2[i-1]==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8373         }
8374       }
8375     }
8376     // Cycle count is needed at branches.  Assume it is needed at the target too.
8377     if(i==0||bt[i]||itype[i]==CJUMP||itype[i]==SPAN) {
8378       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8379       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8380     }
8381     // Save it
8382     needed_reg[i]=nr;
8383
8384     // Deallocate unneeded registers
8385     for(hr=0;hr<HOST_REGS;hr++)
8386     {
8387       if(!((nr>>hr)&1)) {
8388         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8389         if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8390            (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8391            (regs[i].regmap[hr]&63)!=PTEMP && (regs[i].regmap[hr]&63)!=CCREG)
8392         {
8393           if (!is_ujump(i))
8394           {
8395             if(likely[i]) {
8396               regs[i].regmap[hr]=-1;
8397               regs[i].isconst&=~(1<<hr);
8398               if(i<slen-2) {
8399                 regmap_pre[i+2][hr]=-1;
8400                 regs[i+2].wasconst&=~(1<<hr);
8401               }
8402             }
8403           }
8404         }
8405         if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8406         {
8407           int map=0,temp=0;
8408           if(itype[i+1]==STORE || itype[i+1]==STORELR ||
8409              (opcode[i+1]&0x3b)==0x39 || (opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8410             map=INVCP;
8411           }
8412           if(itype[i+1]==LOADLR || itype[i+1]==STORELR ||
8413              itype[i+1]==C1LS || itype[i+1]==C2LS)
8414             temp=FTEMP;
8415           if((regs[i].regmap[hr]&63)!=rs1[i] && (regs[i].regmap[hr]&63)!=rs2[i] &&
8416              (regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8417              (regs[i].regmap[hr]&63)!=rt1[i+1] && (regs[i].regmap[hr]&63)!=rt2[i+1] &&
8418              regs[i].regmap[hr]!=rs1[i+1] && regs[i].regmap[hr]!=rs2[i+1] &&
8419              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8420              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8421              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8422              regs[i].regmap[hr]!=map )
8423           {
8424             regs[i].regmap[hr]=-1;
8425             regs[i].isconst&=~(1<<hr);
8426             if((branch_regs[i].regmap[hr]&63)!=rs1[i] && (branch_regs[i].regmap[hr]&63)!=rs2[i] &&
8427                (branch_regs[i].regmap[hr]&63)!=rt1[i] && (branch_regs[i].regmap[hr]&63)!=rt2[i] &&
8428                (branch_regs[i].regmap[hr]&63)!=rt1[i+1] && (branch_regs[i].regmap[hr]&63)!=rt2[i+1] &&
8429                branch_regs[i].regmap[hr]!=rs1[i+1] && branch_regs[i].regmap[hr]!=rs2[i+1] &&
8430                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8431                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8432                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8433                branch_regs[i].regmap[hr]!=map)
8434             {
8435               branch_regs[i].regmap[hr]=-1;
8436               branch_regs[i].regmap_entry[hr]=-1;
8437               if (!is_ujump(i))
8438               {
8439                 if(!likely[i]&&i<slen-2) {
8440                   regmap_pre[i+2][hr]=-1;
8441                   regs[i+2].wasconst&=~(1<<hr);
8442                 }
8443               }
8444             }
8445           }
8446         }
8447         else
8448         {
8449           // Non-branch
8450           if(i>0)
8451           {
8452             int map=-1,temp=-1;
8453             if(itype[i]==STORE || itype[i]==STORELR ||
8454                       (opcode[i]&0x3b)==0x39 || (opcode[i]&0x3b)==0x3a) { // SWC1/SDC1 || SWC2/SDC2
8455               map=INVCP;
8456             }
8457             if(itype[i]==LOADLR || itype[i]==STORELR ||
8458                itype[i]==C1LS || itype[i]==C2LS)
8459               temp=FTEMP;
8460             if((regs[i].regmap[hr]&63)!=rt1[i] && (regs[i].regmap[hr]&63)!=rt2[i] &&
8461                regs[i].regmap[hr]!=rs1[i] && regs[i].regmap[hr]!=rs2[i] &&
8462                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map &&
8463                (itype[i]!=SPAN||regs[i].regmap[hr]!=CCREG))
8464             {
8465               if(i<slen-1&&!is_ds[i]) {
8466                 assert(regs[i].regmap[hr]<64);
8467                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8468                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8469                 {
8470                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8471                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8472                 }
8473                 regmap_pre[i+1][hr]=-1;
8474                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8475                 regs[i+1].wasconst&=~(1<<hr);
8476               }
8477               regs[i].regmap[hr]=-1;
8478               regs[i].isconst&=~(1<<hr);
8479             }
8480           }
8481         }
8482       } // if needed
8483     } // for hr
8484   }
8485
8486   /* Pass 5 - Pre-allocate registers */
8487
8488   // If a register is allocated during a loop, try to allocate it for the
8489   // entire loop, if possible.  This avoids loading/storing registers
8490   // inside of the loop.
8491
8492   signed char f_regmap[HOST_REGS];
8493   clear_all_regs(f_regmap);
8494   for(i=0;i<slen-1;i++)
8495   {
8496     if(itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
8497     {
8498       if(ba[i]>=start && ba[i]<(start+i*4))
8499       if(itype[i+1]==NOP||itype[i+1]==MOV||itype[i+1]==ALU
8500       ||itype[i+1]==SHIFTIMM||itype[i+1]==IMM16||itype[i+1]==LOAD
8501       ||itype[i+1]==STORE||itype[i+1]==STORELR||itype[i+1]==C1LS
8502       ||itype[i+1]==SHIFT||itype[i+1]==COP1
8503       ||itype[i+1]==COP2||itype[i+1]==C2LS||itype[i+1]==C2OP)
8504       {
8505         int t=(ba[i]-start)>>2;
8506         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
8507         if(t<2||(itype[t-2]!=UJUMP&&itype[t-2]!=RJUMP)||rt1[t-2]!=31) // call/ret assumes no registers allocated
8508         for(hr=0;hr<HOST_REGS;hr++)
8509         {
8510           if(regs[i].regmap[hr]>=0) {
8511             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8512               // dealloc old register
8513               int n;
8514               for(n=0;n<HOST_REGS;n++)
8515               {
8516                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8517               }
8518               // and alloc new one
8519               f_regmap[hr]=regs[i].regmap[hr];
8520             }
8521           }
8522           if(branch_regs[i].regmap[hr]>=0) {
8523             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8524               // dealloc old register
8525               int n;
8526               for(n=0;n<HOST_REGS;n++)
8527               {
8528                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8529               }
8530               // and alloc new one
8531               f_regmap[hr]=branch_regs[i].regmap[hr];
8532             }
8533           }
8534           if(ooo[i]) {
8535             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8536               f_regmap[hr]=branch_regs[i].regmap[hr];
8537           }else{
8538             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8539               f_regmap[hr]=branch_regs[i].regmap[hr];
8540           }
8541           // Avoid dirty->clean transition
8542           #ifdef DESTRUCTIVE_WRITEBACK
8543           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;
8544           #endif
8545           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8546           // case above, however it's always a good idea.  We can't hoist the
8547           // load if the register was already allocated, so there's no point
8548           // wasting time analyzing most of these cases.  It only "succeeds"
8549           // when the mapping was different and the load can be replaced with
8550           // a mov, which is of negligible benefit.  So such cases are
8551           // skipped below.
8552           if(f_regmap[hr]>0) {
8553             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8554               int r=f_regmap[hr];
8555               for(j=t;j<=i;j++)
8556               {
8557                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8558                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8559                 assert(r < 64);
8560                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8561                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8562                   int k;
8563                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8564                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8565                     if(r>63) {
8566                       if(get_reg(regs[i].regmap,r&63)<0) break;
8567                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8568                     }
8569                     k=i;
8570                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8571                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8572                         //printf("no free regs for store %x\n",start+(k-1)*4);
8573                         break;
8574                       }
8575                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8576                         //printf("no-match due to different register\n");
8577                         break;
8578                       }
8579                       if(itype[k-2]==UJUMP||itype[k-2]==RJUMP||itype[k-2]==CJUMP||itype[k-2]==SJUMP) {
8580                         //printf("no-match due to branch\n");
8581                         break;
8582                       }
8583                       // call/ret fast path assumes no registers allocated
8584                       if(k>2&&(itype[k-3]==UJUMP||itype[k-3]==RJUMP)&&rt1[k-3]==31) {
8585                         break;
8586                       }
8587                       assert(r < 64);
8588                       k--;
8589                     }
8590                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8591                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8592                       while(k<i) {
8593                         regs[k].regmap_entry[hr]=f_regmap[hr];
8594                         regs[k].regmap[hr]=f_regmap[hr];
8595                         regmap_pre[k+1][hr]=f_regmap[hr];
8596                         regs[k].wasdirty&=~(1<<hr);
8597                         regs[k].dirty&=~(1<<hr);
8598                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8599                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8600                         regs[k].wasconst&=~(1<<hr);
8601                         regs[k].isconst&=~(1<<hr);
8602                         k++;
8603                       }
8604                     }
8605                     else {
8606                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8607                       break;
8608                     }
8609                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8610                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8611                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8612                       regs[i].regmap_entry[hr]=f_regmap[hr];
8613                       regs[i].regmap[hr]=f_regmap[hr];
8614                       regs[i].wasdirty&=~(1<<hr);
8615                       regs[i].dirty&=~(1<<hr);
8616                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8617                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8618                       regs[i].wasconst&=~(1<<hr);
8619                       regs[i].isconst&=~(1<<hr);
8620                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8621                       branch_regs[i].wasdirty&=~(1<<hr);
8622                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8623                       branch_regs[i].regmap[hr]=f_regmap[hr];
8624                       branch_regs[i].dirty&=~(1<<hr);
8625                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8626                       branch_regs[i].wasconst&=~(1<<hr);
8627                       branch_regs[i].isconst&=~(1<<hr);
8628                       if (!is_ujump(i)) {
8629                         regmap_pre[i+2][hr]=f_regmap[hr];
8630                         regs[i+2].wasdirty&=~(1<<hr);
8631                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8632                       }
8633                     }
8634                   }
8635                   for(k=t;k<j;k++) {
8636                     // Alloc register clean at beginning of loop,
8637                     // but may dirty it in pass 6
8638                     regs[k].regmap_entry[hr]=f_regmap[hr];
8639                     regs[k].regmap[hr]=f_regmap[hr];
8640                     regs[k].dirty&=~(1<<hr);
8641                     regs[k].wasconst&=~(1<<hr);
8642                     regs[k].isconst&=~(1<<hr);
8643                     if(itype[k]==UJUMP||itype[k]==RJUMP||itype[k]==CJUMP||itype[k]==SJUMP) {
8644                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8645                       branch_regs[k].regmap[hr]=f_regmap[hr];
8646                       branch_regs[k].dirty&=~(1<<hr);
8647                       branch_regs[k].wasconst&=~(1<<hr);
8648                       branch_regs[k].isconst&=~(1<<hr);
8649                       if (!is_ujump(k)) {
8650                         regmap_pre[k+2][hr]=f_regmap[hr];
8651                         regs[k+2].wasdirty&=~(1<<hr);
8652                       }
8653                     }
8654                     else
8655                     {
8656                       regmap_pre[k+1][hr]=f_regmap[hr];
8657                       regs[k+1].wasdirty&=~(1<<hr);
8658                     }
8659                   }
8660                   if(regs[j].regmap[hr]==f_regmap[hr])
8661                     regs[j].regmap_entry[hr]=f_regmap[hr];
8662                   break;
8663                 }
8664                 if(j==i) break;
8665                 if(regs[j].regmap[hr]>=0)
8666                   break;
8667                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8668                   //printf("no-match due to different register\n");
8669                   break;
8670                 }
8671                 if (is_ujump(j))
8672                 {
8673                   // Stop on unconditional branch
8674                   break;
8675                 }
8676                 if(itype[j]==CJUMP||itype[j]==SJUMP)
8677                 {
8678                   if(ooo[j]) {
8679                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8680                       break;
8681                   }else{
8682                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8683                       break;
8684                   }
8685                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8686                     //printf("no-match due to different register (branch)\n");
8687                     break;
8688                   }
8689                 }
8690                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8691                   //printf("No free regs for store %x\n",start+j*4);
8692                   break;
8693                 }
8694                 assert(f_regmap[hr]<64);
8695               }
8696             }
8697           }
8698         }
8699       }
8700     }else{
8701       // Non branch or undetermined branch target
8702       for(hr=0;hr<HOST_REGS;hr++)
8703       {
8704         if(hr!=EXCLUDE_REG) {
8705           if(regs[i].regmap[hr]>=0) {
8706             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8707               // dealloc old register
8708               int n;
8709               for(n=0;n<HOST_REGS;n++)
8710               {
8711                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8712               }
8713               // and alloc new one
8714               f_regmap[hr]=regs[i].regmap[hr];
8715             }
8716           }
8717         }
8718       }
8719       // Try to restore cycle count at branch targets
8720       if(bt[i]) {
8721         for(j=i;j<slen-1;j++) {
8722           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8723           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8724             //printf("no free regs for store %x\n",start+j*4);
8725             break;
8726           }
8727         }
8728         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8729           int k=i;
8730           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8731           while(k<j) {
8732             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8733             regs[k].regmap[HOST_CCREG]=CCREG;
8734             regmap_pre[k+1][HOST_CCREG]=CCREG;
8735             regs[k+1].wasdirty|=1<<HOST_CCREG;
8736             regs[k].dirty|=1<<HOST_CCREG;
8737             regs[k].wasconst&=~(1<<HOST_CCREG);
8738             regs[k].isconst&=~(1<<HOST_CCREG);
8739             k++;
8740           }
8741           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8742         }
8743         // Work backwards from the branch target
8744         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8745         {
8746           //printf("Extend backwards\n");
8747           int k;
8748           k=i;
8749           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8750             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8751               //printf("no free regs for store %x\n",start+(k-1)*4);
8752               break;
8753             }
8754             k--;
8755           }
8756           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8757             //printf("Extend CC, %x ->\n",start+k*4);
8758             while(k<=i) {
8759               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8760               regs[k].regmap[HOST_CCREG]=CCREG;
8761               regmap_pre[k+1][HOST_CCREG]=CCREG;
8762               regs[k+1].wasdirty|=1<<HOST_CCREG;
8763               regs[k].dirty|=1<<HOST_CCREG;
8764               regs[k].wasconst&=~(1<<HOST_CCREG);
8765               regs[k].isconst&=~(1<<HOST_CCREG);
8766               k++;
8767             }
8768           }
8769           else {
8770             //printf("Fail Extend CC, %x ->\n",start+k*4);
8771           }
8772         }
8773       }
8774       if(itype[i]!=STORE&&itype[i]!=STORELR&&itype[i]!=C1LS&&itype[i]!=SHIFT&&
8775          itype[i]!=NOP&&itype[i]!=MOV&&itype[i]!=ALU&&itype[i]!=SHIFTIMM&&
8776          itype[i]!=IMM16&&itype[i]!=LOAD&&itype[i]!=COP1)
8777       {
8778         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8779       }
8780     }
8781   }
8782
8783   // This allocates registers (if possible) one instruction prior
8784   // to use, which can avoid a load-use penalty on certain CPUs.
8785   for(i=0;i<slen-1;i++)
8786   {
8787     if(!i||(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP))
8788     {
8789       if(!bt[i+1])
8790       {
8791         if(itype[i]==ALU||itype[i]==MOV||itype[i]==LOAD||itype[i]==SHIFTIMM||itype[i]==IMM16
8792            ||((itype[i]==COP1||itype[i]==COP2)&&opcode2[i]<3))
8793         {
8794           if(rs1[i+1]) {
8795             if((hr=get_reg(regs[i+1].regmap,rs1[i+1]))>=0)
8796             {
8797               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8798               {
8799                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8800                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8801                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8802                 regs[i].isconst&=~(1<<hr);
8803                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8804                 constmap[i][hr]=constmap[i+1][hr];
8805                 regs[i+1].wasdirty&=~(1<<hr);
8806                 regs[i].dirty&=~(1<<hr);
8807               }
8808             }
8809           }
8810           if(rs2[i+1]) {
8811             if((hr=get_reg(regs[i+1].regmap,rs2[i+1]))>=0)
8812             {
8813               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8814               {
8815                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8816                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8817                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8818                 regs[i].isconst&=~(1<<hr);
8819                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8820                 constmap[i][hr]=constmap[i+1][hr];
8821                 regs[i+1].wasdirty&=~(1<<hr);
8822                 regs[i].dirty&=~(1<<hr);
8823               }
8824             }
8825           }
8826           // Preload target address for load instruction (non-constant)
8827           if(itype[i+1]==LOAD&&rs1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8828             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8829             {
8830               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8831               {
8832                 regs[i].regmap[hr]=rs1[i+1];
8833                 regmap_pre[i+1][hr]=rs1[i+1];
8834                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8835                 regs[i].isconst&=~(1<<hr);
8836                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8837                 constmap[i][hr]=constmap[i+1][hr];
8838                 regs[i+1].wasdirty&=~(1<<hr);
8839                 regs[i].dirty&=~(1<<hr);
8840               }
8841             }
8842           }
8843           // Load source into target register
8844           if(lt1[i+1]&&get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8845             if((hr=get_reg(regs[i+1].regmap,rt1[i+1]))>=0)
8846             {
8847               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8848               {
8849                 regs[i].regmap[hr]=rs1[i+1];
8850                 regmap_pre[i+1][hr]=rs1[i+1];
8851                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8852                 regs[i].isconst&=~(1<<hr);
8853                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8854                 constmap[i][hr]=constmap[i+1][hr];
8855                 regs[i+1].wasdirty&=~(1<<hr);
8856                 regs[i].dirty&=~(1<<hr);
8857               }
8858             }
8859           }
8860           // Address for store instruction (non-constant)
8861           if(itype[i+1]==STORE||itype[i+1]==STORELR
8862              ||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8863             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8864               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8865               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8866               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8867               assert(hr>=0);
8868               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8869               {
8870                 regs[i].regmap[hr]=rs1[i+1];
8871                 regmap_pre[i+1][hr]=rs1[i+1];
8872                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8873                 regs[i].isconst&=~(1<<hr);
8874                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8875                 constmap[i][hr]=constmap[i+1][hr];
8876                 regs[i+1].wasdirty&=~(1<<hr);
8877                 regs[i].dirty&=~(1<<hr);
8878               }
8879             }
8880           }
8881           if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8882             if(get_reg(regs[i+1].regmap,rs1[i+1])<0) {
8883               int nr;
8884               hr=get_reg(regs[i+1].regmap,FTEMP);
8885               assert(hr>=0);
8886               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8887               {
8888                 regs[i].regmap[hr]=rs1[i+1];
8889                 regmap_pre[i+1][hr]=rs1[i+1];
8890                 regs[i+1].regmap_entry[hr]=rs1[i+1];
8891                 regs[i].isconst&=~(1<<hr);
8892                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8893                 constmap[i][hr]=constmap[i+1][hr];
8894                 regs[i+1].wasdirty&=~(1<<hr);
8895                 regs[i].dirty&=~(1<<hr);
8896               }
8897               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8898               {
8899                 // move it to another register
8900                 regs[i+1].regmap[hr]=-1;
8901                 regmap_pre[i+2][hr]=-1;
8902                 regs[i+1].regmap[nr]=FTEMP;
8903                 regmap_pre[i+2][nr]=FTEMP;
8904                 regs[i].regmap[nr]=rs1[i+1];
8905                 regmap_pre[i+1][nr]=rs1[i+1];
8906                 regs[i+1].regmap_entry[nr]=rs1[i+1];
8907                 regs[i].isconst&=~(1<<nr);
8908                 regs[i+1].isconst&=~(1<<nr);
8909                 regs[i].dirty&=~(1<<nr);
8910                 regs[i+1].wasdirty&=~(1<<nr);
8911                 regs[i+1].dirty&=~(1<<nr);
8912                 regs[i+2].wasdirty&=~(1<<nr);
8913               }
8914             }
8915           }
8916           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*/) {
8917             if(itype[i+1]==LOAD)
8918               hr=get_reg(regs[i+1].regmap,rt1[i+1]);
8919             if(itype[i+1]==LOADLR||(opcode[i+1]&0x3b)==0x31||(opcode[i+1]&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8920               hr=get_reg(regs[i+1].regmap,FTEMP);
8921             if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8922               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8923               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8924             }
8925             if(hr>=0&&regs[i].regmap[hr]<0) {
8926               int rs=get_reg(regs[i+1].regmap,rs1[i+1]);
8927               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8928                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8929                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8930                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8931                 regs[i].isconst&=~(1<<hr);
8932                 regs[i+1].wasdirty&=~(1<<hr);
8933                 regs[i].dirty&=~(1<<hr);
8934               }
8935             }
8936           }
8937         }
8938       }
8939     }
8940   }
8941
8942   /* Pass 6 - Optimize clean/dirty state */
8943   clean_registers(0,slen-1,1);
8944
8945   /* Pass 7 - Identify 32-bit registers */
8946   for (i=slen-1;i>=0;i--)
8947   {
8948     if(itype[i]==CJUMP||itype[i]==SJUMP)
8949     {
8950       // Conditional branch
8951       if((source[i]>>16)!=0x1000&&i<slen-2) {
8952         // Mark this address as a branch target since it may be called
8953         // upon return from interrupt
8954         bt[i+2]=1;
8955       }
8956     }
8957   }
8958
8959   if(itype[slen-1]==SPAN) {
8960     bt[slen-1]=1; // Mark as a branch target so instruction can restart after exception
8961   }
8962
8963 #ifdef DISASM
8964   /* Debug/disassembly */
8965   for(i=0;i<slen;i++)
8966   {
8967     printf("U:");
8968     int r;
8969     for(r=1;r<=CCREG;r++) {
8970       if((unneeded_reg[i]>>r)&1) {
8971         if(r==HIREG) printf(" HI");
8972         else if(r==LOREG) printf(" LO");
8973         else printf(" r%d",r);
8974       }
8975     }
8976     printf("\n");
8977     #if defined(__i386__) || defined(__x86_64__)
8978     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]);
8979     #endif
8980     #ifdef __arm__
8981     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]);
8982     #endif
8983     #if defined(__i386__) || defined(__x86_64__)
8984     printf("needs: ");
8985     if(needed_reg[i]&1) printf("eax ");
8986     if((needed_reg[i]>>1)&1) printf("ecx ");
8987     if((needed_reg[i]>>2)&1) printf("edx ");
8988     if((needed_reg[i]>>3)&1) printf("ebx ");
8989     if((needed_reg[i]>>5)&1) printf("ebp ");
8990     if((needed_reg[i]>>6)&1) printf("esi ");
8991     if((needed_reg[i]>>7)&1) printf("edi ");
8992     printf("\n");
8993     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]);
8994     printf("dirty: ");
8995     if(regs[i].wasdirty&1) printf("eax ");
8996     if((regs[i].wasdirty>>1)&1) printf("ecx ");
8997     if((regs[i].wasdirty>>2)&1) printf("edx ");
8998     if((regs[i].wasdirty>>3)&1) printf("ebx ");
8999     if((regs[i].wasdirty>>5)&1) printf("ebp ");
9000     if((regs[i].wasdirty>>6)&1) printf("esi ");
9001     if((regs[i].wasdirty>>7)&1) printf("edi ");
9002     #endif
9003     #ifdef __arm__
9004     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]);
9005     printf("dirty: ");
9006     if(regs[i].wasdirty&1) printf("r0 ");
9007     if((regs[i].wasdirty>>1)&1) printf("r1 ");
9008     if((regs[i].wasdirty>>2)&1) printf("r2 ");
9009     if((regs[i].wasdirty>>3)&1) printf("r3 ");
9010     if((regs[i].wasdirty>>4)&1) printf("r4 ");
9011     if((regs[i].wasdirty>>5)&1) printf("r5 ");
9012     if((regs[i].wasdirty>>6)&1) printf("r6 ");
9013     if((regs[i].wasdirty>>7)&1) printf("r7 ");
9014     if((regs[i].wasdirty>>8)&1) printf("r8 ");
9015     if((regs[i].wasdirty>>9)&1) printf("r9 ");
9016     if((regs[i].wasdirty>>10)&1) printf("r10 ");
9017     if((regs[i].wasdirty>>12)&1) printf("r12 ");
9018     #endif
9019     printf("\n");
9020     disassemble_inst(i);
9021     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
9022     #if defined(__i386__) || defined(__x86_64__)
9023     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]);
9024     if(regs[i].dirty&1) printf("eax ");
9025     if((regs[i].dirty>>1)&1) printf("ecx ");
9026     if((regs[i].dirty>>2)&1) printf("edx ");
9027     if((regs[i].dirty>>3)&1) printf("ebx ");
9028     if((regs[i].dirty>>5)&1) printf("ebp ");
9029     if((regs[i].dirty>>6)&1) printf("esi ");
9030     if((regs[i].dirty>>7)&1) printf("edi ");
9031     #endif
9032     #ifdef __arm__
9033     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]);
9034     if(regs[i].dirty&1) printf("r0 ");
9035     if((regs[i].dirty>>1)&1) printf("r1 ");
9036     if((regs[i].dirty>>2)&1) printf("r2 ");
9037     if((regs[i].dirty>>3)&1) printf("r3 ");
9038     if((regs[i].dirty>>4)&1) printf("r4 ");
9039     if((regs[i].dirty>>5)&1) printf("r5 ");
9040     if((regs[i].dirty>>6)&1) printf("r6 ");
9041     if((regs[i].dirty>>7)&1) printf("r7 ");
9042     if((regs[i].dirty>>8)&1) printf("r8 ");
9043     if((regs[i].dirty>>9)&1) printf("r9 ");
9044     if((regs[i].dirty>>10)&1) printf("r10 ");
9045     if((regs[i].dirty>>12)&1) printf("r12 ");
9046     #endif
9047     printf("\n");
9048     if(regs[i].isconst) {
9049       printf("constants: ");
9050       #if defined(__i386__) || defined(__x86_64__)
9051       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
9052       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
9053       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
9054       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
9055       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
9056       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
9057       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
9058       #endif
9059       #if defined(__arm__) || defined(__aarch64__)
9060       int r;
9061       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
9062         if ((regs[i].isconst >> r) & 1)
9063           printf(" r%d=%x", r, (u_int)constmap[i][r]);
9064       #endif
9065       printf("\n");
9066     }
9067     if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP) {
9068       #if defined(__i386__) || defined(__x86_64__)
9069       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]);
9070       if(branch_regs[i].dirty&1) printf("eax ");
9071       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9072       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9073       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9074       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9075       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9076       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9077       #endif
9078       #ifdef __arm__
9079       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]);
9080       if(branch_regs[i].dirty&1) printf("r0 ");
9081       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9082       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9083       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9084       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9085       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9086       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9087       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9088       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9089       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9090       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9091       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9092       #endif
9093     }
9094   }
9095 #endif // DISASM
9096
9097   /* Pass 8 - Assembly */
9098   linkcount=0;stubcount=0;
9099   ds=0;is_delayslot=0;
9100   u_int dirty_pre=0;
9101   void *beginning=start_block();
9102   if((u_int)addr&1) {
9103     ds=1;
9104     pagespan_ds();
9105   }
9106   void *instr_addr0_override = NULL;
9107
9108   if (start == 0x80030000) {
9109     // nasty hack for the fastbios thing
9110     // override block entry to this code
9111     instr_addr0_override = out;
9112     emit_movimm(start,0);
9113     // abuse io address var as a flag that we
9114     // have already returned here once
9115     emit_readword(&address,1);
9116     emit_writeword(0,&pcaddr);
9117     emit_writeword(0,&address);
9118     emit_cmp(0,1);
9119     #ifdef __aarch64__
9120     emit_jeq(out + 4*2);
9121     emit_far_jump(new_dyna_leave);
9122     #else
9123     emit_jne(new_dyna_leave);
9124     #endif
9125   }
9126   for(i=0;i<slen;i++)
9127   {
9128     //if(ds) printf("ds: ");
9129     disassemble_inst(i);
9130     if(ds) {
9131       ds=0; // Skip delay slot
9132       if(bt[i]) assem_debug("OOPS - branch into delay slot\n");
9133       instr_addr[i] = NULL;
9134     } else {
9135       speculate_register_values(i);
9136       #ifndef DESTRUCTIVE_WRITEBACK
9137       if (i < 2 || !is_ujump(i-2))
9138       {
9139         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9140       }
9141       if((itype[i]==CJUMP||itype[i]==SJUMP)&&!likely[i]) {
9142         dirty_pre=branch_regs[i].dirty;
9143       }else{
9144         dirty_pre=regs[i].dirty;
9145       }
9146       #endif
9147       // write back
9148       if (i < 2 || !is_ujump(i-2))
9149       {
9150         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9151         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9152       }
9153       // branch target entry point
9154       instr_addr[i] = out;
9155       assem_debug("<->\n");
9156       drc_dbg_emit_do_cmp(i);
9157
9158       // load regs
9159       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9160         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9161       load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i],rs2[i]);
9162       address_generation(i,&regs[i],regs[i].regmap_entry);
9163       load_consts(regmap_pre[i],regs[i].regmap,i);
9164       if(itype[i]==RJUMP||itype[i]==UJUMP||itype[i]==CJUMP||itype[i]==SJUMP)
9165       {
9166         // Load the delay slot registers if necessary
9167         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i]&&(rs1[i+1]!=rt1[i]||rt1[i]==0))
9168           load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
9169         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))
9170           load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
9171         if(itype[i+1]==STORE||itype[i+1]==STORELR||(opcode[i+1]&0x3b)==0x39||(opcode[i+1]&0x3b)==0x3a)
9172           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9173       }
9174       else if(i+1<slen)
9175       {
9176         // Preload registers for following instruction
9177         if(rs1[i+1]!=rs1[i]&&rs1[i+1]!=rs2[i])
9178           if(rs1[i+1]!=rt1[i]&&rs1[i+1]!=rt2[i])
9179             load_regs(regs[i].regmap_entry,regs[i].regmap,rs1[i+1],rs1[i+1]);
9180         if(rs2[i+1]!=rs1[i+1]&&rs2[i+1]!=rs1[i]&&rs2[i+1]!=rs2[i])
9181           if(rs2[i+1]!=rt1[i]&&rs2[i+1]!=rt2[i])
9182             load_regs(regs[i].regmap_entry,regs[i].regmap,rs2[i+1],rs2[i+1]);
9183       }
9184       // TODO: if(is_ooo(i)) address_generation(i+1);
9185       if(itype[i]==CJUMP)
9186         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9187       if(itype[i]==STORE||itype[i]==STORELR||(opcode[i]&0x3b)==0x39||(opcode[i]&0x3b)==0x3a)
9188         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9189       // assemble
9190       switch(itype[i]) {
9191         case ALU:
9192           alu_assemble(i,&regs[i]);break;
9193         case IMM16:
9194           imm16_assemble(i,&regs[i]);break;
9195         case SHIFT:
9196           shift_assemble(i,&regs[i]);break;
9197         case SHIFTIMM:
9198           shiftimm_assemble(i,&regs[i]);break;
9199         case LOAD:
9200           load_assemble(i,&regs[i]);break;
9201         case LOADLR:
9202           loadlr_assemble(i,&regs[i]);break;
9203         case STORE:
9204           store_assemble(i,&regs[i]);break;
9205         case STORELR:
9206           storelr_assemble(i,&regs[i]);break;
9207         case COP0:
9208           cop0_assemble(i,&regs[i]);break;
9209         case COP1:
9210           cop1_assemble(i,&regs[i]);break;
9211         case C1LS:
9212           c1ls_assemble(i,&regs[i]);break;
9213         case COP2:
9214           cop2_assemble(i,&regs[i]);break;
9215         case C2LS:
9216           c2ls_assemble(i,&regs[i]);break;
9217         case C2OP:
9218           c2op_assemble(i,&regs[i]);break;
9219         case MULTDIV:
9220           multdiv_assemble(i,&regs[i]);
9221           multdiv_prepare_stall(i,&regs[i]);
9222           break;
9223         case MOV:
9224           mov_assemble(i,&regs[i]);break;
9225         case SYSCALL:
9226           syscall_assemble(i,&regs[i]);break;
9227         case HLECALL:
9228           hlecall_assemble(i,&regs[i]);break;
9229         case INTCALL:
9230           intcall_assemble(i,&regs[i]);break;
9231         case UJUMP:
9232           ujump_assemble(i,&regs[i]);ds=1;break;
9233         case RJUMP:
9234           rjump_assemble(i,&regs[i]);ds=1;break;
9235         case CJUMP:
9236           cjump_assemble(i,&regs[i]);ds=1;break;
9237         case SJUMP:
9238           sjump_assemble(i,&regs[i]);ds=1;break;
9239         case SPAN:
9240           pagespan_assemble(i,&regs[i]);break;
9241       }
9242       if (is_ujump(i))
9243         literal_pool(1024);
9244       else
9245         literal_pool_jumpover(256);
9246     }
9247   }
9248   //assert(is_ujump(i-2));
9249   // If the block did not end with an unconditional branch,
9250   // add a jump to the next instruction.
9251   if(i>1) {
9252     if(!is_ujump(i-2)&&itype[i-1]!=SPAN) {
9253       assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
9254       assert(i==slen);
9255       if(itype[i-2]!=CJUMP&&itype[i-2]!=SJUMP) {
9256         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9257         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9258           emit_loadreg(CCREG,HOST_CCREG);
9259         emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9260       }
9261       else if(!likely[i-2])
9262       {
9263         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9264         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9265       }
9266       else
9267       {
9268         store_regs_bt(regs[i-2].regmap,regs[i-2].dirty,start+i*4);
9269         assert(regs[i-2].regmap[HOST_CCREG]==CCREG);
9270       }
9271       add_to_linker(out,start+i*4,0);
9272       emit_jmp(0);
9273     }
9274   }
9275   else
9276   {
9277     assert(i>0);
9278     assert(itype[i-1]!=UJUMP&&itype[i-1]!=CJUMP&&itype[i-1]!=SJUMP&&itype[i-1]!=RJUMP);
9279     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9280     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9281       emit_loadreg(CCREG,HOST_CCREG);
9282     emit_addimm(HOST_CCREG,CLOCK_ADJUST(ccadj[i-1]+1),HOST_CCREG);
9283     add_to_linker(out,start+i*4,0);
9284     emit_jmp(0);
9285   }
9286
9287   // TODO: delay slot stubs?
9288   // Stubs
9289   for(i=0;i<stubcount;i++)
9290   {
9291     switch(stubs[i].type)
9292     {
9293       case LOADB_STUB:
9294       case LOADH_STUB:
9295       case LOADW_STUB:
9296       case LOADD_STUB:
9297       case LOADBU_STUB:
9298       case LOADHU_STUB:
9299         do_readstub(i);break;
9300       case STOREB_STUB:
9301       case STOREH_STUB:
9302       case STOREW_STUB:
9303       case STORED_STUB:
9304         do_writestub(i);break;
9305       case CC_STUB:
9306         do_ccstub(i);break;
9307       case INVCODE_STUB:
9308         do_invstub(i);break;
9309       case FP_STUB:
9310         do_cop1stub(i);break;
9311       case STORELR_STUB:
9312         do_unalignedwritestub(i);break;
9313     }
9314   }
9315
9316   if (instr_addr0_override)
9317     instr_addr[0] = instr_addr0_override;
9318
9319   /* Pass 9 - Linker */
9320   for(i=0;i<linkcount;i++)
9321   {
9322     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9323     literal_pool(64);
9324     if (!link_addr[i].ext)
9325     {
9326       void *stub = out;
9327       void *addr = check_addr(link_addr[i].target);
9328       emit_extjump(link_addr[i].addr, link_addr[i].target);
9329       if (addr) {
9330         set_jump_target(link_addr[i].addr, addr);
9331         add_link(link_addr[i].target,stub);
9332       }
9333       else
9334         set_jump_target(link_addr[i].addr, stub);
9335     }
9336     else
9337     {
9338       // Internal branch
9339       int target=(link_addr[i].target-start)>>2;
9340       assert(target>=0&&target<slen);
9341       assert(instr_addr[target]);
9342       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9343       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9344       //#else
9345       set_jump_target(link_addr[i].addr, instr_addr[target]);
9346       //#endif
9347     }
9348   }
9349   // External Branch Targets (jump_in)
9350   if(copy+slen*4>(void *)shadow+sizeof(shadow)) copy=shadow;
9351   for(i=0;i<slen;i++)
9352   {
9353     if(bt[i]||i==0)
9354     {
9355       if(instr_addr[i]) // TODO - delay slots (=null)
9356       {
9357         u_int vaddr=start+i*4;
9358         u_int page=get_page(vaddr);
9359         u_int vpage=get_vpage(vaddr);
9360         literal_pool(256);
9361         {
9362           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9363           assem_debug("jump_in: %x\n",start+i*4);
9364           ll_add(jump_dirty+vpage,vaddr,out);
9365           void *entry_point = do_dirty_stub(i);
9366           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9367           // If there was an existing entry in the hash table,
9368           // replace it with the new address.
9369           // Don't add new entries.  We'll insert the
9370           // ones that actually get used in check_addr().
9371           struct ht_entry *ht_bin = hash_table_get(vaddr);
9372           if (ht_bin->vaddr[0] == vaddr)
9373             ht_bin->tcaddr[0] = entry_point;
9374           if (ht_bin->vaddr[1] == vaddr)
9375             ht_bin->tcaddr[1] = entry_point;
9376         }
9377       }
9378     }
9379   }
9380   // Write out the literal pool if necessary
9381   literal_pool(0);
9382   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9383   // Align code
9384   if(((u_int)out)&7) emit_addnop(13);
9385   #endif
9386   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9387   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9388   memcpy(copy,source,slen*4);
9389   copy+=slen*4;
9390
9391   end_block(beginning);
9392
9393   // If we're within 256K of the end of the buffer,
9394   // start over from the beginning. (Is 256K enough?)
9395   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9396     out = ndrc->translation_cache;
9397
9398   // Trap writes to any of the pages we compiled
9399   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9400     invalid_code[i]=0;
9401   }
9402   inv_code_start=inv_code_end=~0;
9403
9404   // for PCSX we need to mark all mirrors too
9405   if(get_page(start)<(RAM_SIZE>>12))
9406     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9407       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9408       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9409       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9410
9411   /* Pass 10 - Free memory by expiring oldest blocks */
9412
9413   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9414   while(expirep!=end)
9415   {
9416     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9417     uintptr_t base=(uintptr_t)ndrc->translation_cache+((expirep>>13)<<shift); // Base address of this block
9418     inv_debug("EXP: Phase %d\n",expirep);
9419     switch((expirep>>11)&3)
9420     {
9421       case 0:
9422         // Clear jump_in and jump_dirty
9423         ll_remove_matching_addrs(jump_in+(expirep&2047),base,shift);
9424         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base,shift);
9425         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base,shift);
9426         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base,shift);
9427         break;
9428       case 1:
9429         // Clear pointers
9430         ll_kill_pointers(jump_out[expirep&2047],base,shift);
9431         ll_kill_pointers(jump_out[(expirep&2047)+2048],base,shift);
9432         break;
9433       case 2:
9434         // Clear hash table
9435         for(i=0;i<32;i++) {
9436           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9437           if (((uintptr_t)ht_bin->tcaddr[1]>>shift) == (base>>shift) ||
9438              (((uintptr_t)ht_bin->tcaddr[1]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9439             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9440             ht_bin->vaddr[1] = -1;
9441             ht_bin->tcaddr[1] = NULL;
9442           }
9443           if (((uintptr_t)ht_bin->tcaddr[0]>>shift) == (base>>shift) ||
9444              (((uintptr_t)ht_bin->tcaddr[0]-MAX_OUTPUT_BLOCK_SIZE)>>shift)==(base>>shift)) {
9445             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9446             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9447             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9448             ht_bin->vaddr[1] = -1;
9449             ht_bin->tcaddr[1] = NULL;
9450           }
9451         }
9452         break;
9453       case 3:
9454         // Clear jump_out
9455         if((expirep&2047)==0)
9456           do_clear_cache();
9457         ll_remove_matching_addrs(jump_out+(expirep&2047),base,shift);
9458         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base,shift);
9459         break;
9460     }
9461     expirep=(expirep+1)&65535;
9462   }
9463   return 0;
9464 }
9465
9466 // vim:shiftwidth=2:expandtab